问:
Link inside clickable div
I have a link inside a clickable div like this:

HTML:

```<code><div onClick="goToCat(2);" class="author-topics-block ">
    <a href="http://mywebsite/page/?cat=2">The woman in steel</a>
</div>
</code>```

CSS:

```<code>.author-topics-block {
    cursor: pointer;
    text-align: center;
    line-height:26px;
    padding: 0 10px 0 10px;
    font-size: 15px;
    font-family: Oswald;
    border-bottom: 4px solid transparent;
}
</code>```

JS:

```<code>function goToCat(catId) {
  window.location.href = "http://mywebsite/page/?cat=" + catId;
}
</code>```

How do I prevent a click from triggering both on the div and on the link?

I want to keep the tag of the link href for search engines and the referencing.

答:
You could make the function return false to disable anchor href forwarding    </p>

```<code><div onClick=" return goToCat(2);" class="author-topics-block ">
  <a href="http://mywebsite/page/?cat=2">The woman in steel</a>
</div>

function goToCat(catId) {
  window.location.href = "http://mywebsite/page/?cat=" + catId;
  return false;
}
</code>```

Title: Link inside clickable div

Body:
I have a link inside a clickable div like this:

HTML:

    The woman in steel

CSS:

.author-topics-block {
    cursor: pointer;
    text-align: center;
    line-height:26px;
    padding: 0 10px 0 10px;
    font-size: 15px;
    font-family: Oswald;
    border-bottom: 4px solid transparent;
}

JS:

function goToCat(catId) {
  window.location.href = "http://mywebsite/page/?cat=" + catId;
}

How do I prevent a click from triggering both on the div and on the link?

I want to keep the tag of the link <a href for search engines and the referencing.

Body:
You could make the function return false to disable anchor href forwarding

<div onClick=" return goToCat(2);" class="author-topics-block ">
  <a href="http://mywebsite/page/?cat=2">The woman in steel</a>
</div>

function goToCat(catId) {
  window.location.href = "http://mywebsite/page/?cat=" + catId;
  return false;
}


来源: stackexchange

问:
Ruby - Filtering array of hashes based on another array
I am trying to filter an array of hashes based on another array. What's the best way to accomplish this? Here are the 2 brutes I've right now:

```<code>x=[1,2,3]
y = [{dis:4,as:"hi"},{dis:2,as:"li"}]

1) aa = []
x.each do |a|
  qq = y.select{|k,v| k[:dis]==a}
  aa+=qq unless qq.empty?
end

2) q = []
y.each do |k,v|
  x.each do |ele|
    if k[:dis]==ele
      q << {dis: ele,as: k[:as]}
    end
  end
end
</code>```

Here's the output I'm intending:

[{dis:2,as:"li"}]

答:
If you want to select only the elements where the value of :dis is included in x:

```<code>y.select{|h| x.include? h[:dis]}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to filter an array of hashes based on another array. What's the best way to accomplish this? Here are the 2 brutes I've right now:

x=[1,2,3]
y = [{dis:4,as:"hi"},{dis:2,as:"li"}]

1) aa = []
x.each do |a|
  qq = y.select{|k,v| k[:dis]==a}
  aa+=qq unless qq.empty?
end

2) q = []
y.each do |k,v|
  x.each do |ele|
    if k[:dis]==ele
      q << {dis: ele,as: k[:as]}
    end
  end
end

Here's the output I'm intending:

[{dis:2,as:"li"}]

Body:
If you want to select only the elements where the value of :dis is included in x:

y.select{|h| x.include? h[:dis]}


问:
Elmah.MVC + NLog - store all errors in one place
I'm working on an ASP.NET MVC 5 app in Visual Studio 2015. We use NLog to write some errors and other information to the database in our try/catch blocks. However, it would be nice to also implement ELMAH.MVC, so that any/all uncaught exceptions get caught/logged and the user redirected to a friendly page.

Here's our NLog table structure; note that ApplicationId is not equivalent to Application on the ELMAH_Error table; people apply for things through the app, and this is the ID we assign when they start the process. And RouteId is not an MVC route.

```<code>CREATE TABLE [dbo].[Log](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ApplicationId] [int] NULL,
    [RouteId] [int] NULL,
    [MachineName] [varchar](50) NULL,
    [TimeStamp] [datetime2](7) NULL,
    [LogLevel] [varchar](5) NULL,
    [Logger] [nvarchar](max) NULL,
    [Message] [nvarchar](max) NULL,
    [Exception] [nvarchar](max) NULL,
    [StackTrace] [nvarchar](max) NULL,
 CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
</code>```

The SQL for ELMAH's table looks like this (from the script here):

```<code>CREATE TABLE [dbo].[ELMAH_Error]
(
    [ErrorId]     UNIQUEIDENTIFIER NOT NULL,
    [Application] NVARCHAR(60)  COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Host]        NVARCHAR(50)  COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Type]        NVARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Source]      NVARCHAR(60)  COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Message]     NVARCHAR(500) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [User]        NVARCHAR(50)  COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [StatusCode]  INT NOT NULL,
    [TimeUtc]     DATETIME NOT NULL,
    [Sequence]    INT IDENTITY (1, 1) NOT NULL,
    [AllXml]      NTEXT COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
)
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
</code>```

Is it possible to have the ELMAH_Error table contain the additional columns found on the NLog Log table, or vice versa? How can I write errors from NLog to the ELMAH table?

Thank you.

Update 1: Came across this: https://github.com/ccellar/nlog-elmah-target, but it lacks any documentation on how you use it. Would this redirect all NLog exceptions to ELMAH?

Update 2: A related question has been asked about adding the Exception.Data dictionary to ELMAH. This way, any number of key/value pairs can be added to what Elmah stored. This way, all the data now stored with NLog would be stored on ELMAH.

答:
Found a solution that works very nicely: https://github.com/NLog/NLog.Elmah/

To install,

Install-Package NLog.Elmah

Update-Package NLog

I also installed NLog.Web package, but isn't required for this.

Modify NLog.config to include:

<targets><target name="target1" xsi:type="Elmah" LogLevelAsType"false" /></targets>
    <rules><logger name="*" minlevel="Info" writeTo="target1" /></rules>
```

<p>Now just decorate any controller/class that uses NLog with the target:</p>

```[Target("Elmah")]
public class HomeController : Controller
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();
    public ActionResult Index()
    {
        // Other code...

        var logEvent = new LogEventInfo(LogLevel.Info, _logger.Name, "Some information...");
        _logger.Log(logEvent);

        // Other code...
    }
}
```

You can also throw the attribute on a base controller/class and cover all your application.

Body:
I'm working on an ASP.NET MVC 5 app in Visual Studio 2015. We use NLog to write some errors and other information to the database in our try/catch blocks. However, it would be nice to also implement ELMAH.MVC, so that any/all uncaught exceptions get caught/logged and the user redirected to a friendly page.

Here's our NLog table structure; note that ApplicationId is not equivalent to Application on the ELMAH_Error table; people apply for things through the app, and this is the ID we assign when they start the process. And RouteId is not an MVC route.

CREATE TABLE [dbo].[Log](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ApplicationId] [int] NULL,
    [RouteId] [int] NULL,
    [MachineName] [varchar](50) NULL,
    [TimeStamp] [datetime2](7) NULL,
    [LogLevel] [varchar](5) NULL,
    [Logger] [nvarchar](max) NULL,
    [Message] [nvarchar](max) NULL,
    [Exception] [nvarchar](max) NULL,
    [StackTrace] [nvarchar](max) NULL,
 CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

The SQL for ELMAH's table looks like this (from the script here):

CREATE TABLE [dbo].[ELMAH_Error]
(
    [ErrorId]     UNIQUEIDENTIFIER NOT NULL,
    [Application] NVARCHAR(60)  COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Host]        NVARCHAR(50)  COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Type]        NVARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Source]      NVARCHAR(60)  COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [Message]     NVARCHAR(500) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [User]        NVARCHAR(50)  COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
    [StatusCode]  INT NOT NULL,
    [TimeUtc]     DATETIME NOT NULL,
    [Sequence]    INT IDENTITY (1, 1) NOT NULL,
    [AllXml]      NTEXT COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
)
ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Is it possible to have the ELMAH_Error table contain the additional columns found on the NLog Log table, or vice versa? How can I write errors from NLog to the ELMAH table?

Thank you.

Update 1: Came across this: https://github.com/ccellar/nlog-elmah-target, but it lacks any documentation on how you use it. Would this redirect all NLog exceptions to ELMAH?

Update 2: A related question has been asked about adding the Exception.Data dictionary to ELMAH. This way, any number of key/value pairs can be added to what Elmah stored. This way, all the data now stored with NLog would be stored on ELMAH.

Body:
Found a solution that works very nicely: https://github.com/NLog/NLog.Elmah/

To install,

Install-Package NLog.Elmah

Update-Package NLog

I also installed NLog.Web package, but isn't required for this.

Modify NLog.config to include:

<targets><target name="target1" xsi:type="Elmah" LogLevelAsType"false" /></targets>
    <rules><logger name="*" minlevel="Info" writeTo="target1" /></rules>

Now just decorate any controller/class that uses NLog with the target:

[Target("Elmah")]
public class HomeController : Controller
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();
    public ActionResult Index()
    {
        // Other code...

        var logEvent = new LogEventInfo(LogLevel.Info, _logger.Name, "Some information...");
        _logger.Log(logEvent);

        // Other code...
    }
}

You can also throw the attribute on a base controller/class and cover all your application.


问:
WPF - Binding problem
Why after clicking the button the text in the textblock doesn't change ?

XAML:

```<code> <Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <TextBlock Text="{Binding Name}"/>
    <Button Click="Button_Click" Grid.Row="1" Margin="20">Click Me</Button>
</Grid>
</code>```

Code behind:

```<code>  public partial class Window1 : Window, INotifyPropertyChanged
{
    private Person _myPerson;
    public Person MyPerson
    {
        get { return _myPerson; }
        set
        {
            _myPerson = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("MyPerson"));
            }
        }
    }

    public Window1()
    {
        MyPerson = new Person { Name = "A" };
        DataContext = MyPerson;
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyPerson = new Person { Name = "B" };
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}
</code>```

答:
You need to implement INotifyPropertyChanged on Person class and then just change the name of MyPerson raising PropertyChanged, if you want it to be cleaner...

Or You can re-apply the newly created object you have created to the DataContext, or it won't work

ContentLicense: CC BY-SA 2.5

Title: WPF - Binding problem

Body:
Why after clicking the button the text in the textblock doesn't change ?

XAML:

 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>

    <TextBlock Text="{Binding Name}"/>
    <Button Click="Button_Click" Grid.Row="1" Margin="20">Click Me</Button>
</Grid>

Code behind:

  public partial class Window1 : Window, INotifyPropertyChanged
{
    private Person _myPerson;
    public Person MyPerson
    {
        get { return _myPerson; }
        set
        {
            _myPerson = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("MyPerson"));
            }
        }
    }

    public Window1()
    {
        MyPerson = new Person { Name = "A" };
        DataContext = MyPerson;
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyPerson = new Person { Name = "B" };
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}


问:
Dynamically Loading an ASP.NET Core Assembly
I am trying to dynamically load a .NET Core DLL containing an ASP.NET Core's Startup class. I then want to instantiate the Startup class and hand it over to the TestHost API, so I can start the site in memory. I've written the following code:

```<code>var directoryPath = @"C:\Dlls";
var assemblyFilePath = Path.Combine(directoryPath, "Foo.dll");
var assemblyName = AssemblyLoadContext.GetAssemblyName(assemblyFilePath);
var assembly = new AssemblyLoader(directoryPath).LoadFromAssemblyName(assemblyName);
var startupType = assembly.ExportedTypes
    .FirstOrDefault(x => string.Equals(x.Name, "Startup"));
var webHostBuilder = new WebHostBuilder()
    .UseStartup(startupType)
    .UseUrls(new string[] { "http://localhost" });
using (var testServer = new TestServer(webHostBuilder))
{
    var response = testServer.CreateClient().GetAsync("/");
}

public class AssemblyLoader : AssemblyLoadContext
{
    private readonly string directoryPath;

    public AssemblyLoader(string directoryPath) =>
        this.directoryPath = directoryPath;

    protected override Assembly Load(AssemblyName assemblyName)
    {
        var dependencyContext = DependencyContext.Default;
        var compilationLibraries = dependencyContext
            .CompileLibraries
            .Where(x => x.Name.Contains(assemblyName.Name))
            .ToList();
        if (compilationLibraries.Count > 0)
        {
            return Assembly.Load(new AssemblyName(compilationLibraries.First().Name));
        }
        else
        {
            var file = new FileInfo($"{this.directoryPath}{Path.DirectorySeparatorChar}{assemblyName.Name}.dll");
            if (File.Exists(file.FullName))
            {
                var asemblyLoader = new AssemblyLoader(file.DirectoryName);
                return asemblyLoader.LoadFromAssemblyPath(file.FullName);
            }
        }

        return Assembly.Load(assemblyName);
    }
}
</code>```

However, this throws a TypeLoadException when assembly.ExportedTypes is called. The full stack trace:

System.TypeLoadException occurred   HResult=0x80131522

  Message=Method 'ConfigureServices' in type 'Foo.Startup' from assembly
  'Foo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not
  have an implementation.   Source=   StackTrace:    at
  System.Reflection.RuntimeAssembly.GetExportedTypes(RuntimeAssembly
  assembly, ObjectHandleOnStack retTypes)    at
  System.Reflection.RuntimeAssembly.GetExportedTypes()

I think it's having trouble loading the ASP.NET Core and other third party DLL's like Newtonsoft.Json.

答:
I am not happy with this answer put I'll post it incase it helps someone.

I was doing a dotnet publish and then trying to run my app from the published output. I managed to get it working by publishing a self contained app using the following command instead:

```<code>dotnet publish --self-contained --framework netcoreapp1.1 --runtime win7-x64
</code>```

A self contained app contains all assemblies required to run the app including the .NET Core runtime. I wanted to avoid having to do this as it requires you to know the runtime identifier (RID) and what platform you are running n before hand.

Given the knowledge that my code above is missing .NET Core runtime assemblies, I've tried to load assemblies from the .NET Core runtime folder but this has failed for me so far.

Body:
I am trying to dynamically load a .NET Core DLL containing an ASP.NET Core's Startup class. I then want to instantiate the Startup class and hand it over to the TestHost API, so I can start the site in memory. I've written the following code:

var directoryPath = @"C:\Dlls";
var assemblyFilePath = Path.Combine(directoryPath, "Foo.dll");
var assemblyName = AssemblyLoadContext.GetAssemblyName(assemblyFilePath);
var assembly = new AssemblyLoader(directoryPath).LoadFromAssemblyName(assemblyName);
var startupType = assembly.ExportedTypes
    .FirstOrDefault(x => string.Equals(x.Name, "Startup"));
var webHostBuilder = new WebHostBuilder()
    .UseStartup(startupType)
    .UseUrls(new string[] { "http://localhost" });
using (var testServer = new TestServer(webHostBuilder))
{
    var response = testServer.CreateClient().GetAsync("/");
}

public class AssemblyLoader : AssemblyLoadContext
{
    private readonly string directoryPath;

    public AssemblyLoader(string directoryPath) =>
        this.directoryPath = directoryPath;

    protected override Assembly Load(AssemblyName assemblyName)
    {
        var dependencyContext = DependencyContext.Default;
        var compilationLibraries = dependencyContext
            .CompileLibraries
            .Where(x => x.Name.Contains(assemblyName.Name))
            .ToList();
        if (compilationLibraries.Count > 0)
        {
            return Assembly.Load(new AssemblyName(compilationLibraries.First().Name));
        }
        else
        {
            var file = new FileInfo($"{this.directoryPath}{Path.DirectorySeparatorChar}{assemblyName.Name}.dll");
            if (File.Exists(file.FullName))
            {
                var asemblyLoader = new AssemblyLoader(file.DirectoryName);
                return asemblyLoader.LoadFromAssemblyPath(file.FullName);
            }
        }

        return Assembly.Load(assemblyName);
    }
}

However, this throws a TypeLoadException when assembly.ExportedTypes is called. The full stack trace:

System.TypeLoadException occurred   HResult=0x80131522

  Message=Method 'ConfigureServices' in type 'Foo.Startup' from assembly
  'Foo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not
  have an implementation.   Source=   StackTrace:    at
  System.Reflection.RuntimeAssembly.GetExportedTypes(RuntimeAssembly
  assembly, ObjectHandleOnStack retTypes)    at
  System.Reflection.RuntimeAssembly.GetExportedTypes()

I think it's having trouble loading the ASP.NET Core and other third party DLL's like Newtonsoft.Json.

Body:
I am not happy with this answer put I'll post it incase it helps someone.

I was doing a dotnet publish and then trying to run my app from the published output. I managed to get it working by publishing a self contained app using the following command instead:

dotnet publish --self-contained --framework netcoreapp1.1 --runtime win7-x64

A self contained app contains all assemblies required to run the app including the .NET Core runtime. I wanted to avoid having to do this as it requires you to know the runtime identifier (RID) and what platform you are running n before hand.

Given the knowledge that my code above is missing .NET Core runtime assemblies, I've tried to load assemblies from the .NET Core runtime folder but this has failed for me so far.


问:
Django ManyToMany field get all values from an object without a 'for'
Is it possible to get the values of a ManyToMany from an object without using a 'for'?

models.py

```<code>class Citizenship(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "Citizenship"

    def __str__(self):
        return self.name

class Anexa(models.Model):
    name = models.CharField(max_length=150, help_text="3")
    citizenship = models.ManyToManyField(Citizenship, help_text="4")
</code>```

I have an Anexa object with the name Alex and i have 4 citizenships for this object. I'm searching for something equivalent to this:

```<code>for citizenships in x.citizenship.all():
    print(citizenships.name)
</code>```

答:
The closest you will get is a Values List https://docs.djangoproject.com/en/1.11/ref/models/querysets/#values-list, which you would still have to loop through to print individually.</p>

```<code>x.citizenship.values_list('name', flat=True)
</code>```

Body:
Is it possible to get the values of a ManyToMany from an object without using a 'for'?

models.py

class Citizenship(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "Citizenship"

    def __str__(self):
        return self.name

class Anexa(models.Model):
    name = models.CharField(max_length=150, help_text="3")
    citizenship = models.ManyToManyField(Citizenship, help_text="4")

I have an Anexa object with the name Alex and i have 4 citizenships for this object. I'm searching for something equivalent to this:

for citizenships in x.citizenship.all():
    print(citizenships.name)

Body:
The closest you will get is a Values List https://docs.djangoproject.com/en/1.11/ref/models/querysets/#values-list, which you would still have to loop through to print individually.

x.citizenship.values_list('name', flat=True)


问:
Filter a Kendo UI MVC Grid using checked items in a checkbox column
I have a Kendo UI MVC Grid where I'd like to add a special checkbox column.
This column will not be bound to a model but will be used like a sort of filter.

The idea is that users can check some rows and then click a button (for instance the filter icon in the column header). When clicked, the grid should collapse to the selected rows. The way I see it, it is an extra filter, but not the usual way.

The way my users will work with it would be about as follows:

They select a row and play the attached sound file for that row.

If the row holds an interesting sound file, they may check the checkbox and move to a new row -> 1.

After the selection with checkboxes is made, they will click on the checkbox column filter icon.

The selection will then collapse to the rows that were selected.

After this, the collapsed grid may be exported to excel, pdf or whatever…

A multi select grid is not an option as well as a checkboxed column filter because the selection is not instant, but a process over time.

I cannot find how I would make #4 work. Any suggestions? I don't need a complete solution, ideas are welcome.

答:
The best way is to add boolean 'util' property to your model and bind it to a checkbox column. Once your checkbox column will be bound, your button can execute:

```<code>dataSource.filter({ field:"Field", operator: "eq", value: true });
</code>```

As far I know - there is no build kendo way to manage filtering unbounded columns.

Body:
The best way is to add boolean 'util' property to your model and bind it to a checkbox column. Once your checkbox column will be bound, your button can execute:

dataSource.filter({ field:"Field", operator: "eq", value: true });

As far I know - there is no build kendo way to manage filtering unbounded columns.


问:
Update only edited/changed fields
I have a form that can be edited by users. When changes are made, I want only those changes to update. A member of staff has pressed "save" before the whole page has loaded meaning the script saw the form fields as being empty so replaced the fields with empty ones.

Current code is:

```<code>$res= mysql_query ("UPDATE table SET site='$site', the1='$the1' WHERE id='$id'");
</code>```

Appreciate the help here.....

答:
You need write javascript script for check data changes and send only changed data. For example, you can save previous data in data-prev-value attribute.

```<code><input type="text" name="my_field" id="field_id" value="old_value" data-prev-value="old_value">
</code>```

On submit, you compare

```<code>$('#field_id').val() != $('#field_id').attr('data-prev-value')
</code>```

and if they not equal add data to array and send it to server.

Title: Update only edited/changed fields

Body:
I have a form that can be edited by users. When changes are made, I want only those changes to update. A member of staff has pressed "save" before the whole page has loaded meaning the script saw the form fields as being empty so replaced the fields with empty ones.

Current code is:

$res= mysql_query ("UPDATE table SET site='$site', the1='$the1' WHERE id='$id'");

Appreciate the help here.....

Body:
You need write javascript script for check data changes and send only changed data. For example, you can save previous data in data-prev-value attribute.

<input type="text" name="my_field" id="field_id" value="old_value" data-prev-value="old_value">

On submit, you compare

$('#field_id').val() != $('#field_id').attr('data-prev-value')

and if they not equal add data to array and send it to server.


问:
expose heroku $PORT with gulp task
I am building a Docker image with the following Dockerfile

```<code>FROM node:latest

RUN npm install -g gulp

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

EXPOSE 5000

CMD ["gulp", "serveprod"]
</code>```

I know I need to expose the $PORT variable from the heroku documents.

However, I do not know how this works with gulp.

Here is my gulpfile.js and the serveprod task.

```<code>gulp.task('serveprod', function() {
    connect.server({
        root: './',
        port: $PORT || process.env.PORT || 5000, // localhost:5000
        livereload: false
    });
});
</code>```

Previously, I was using the node buildpack and all I needed for the port: was process.env.PORT and it would work just fine. I have tried adding the $PORT but this still isn't working.

UPDATE:

I just tried putting this in my Dockerfile

```<code>ENV 5000 $PORT
</code>```

Here are the Heroku logs:

```<code>2017-07-07T15:01:27.127275+00:00 heroku[web.1]: Starting process with command `gulp serveprod`
2017-07-07T15:01:29.985824+00:00 heroku[web.1]: State changed from starting to crashed
2017-07-07T15:01:29.875500+00:00 app[web.1]: module.js:487
2017-07-07T15:01:29.875515+00:00 app[web.1]:     throw err;
2017-07-07T15:01:29.875517+00:00 app[web.1]:     ^
2017-07-07T15:01:29.875517+00:00 app[web.1]:
2017-07-07T15:01:29.875518+00:00 app[web.1]: Error: Cannot find module './lib/_stream_readable.js'
2017-07-07T15:01:29.875519+00:00 app[web.1]:     at Function.Module._resolveFilename (module.js:485:15)
2017-07-07T15:01:29.875519+00:00 app[web.1]:     at Function.Module._load (module.js:437:25)
2017-07-07T15:01:29.875520+00:00 app[web.1]:     at Module.require (module.js:513:17)
2017-07-07T15:01:29.875521+00:00 app[web.1]:     at require (internal/module.js:11:18)
2017-07-07T15:01:29.875539+00:00 app[web.1]:     at Object.<anonymous> (/usr/local/lib/node_modules/gulp/node_modules/through2/node_modules/readable-stream/readable.js:12:30)
2017-07-07T15:01:29.875540+00:00 app[web.1]:     at Module._compile (module.js:569:30)
2017-07-07T15:01:29.875541+00:00 app[web.1]:     at Object.Module._extensions..js (module.js:580:10)
2017-07-07T15:01:29.875541+00:00 app[web.1]:     at Module.load (module.js:503:32)
2017-07-07T15:01:29.875542+00:00 app[web.1]:     at tryModuleLoad (module.js:466:12)
2017-07-07T15:01:29.875543+00:00 app[web.1]:     at Function.Module._load (module.js:458:3)
2017-07-07T15:01:29.971237+00:00 heroku[web.1]: Process exited with status 1
2017-07-07T15:01:32.103467+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=www.christopherdbolton.com request_id=469ad736-103a-461f-af20-91454a8a83f1 fwd="139.72.158.28" dyno= connect= service= status=503 bytes= protocol=http
2017-07-07T15:01:32.923798+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=www.christopherdbolton.com request_id=a5c0b8c4-69c7-4bd7-ab00-372fe625b2f8 fwd="139.72.158.28" dyno= connect= service= status=503 bytes= protocol=http
Disconnected from log stream. There may be events happening that you do not see here! Attempting to reconnect...
2017-07-07T15:01:29.875520+00:00 app[web.1]:     at Module.require (module.js:513:17)
2017-07-07T15:01:29.875521+00:00 app[web.1]:     at require (internal/module.js:11:18)
2017-07-07T15:01:29.875539+00:00 app[web.1]:     at Object.<anonymous> (/usr/local/lib/node_modules/gulp/node_modules/through2/node_modules/readable-stream/readable.js:12:30)
2017-07-07T15:01:29.875541+00:00 app[web.1]:     at Object.Module._extensions..js (module.js:580:10)
2017-07-07T15:01:29.875540+00:00 app[web.1]:     at Module._compile (module.js:569:30)
2017-07-07T15:01:29.875541+00:00 app[web.1]:     at Module.load (module.js:503:32)
2017-07-07T15:01:29.875542+00:00 app[web.1]:     at tryModuleLoad (module.js:466:12)
2017-07-07T15:01:29.875543+00:00 app[web.1]:     at Function.Module._load (module.js:458:3)
</code>```

答:
Instead of starting with gulp serveprod, start with npm start.

Here is the resulting Dockerfile:

```<code>FROM node:latest

RUN npm install -g gulp

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

CMD ["npm", "start"]
</code>```

Here is the package.json:

```<code>  "scripts": {
    "build": "gulp",
    "start": "gulp serveprod"
  }
</code>```

Title: expose heroku $PORT with gulp task

Body:
I am building a Docker image with the following Dockerfile

FROM node:latest

RUN npm install -g gulp

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

EXPOSE 5000

CMD ["gulp", "serveprod"]

I know I need to expose the $PORT variable from the heroku documents.

However, I do not know how this works with gulp.

Here is my gulpfile.js and the serveprod task.

gulp.task('serveprod', function() {
    connect.server({
        root: './',
        port: $PORT || process.env.PORT || 5000, // localhost:5000
        livereload: false
    });
});

Previously, I was using the node buildpack and all I needed for the port: was process.env.PORT and it would work just fine. I have tried adding the $PORT but this still isn't working.

UPDATE:

I just tried putting this in my Dockerfile

ENV 5000 $PORT

Here are the Heroku logs:

2017-07-07T15:01:27.127275+00:00 heroku[web.1]: Starting process with command `gulp serveprod`
2017-07-07T15:01:29.985824+00:00 heroku[web.1]: State changed from starting to crashed
2017-07-07T15:01:29.875500+00:00 app[web.1]: module.js:487
2017-07-07T15:01:29.875515+00:00 app[web.1]:     throw err;
2017-07-07T15:01:29.875517+00:00 app[web.1]:     ^
2017-07-07T15:01:29.875517+00:00 app[web.1]:
2017-07-07T15:01:29.875518+00:00 app[web.1]: Error: Cannot find module './lib/_stream_readable.js'
2017-07-07T15:01:29.875519+00:00 app[web.1]:     at Function.Module._resolveFilename (module.js:485:15)
2017-07-07T15:01:29.875519+00:00 app[web.1]:     at Function.Module._load (module.js:437:25)
2017-07-07T15:01:29.875520+00:00 app[web.1]:     at Module.require (module.js:513:17)
2017-07-07T15:01:29.875521+00:00 app[web.1]:     at require (internal/module.js:11:18)
2017-07-07T15:01:29.875539+00:00 app[web.1]:     at Object.<anonymous> (/usr/local/lib/node_modules/gulp/node_modules/through2/node_modules/readable-stream/readable.js:12:30)
2017-07-07T15:01:29.875540+00:00 app[web.1]:     at Module._compile (module.js:569:30)
2017-07-07T15:01:29.875541+00:00 app[web.1]:     at Object.Module._extensions..js (module.js:580:10)
2017-07-07T15:01:29.875541+00:00 app[web.1]:     at Module.load (module.js:503:32)
2017-07-07T15:01:29.875542+00:00 app[web.1]:     at tryModuleLoad (module.js:466:12)
2017-07-07T15:01:29.875543+00:00 app[web.1]:     at Function.Module._load (module.js:458:3)
2017-07-07T15:01:29.971237+00:00 heroku[web.1]: Process exited with status 1
2017-07-07T15:01:32.103467+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=www.christopherdbolton.com request_id=469ad736-103a-461f-af20-91454a8a83f1 fwd="139.72.158.28" dyno= connect= service= status=503 bytes= protocol=http
2017-07-07T15:01:32.923798+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=www.christopherdbolton.com request_id=a5c0b8c4-69c7-4bd7-ab00-372fe625b2f8 fwd="139.72.158.28" dyno= connect= service= status=503 bytes= protocol=http
Disconnected from log stream. There may be events happening that you do not see here! Attempting to reconnect...
2017-07-07T15:01:29.875520+00:00 app[web.1]:     at Module.require (module.js:513:17)
2017-07-07T15:01:29.875521+00:00 app[web.1]:     at require (internal/module.js:11:18)
2017-07-07T15:01:29.875539+00:00 app[web.1]:     at Object.<anonymous> (/usr/local/lib/node_modules/gulp/node_modules/through2/node_modules/readable-stream/readable.js:12:30)
2017-07-07T15:01:29.875541+00:00 app[web.1]:     at Object.Module._extensions..js (module.js:580:10)
2017-07-07T15:01:29.875540+00:00 app[web.1]:     at Module._compile (module.js:569:30)
2017-07-07T15:01:29.875541+00:00 app[web.1]:     at Module.load (module.js:503:32)
2017-07-07T15:01:29.875542+00:00 app[web.1]:     at tryModuleLoad (module.js:466:12)
2017-07-07T15:01:29.875543+00:00 app[web.1]:     at Function.Module._load (module.js:458:3)

Body:
Instead of starting with gulp serveprod, start with npm start.

Here is the resulting Dockerfile:

FROM node:latest

RUN npm install -g gulp

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
COPY . /usr/src/app

CMD ["npm", "start"]

Here is the package.json:

  "scripts": {
    "build": "gulp",
    "start": "gulp serveprod"
  }


问:
Ansible loop over range of letters in template
I'm trying to generate an Ansible template that increments on letters alphabetically rather than numbers.  Is there a function similar to range(x) that could help me?

pseudo code example

```<code>{% for letter in range(a, d) %}
{{ letter }}
{% endfor %}
</code>```

expected output

```<code>a
b
c
d
</code>```

Alternatively is there a way to convert a number into it's alphabetical equivalent in Ansible?

```<code>{% for i in range(6) %}
{{ convert(i) }}
{% endfor %}
</code>```

UPDATE

For those who are curious, here's how I ended up applying @zigam's solution.  The goal was to create xml tags with every host from a hostgroup.

In my role defaults:

```<code>ids: "ABCDEFGHIGJKLMNPQRSTUVWXYZ"
</code>```

In my template:

```<code>{% for host in groups['some_group'] %}
<host-id="{{ ids[loop.index] }}" hostName="{{ host }}" port="8888" />
{% endfor %}
</code>```

答:
You can iterate over a string:

```<code> {% for letter in 'abcd' %}
 {{ letter }}
 {% endfor %}
</code>```

If you want to iterate over a range of the alphabet:

```<code> {% set letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' %}
 {% for letter in letters[:6] %} {# first 6 chars #}
 {{ letter }}
 {% endfor %}
</code>```

Body:
I'm trying to generate an Ansible template that increments on letters alphabetically rather than numbers.  Is there a function similar to range(x) that could help me?

pseudo code example

{% for letter in range(a, d) %}
{{ letter }}
{% endfor %}

expected output

a
b
c
d

Alternatively is there a way to convert a number into it's alphabetical equivalent in Ansible?

{% for i in range(6) %}
{{ convert(i) }}
{% endfor %}

UPDATE

For those who are curious, here's how I ended up applying @zigam's solution.  The goal was to create xml tags with every host from a hostgroup.

In my role defaults:

ids: "ABCDEFGHIGJKLMNPQRSTUVWXYZ"

In my template:

{% for host in groups['some_group'] %}
<host-id="{{ ids[loop.index] }}" hostName="{{ host }}" port="8888" />
{% endfor %}

Body:
You can iterate over a string:

 {% for letter in 'abcd' %}
 {{ letter }}
 {% endfor %}

If you want to iterate over a range of the alphabet:

 {% set letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' %}
 {% for letter in letters[:6] %} {# first 6 chars #}
 {{ letter }}
 {% endfor %}


问:
FXML control always null when using Kotlin
Using IntelliJ I created a JavaFX application and then added Kotlin and Maven as frameworks to it. It came with a sample.fxml file and a Controller.java and Main.java. I created a new class for the controller in Kotlin (MainWindowController.kt) and renamed the sample.fxml file to MainWindow.fxml. I updated the MainWindow.fxml to look like:

```<code><?import javafx.scene.control.Label?>
<?import javafx.scene.layout.GridPane?>
<GridPane fx:controller="reader.MainWindowController" xmlns:fx="http://javafx.com/fxml" xmlns="http://javafx.com/javafx/8" alignment="center" hgap="10" vgap="10">
    <Label fx:id="helloLabel" text="Hello"/>
</GridPane>
</code>```

And in my MainWindowController.kt file I have:

```<code>package reader

import javafx.fxml.FXML
import javafx.scene.control.Label

class MainWindowController {

    @FXML var helloLabel: Label? = null

    init {
        println("Label is null? ${helloLabel == null}")
    }
}
</code>```

Here's my Main.java:

```<code>import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("MainWindow.fxml"));
        primaryStage.setTitle("My App");
        primaryStage.setScene(new Scene(root, 1000, 600));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

When I run the app the print line shows that the label is null but otherwise the window shows properly and I see the text from my label. The null is the problem I'm having. I haven't found much on using FXML with Kotlin and what I did find was a little out-dated and didn't appear to have an actual working solution.

Does anyone know why the label is null? I must be doing something wrong or misunderstanding something.

Edit: Here's what I have that now works thanks to the quick replies:

```<code>package reader

import javafx.fxml.FXML
import javafx.scene.control.Label

class MainWindowController {

    @FXML var helloLabel: Label? = null

    fun initialize() {
        println("Label is null? ${helloLabel == null}")
    }
}
</code>```

答:
As mentioned before. Check if fx:id is set.

Is also possible to use lateinit modifier.

Your code could looks like:

```<code>import javafx.fxml.FXML
import javafx.scene.control.Label

class MainWindowController {
    @FXML
    lateinit var helloLabel : Label
}
</code>```

Body:
Using IntelliJ I created a JavaFX application and then added Kotlin and Maven as frameworks to it. It came with a sample.fxml file and a Controller.java and Main.java. I created a new class for the controller in Kotlin (MainWindowController.kt) and renamed the sample.fxml file to MainWindow.fxml. I updated the MainWindow.fxml to look like:

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.GridPane?>
<GridPane fx:controller="reader.MainWindowController" xmlns:fx="http://javafx.com/fxml" xmlns="http://javafx.com/javafx/8" alignment="center" hgap="10" vgap="10">

</GridPane>

And in my MainWindowController.kt file I have:

package reader

import javafx.fxml.FXML
import javafx.scene.control.Label

class MainWindowController {

    @FXML var helloLabel: Label? = null

    init {
        println("Label is null? ${helloLabel == null}")
    }
}

Here's my Main.java:

import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("MainWindow.fxml"));
        primaryStage.setTitle("My App");
        primaryStage.setScene(new Scene(root, 1000, 600));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

When I run the app the print line shows that the label is null but otherwise the window shows properly and I see the text from my label. The null is the problem I'm having. I haven't found much on using FXML with Kotlin and what I did find was a little out-dated and didn't appear to have an actual working solution.

Does anyone know why the label is null? I must be doing something wrong or misunderstanding something.

Edit: Here's what I have that now works thanks to the quick replies:

package reader

import javafx.fxml.FXML
import javafx.scene.control.Label

class MainWindowController {

    @FXML var helloLabel: Label? = null

    fun initialize() {
        println("Label is null? ${helloLabel == null}")
    }
}

Body:
As mentioned before. Check if fx:id is set.

Is also possible to use lateinit modifier.

Your code could looks like:

import javafx.fxml.FXML
import javafx.scene.control.Label

class MainWindowController {
    @FXML
    lateinit var helloLabel : Label
}


问:
Firebase maximum projects and apps
How many applications can I create in one project from a single account and how many projects I can create in Firebase for Cloud Messaging?</p>

答:
About your second question

how many projects I can create in Firebase for Cloud Messaging?

For the Free plan, you can read this FAQ
https://support.google.com/cloud/answer/6330231?hl=en
It doesn't actually say how many, but explains how you can request more if necessary.

Title: Firebase maximum projects and apps


问:
WebPack: Change in module numbers do not change chunkhash
I am using webpack to bundle my files into two file: app.js and lib.js and I create and append unique chunkhash for each of my files that get download by browser. Both these files are built together in the same build output. It would look like this:

```<code>lib.747c2ee515b25d871bd0.js
app.e6a0b36a5bb2bff41393.js
</code>```

I have following caching set on these files:

```<code>Cache-Control:private, max-age=31536000
</code>```

This means that these files will be cached for an year or when a new file arrives. And this would work independently for each file.

Since our application is closer to release, there more changes in app than in lib.

Problem: The problem I am facing is that in a new build, contents of the lib are not changed but module ids are changed. This is causing module ids to change but chunkhash doesn't change; causing downloading of app but not lib resulting into broken app. On Ctrl+F5 everything starts working again as expected.

Questions: Isn't the changed module ids considered as part of chunkash? How do I fix this problem? Is it possible to add auto-increment explicit version number to file names through WebPack?

Any help will be much appreciated.

答:
The way I solved this is by adding one more number (which is Date.now()) into my file names as below.

```<code>filename: `[name].${Date.now().valueOf()}.[chunkhash].js`
</code>```

This works pretty reliably for foreseeable time. This is with an understanding that the value returned by Date.now().valueOf() is the number of millisecond since midnight January 1, 1970 UTC. Besides, all I want to achieve here is the value be automatically generated and different from previous one.

The only drawback I see with this method is that: With each release, this forces all the bundles to be refreshed. However, this is not a so much of a concern considering very low frequency of production rollouts we will have after first 2 releases.

Body:
I am using webpack to bundle my files into two file: app.js and lib.js and I create and append unique chunkhash for each of my files that get download by browser. Both these files are built together in the same build output. It would look like this:

lib.747c2ee515b25d871bd0.js
app.e6a0b36a5bb2bff41393.js

I have following caching set on these files:

Cache-Control:private, max-age=31536000

This means that these files will be cached for an year or when a new file arrives. And this would work independently for each file.

Since our application is closer to release, there more changes in app than in lib.

Problem: The problem I am facing is that in a new build, contents of the lib are not changed but module ids are changed. This is causing module ids to change but chunkhash doesn't change; causing downloading of app but not lib resulting into broken app. On Ctrl+F5 everything starts working again as expected.

Questions: Isn't the changed module ids considered as part of chunkash? How do I fix this problem? Is it possible to add auto-increment explicit version number to file names through WebPack?

Any help will be much appreciated.

Body:
The way I solved this is by adding one more number (which is Date.now()) into my file names as below.

filename: `[name].${Date.now().valueOf()}.[chunkhash].js`

This works pretty reliably for foreseeable time. This is with an understanding that the value returned by Date.now().valueOf() is the number of millisecond since midnight January 1, 1970 UTC. Besides, all I want to achieve here is the value be automatically generated and different from previous one.

The only drawback I see with this method is that: With each release, this forces all the bundles to be refreshed. However, this is not a so much of a concern considering very low frequency of production rollouts we will have after first 2 releases.


问:
Hooking into windows file access
Is it possible to hook into Windows loading or saving files (no matter how the file is opened like notepad word etc.) to modify the file on the fly?

For example to encode/decode it on the fly?

Would code need administrative permissions to launch?

答:
avoid madCodeHook (not profesdional)
use standard api hooking mechanisms (Richter and Microsoft D  mainly)</p>

OwnerDisplayName: Ornus

Title: Hooking into windows file access

OwnerDisplayName: red


问:
IntelliJ IDEA - How to give dependency between projects?
I've recently moved to IDEA from Eclipse and would like to do simple task of making one project depend on another.

With Eclipse it's straight forward as mentioned in
Eclipse - How to give dependency between projects?

But since last few days; I couldn't make it work with IDEA. Their support page neither forum post has helped in resolving this issue.

Please let me how to fix this problem

Thanks & Regards,
Vikram

P.S. I did try solutions mentioned in comments as below. But it didn't to resolve issue with IDEA version 2017.1.5. Thus I feel this shouldn't be marked as duplicate. IDEA is changing each year & they might have introduced bug.

答:
I could get it working be referring to below links

Main link to refer to

https://www.jetbrains.com/help/idea/2017.1/working-with-module-dependencies.html#add_dependency

Other helpful links to understand concepts in IDEA for those coming from Eclipse world

https://www.jetbrains.com/help/idea/2017.1/about-projects.html

https://www.jetbrains.com/help/idea/2017.1/about-modules.html

https://www.jetbrains.com/help/idea/2017.1/working-with-module-dependencies.html

https://github.com/jamesward/maven-multi-module-example

https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000448990-How-to-combine-3-maven-projects-into-single-window?page=1#community_comment_115000360310


问:
C# Regex.Split() does not work as expected
I'm trying out services in C#, so I cannot debug values using Console.WriteLine(...). That's why I don't know what is in my variable number at the end :

```<code>    public int addAndSoustractNumberFromAString(string ustr)
    {
        int result = 0;

        if(!string.IsNullOrEmpty(str))
        {
            string str = ustr.Trim();

            //Regexes
            System.Text.RegularExpressions.Regex valid_regex = new System.Text.RegularExpressions.Regex(@"[\+]\d+|[\-]\d+");
            System.Text.RegularExpressions.Regex invalid_regex = new System.Text.RegularExpressions.Regex(@"[a-zA-Z]");

            //Handling errors
            if (invalid_regex.IsMatch(str) || !valid_regex.IsMatch(str) || !Char.IsDigit(str[str.Length - 1])) return 0;
            if (Char.IsDigit(str[0])) str = "+" + str;

            //Load all numbers in a string array
            List<string> numbers = new List<string>(valid_regex.Split(str).ToArray());

            //Cast string numbers to int + result calculation
            foreach (string number in numbers) { if (!int.TryParse(number, out int n)) return 99; result += n; }
        }

        return result;
    }
</code>```

What does my code ?
I enter additions & subtractions, it does the operations & return the result as an integer.

example :
If I enter "52-2+3" it should return 53

Problem :
My code always returns 99 wich means the parsing failed.
Just in case, I tried int.TryParse("-2", out int n) instead and it works fine.

The line not working :

List<string> numbers = new List<string>(valid_regex.Split(str).ToArray());

My regexes are fine, I tested them with the website regexstorm net.

My question is, why my string ain't split correctly using a supposed valid regex ? Is Regex.Split() not doing what I believe it does ? (I tought it would split my string into +number or -number strings

Side note : it's ok if do not start with a sign. If my string starts with a number it will add "+" at the end for regex purposes.

答:
Replacing your regexp with ([\+\-]\d+) made the trick with the example "52-2+3" here.

Also added .Where(x => !String.IsNullOrEmpty(x)).ToList(); after the split so you get rid of empty strings.

Body:
I'm trying out services in C#, so I cannot debug values using Console.WriteLine(...). That's why I don't know what is in my variable number at the end :

    public int addAndSoustractNumberFromAString(string ustr)
    {
        int result = 0;

        if(!string.IsNullOrEmpty(str))
        {
            string str = ustr.Trim();

            //Regexes
            System.Text.RegularExpressions.Regex valid_regex = new System.Text.RegularExpressions.Regex(@"[\+]\d+|[\-]\d+");
            System.Text.RegularExpressions.Regex invalid_regex = new System.Text.RegularExpressions.Regex(@"[a-zA-Z]");

            //Handling errors
            if (invalid_regex.IsMatch(str) || !valid_regex.IsMatch(str) || !Char.IsDigit(str[str.Length - 1])) return 0;
            if (Char.IsDigit(str[0])) str = "+" + str;

            //Load all numbers in a string array
            List<string> numbers = new List<string>(valid_regex.Split(str).ToArray());

            //Cast string numbers to int + result calculation
            foreach (string number in numbers) { if (!int.TryParse(number, out int n)) return 99; result += n; }
        }

        return result;
    }

What does my code ?
I enter additions & subtractions, it does the operations & return the result as an integer.

example :
If I enter "52-2+3" it should return 53

Problem :
My code always returns 99 wich means the parsing failed.
Just in case, I tried int.TryParse("-2", out int n) instead and it works fine.

The line not working :

List<string> numbers = new List<string>(valid_regex.Split(str).ToArray());

My regexes are fine, I tested them with the website regexstorm net.

My question is, why my string ain't split correctly using a supposed valid regex ? Is Regex.Split() not doing what I believe it does ? (I tought it would split my string into +number or -number strings

Side note : it's ok if do not start with a sign. If my string starts with a number it will add "+" at the end for regex purposes.


问:
get value form nested map type map[string]interface{}
I'm trying to get all value from nested map and, I don't know how I can do that.

```<code>package main

import "fmt"

func main() {
    m := map[string]interface{}{
        "date":       "created",
        "clientName": "data.user.name",
        "address": map[string]interface{}{
            "street": "x.address",
        },
        "other": map[string]interface{}{
            "google": map[string]interface{}{
                "value": map[string]interface{}{
                    "x": "y.address",
                },
            },
        },
        "new_address": map[string]interface{}{
            "address": "z.address",
        },
    }

    for i := range m {
        fmt.Println(m[i])
        // how I can get value from other nested map?
    }
}
</code>```

how I can get value from other nested map?

答:
Inspired by @BayRinat answer

```<code>package main

import "fmt"

func main() {
    m := map[string]interface{}{
        "date":       "created",
        "clientName": "data.user.name",
        "address": map[string]interface{}{
            "street": "x.address",
        },
        "other": map[string]interface{}{
            "google": map[string]interface{}{
                "value": map[string]interface{}{
                    "x": "g.address",
                },
            },
        },
        "new_address": map[string]interface{}{
            "address": "z.address",
        },
        "key1": map[string]interface{}{
            "key2": map[string]interface{}{
                "key3": map[string]interface{}{
                    "key4": map[string]interface{}{
                        "key5": map[string]interface{}{
                            "key6": map[string]interface{}{
                                "key7": map[string]interface{}{
                                    "key": "enough",
                                },
                            },
                        },
                    },
                },
            },
        },
    }

    for i := range m {
        nestedMap, ok := m[i].(map[string]interface{})
        if ok {
            fmt.Println("Key:", i)
            fmt.Println("Value:", getValNestedMap(nestedMap))
        } else {
            fmt.Println("Key:", i)
            fmt.Println("Value:", m[i])
        }
    }

}
</code>```

```<code>func getValNestedMap(m map[string]interface{}) interface{} {
    for i := range m {
        nestedMap, ok := m[i].(map[string]interface{})
        if ok {
            return getValNestedMap(nestedMap)
        }
        return m[i]
    }

    return nil
}
</code>```

Go Playground

Body:
I'm trying to get all value from nested map and, I don't know how I can do that.

package main

import "fmt"

func main() {
    m := map[string]interface{}{
        "date":       "created",
        "clientName": "data.user.name",
        "address": map[string]interface{}{
            "street": "x.address",
        },
        "other": map[string]interface{}{
            "google": map[string]interface{}{
                "value": map[string]interface{}{
                    "x": "y.address",
                },
            },
        },
        "new_address": map[string]interface{}{
            "address": "z.address",
        },
    }

    for i := range m {
        fmt.Println(m[i])
        // how I can get value from other nested map?
    }
}

how I can get value from other nested map?

Body:
Inspired by @BayRinat answer

package main

import "fmt"

func main() {
    m := map[string]interface{}{
        "date":       "created",
        "clientName": "data.user.name",
        "address": map[string]interface{}{
            "street": "x.address",
        },
        "other": map[string]interface{}{
            "google": map[string]interface{}{
                "value": map[string]interface{}{
                    "x": "g.address",
                },
            },
        },
        "new_address": map[string]interface{}{
            "address": "z.address",
        },
        "key1": map[string]interface{}{
            "key2": map[string]interface{}{
                "key3": map[string]interface{}{
                    "key4": map[string]interface{}{
                        "key5": map[string]interface{}{
                            "key6": map[string]interface{}{
                                "key7": map[string]interface{}{
                                    "key": "enough",
                                },
                            },
                        },
                    },
                },
            },
        },
    }

    for i := range m {
        nestedMap, ok := m[i].(map[string]interface{})
        if ok {
            fmt.Println("Key:", i)
            fmt.Println("Value:", getValNestedMap(nestedMap))
        } else {
            fmt.Println("Key:", i)
            fmt.Println("Value:", m[i])
        }
    }

}

func getValNestedMap(m map[string]interface{}) interface{} {
    for i := range m {
        nestedMap, ok := m[i].(map[string]interface{})
        if ok {
            return getValNestedMap(nestedMap)
        }
        return m[i]
    }

    return nil
}

Go Playground


问:
Minimize sum of columns in matrix by permutating elements in python
I have the following matrix:

```<code>([2, 5, 5, 10]
 [7, 1, 4, 1]
 [1, 3, 3, 9])
</code>```

If the columns are summed the result is:

```<code>[10, 9, 12, 20]
</code>```

My objective is to determine the optimum way to sort the elements in the diferent rows in order to minimize the maximum element in the sum of columns.

For example, one possibility would be:

```<code>([2, 5, 5, 10]
 [7, 1, 4, 1]
 [1, 9, 3, 3])
</code>```

If the columns are summed the result is:

```<code>[10, 15, 12, 14]
</code>```

This is a better solution than the first one.

The easiest way to do this is checking all the possible permutations, but this method gets incredible slow in python as the matrix grows.

Any idea to do this in a faster way?

答:
First lets strengthen your requirement you could ask

```<code>"Can I produce a matrix that minimizes the difference between the max sum and the min sum of each column in my matrix"
</code>```

This is good because:

It will satisfy your original requirement so solving this solves your question

With this requirement it is easy to show sub-optimality in each iteration so we can convince ourselves that a greedy approach is going to work.

To implement a greedy solution just hold a running sum of your mat and for each row insert the lowest value in the current row into the highest sum column. This ensure that the column are as evenly stacked as possible.

This will take m inserts for each of n rows and 2mlogm sorts of each row so should run at O(n*m + n*2*mlogm) so O(nmlogm).

```<code>output_mat = []

input_mat = [
     [2, 5, 5, 10],
     [7, 1, 4, 1],
     [1, 3, 3, 9],
]

row_size = len(input_mat[0])
running_sum = [0] * row_size

for row in input_mat:
    sorted_idx = [
        x[0] for x in
        sorted(enumerate(row), key=lambda x: x[1])
    ]

    sum_sorted_idx = [
         x[0] for x in
         sorted(enumerate(running_sum), key=lambda x: x[1], reverse=True)
    ]

    new_val_row = [None] * row_size
    for col_idx,val_idx in zip(sum_sorted_idx, sorted_idx):
        new_val_row[col_idx] = row[val_idx]
        running_sum[col_idx] += row[val_idx]

    output_mat.append(new_val_row)

for x in output_mat:
    print ">> %s" % x
print(running_sum)
</code>```

Output:

```<code>>> [2, 5, 5, 10]
>> [7, 1, 4, 1]
>> [3, 9, 3, 1]
[12, 15, 12, 12]
</code>```

Body:
I have the following matrix:

([2, 5, 5, 10]
 [7, 1, 4, 1]
 [1, 3, 3, 9])

If the columns are summed the result is:

[10, 9, 12, 20]

My objective is to determine the optimum way to sort the elements in the diferent rows in order to minimize the maximum element in the sum of columns.

For example, one possibility would be:

([2, 5, 5, 10]
 [7, 1, 4, 1]
 [1, 9, 3, 3])

If the columns are summed the result is:

[10, 15, 12, 14]

This is a better solution than the first one.

The easiest way to do this is checking all the possible permutations, but this method gets incredible slow in python as the matrix grows.

Any idea to do this in a faster way?

Body:
First lets strengthen your requirement you could ask

"Can I produce a matrix that minimizes the difference between the max sum and the min sum of each column in my matrix"

This is good because:

It will satisfy your original requirement so solving this solves your question

With this requirement it is easy to show sub-optimality in each iteration so we can convince ourselves that a greedy approach is going to work.

To implement a greedy solution just hold a running sum of your mat and for each row insert the lowest value in the current row into the highest sum column. This ensure that the column are as evenly stacked as possible.

This will take m inserts for each of n rows and 2mlogm sorts of each row so should run at O(n*m + n*2*mlogm) so O(nmlogm).

output_mat = []

input_mat = [
     [2, 5, 5, 10],
     [7, 1, 4, 1],
     [1, 3, 3, 9],
]

row_size = len(input_mat[0])
running_sum = [0] * row_size

for row in input_mat:
    sorted_idx = [
        x[0] for x in
        sorted(enumerate(row), key=lambda x: x[1])
    ]

    sum_sorted_idx = [
         x[0] for x in
         sorted(enumerate(running_sum), key=lambda x: x[1], reverse=True)
    ]

    new_val_row = [None] * row_size
    for col_idx,val_idx in zip(sum_sorted_idx, sorted_idx):
        new_val_row[col_idx] = row[val_idx]
        running_sum[col_idx] += row[val_idx]

    output_mat.append(new_val_row)

for x in output_mat:
    print ">> %s" % x
print(running_sum)

Output:

>> [2, 5, 5, 10]
>> [7, 1, 4, 1]
>> [3, 9, 3, 1]
[12, 15, 12, 12]


问:
bash sed replace a line number in a file containing a colon
I am on RHEL 7.3. Line 12 of myfile.txt looks like:

image: /currentimage/myimage

I need a bash script to change it to:

image: /newimage/otherimage

I tried doing it this way:

```<code>sed -i '12s/image: /currentimage/myimage/image: /newimage/otherimage/' ./myfile
</code>```

But it fails with:

```<code>sed: unknown option to `s'
</code>```

答:
If you can use Awk, it is pretty simple to move on the 12th line using the NR variable which represents the line being processed,

```<code>awk 'NR==12{$2="/newimage/otherimage/"}1' myfile > tmp && mv tmp myfile
</code>```

The part > tmp && mv tmp myfile is equivalent to to the -i option in sed for an indirect way to do modify the file in-place.

ContentLicense: CC BY-SA 4.0

Body:
I am on RHEL 7.3. Line 12 of myfile.txt looks like:

image: /currentimage/myimage

I need a bash script to change it to:

image: /newimage/otherimage

I tried doing it this way:

sed -i '12s/image: /currentimage/myimage/image: /newimage/otherimage/' ./myfile

But it fails with:

sed: unknown option to `s'

Body:
If you can use Awk, it is pretty simple to move on the 12th line using the NR variable which represents the line being processed,

awk 'NR==12{$2="/newimage/otherimage/"}1' myfile > tmp && mv tmp myfile

The part > tmp && mv tmp myfile is equivalent to to the -i option in sed for an indirect way to do modify the file in-place.


问:
CoreData application directory crashes on iOS3
I have nearly finished my application that works well on iOS4, however when loading it into the 3.2 simulator it crashes with..

```<code>2010-12-21 07:54:32.052 App[14044:207] *** -[NSPathStore2 URLByAppendingPathComponent:]: unrecognized selector sent to instance 0x4d2b640
2010-12-21 07:54:32.054 App[14044:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSPathStore2 URLByAppendingPathComponent:]: unrecognized selector sent to instance 0x4d2b640'
</code>```

I am getting the application Document Directory with

```<code>NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"App.sqlite"];

- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
</code>```

Any help would be great, thanks.

答:
The documentation mentions that URLByAppendingPathComponent: is only available in iOS 4 and later. You can accomplish the same thing by using NSStrings with stringByAppendingPathComponent:, and then converting to a URL when done.

Apparently URLsForDirectory:inDomains: is 4.0-only as well. Check out NSSearchPathsForDirectoriesInDomains() for an alternative that's compatible with earlier OSes.

Body:
I have nearly finished my application that works well on iOS4, however when loading it into the 3.2 simulator it crashes with..

2010-12-21 07:54:32.052 App[14044:207] *** -[NSPathStore2 URLByAppendingPathComponent:]: unrecognized selector sent to instance 0x4d2b640
2010-12-21 07:54:32.054 App[14044:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSPathStore2 URLByAppendingPathComponent:]: unrecognized selector sent to instance 0x4d2b640'

I am getting the application Document Directory with

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"App.sqlite"];

- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

Any help would be great, thanks.


问:
How to save content to my computer from Jframe in netbeans?
I have some problem, can somebody help me, I am new at java. I whant to save content from jframe on my computer, and I need option to again open in program after I save that on my computer, not txt file, not pdf? Can somebody help me?
This is the jframe enter image description here

And this is code for now but it doesn't work

```<code> package servis1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.StringReader;
import javax.swing.JFileChooser;

/**
 *
 * @author Boris
 */
public class NewJFrame extends javax.swing.JFrame {
     private String data;
    JFileChooser chooser = new JFileChooser();

/**
 * Creates new form NewJFrame
 */
public NewJFrame() {
    initComponents();
}
 @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    Imeiprezime = new java.awt.Label();
    textField1 = new java.awt.TextField();
    label2 = new java.awt.Label();
    textField2 = new java.awt.TextField();
    label3 = new java.awt.Label();
    label4 = new java.awt.Label();
    textField4 = new java.awt.TextField();
    label5 = new java.awt.Label();
    textField5 = new java.awt.TextField();
    label6 = new java.awt.Label();
    label7 = new java.awt.Label();
    jComboBox1 = new javax.swing.JComboBox();
    jLabel2 = new javax.swing.JLabel();
    jComboBox2 = new javax.swing.JComboBox();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea2 = new javax.swing.JTextArea();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
    jLabel1.setText("POTVDA O PRIJEMU NA SERVIS");

    Imeiprezime.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    Imeiprezime.setText("Ime i prezime:");

    label2.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    label2.setText("Broj telefona:");

    label3.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    label3.setText("Proizvodjac:");

    label4.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    label4.setText("Model:");

    label5.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    label5.setText("IMEI:");

    label6.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    label6.setText("Opis kvara:");

    label7.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    label7.setText("Napomena:");

    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Apple", "Samsung", "HTC", "Huawei" }));

    jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
    jLabel2.setText("Primio na servis:");

    jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Marko Markovic", "Petar Petrovic", "Janko Jankovic" }));

    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);

    jTextArea2.setColumns(20);
    jTextArea2.setRows(5);
    jScrollPane2.setViewportView(jTextArea2);

    jButton1.setText("Sacuvaj");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(23, 23, 23)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(Imeiprezime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jComboBox1, 0, 400, Short.MAX_VALUE)
                    .addComponent(textField1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(textField2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(textField4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(textField5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addGap(49, 49, 49))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                    .addComponent(jScrollPane2)))
            .addContainerGap(79, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(30, 30, 30)
            .addComponent(jLabel1)
            .addGap(25, 25, 25)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(Imeiprezime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(24, 24, 24)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(textField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(textField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(22, 22, 22)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton1))
            .addGap(60, 60, 60))
    );

    pack();
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
           int retValue = chooser.showSaveDialog(null);
        if(retValue == chooser.APPROVE_OPTION){
        File f = chooser.getSelectedFile();
        try{
            BufferedReader reader = new BufferedReader(new StringReader(data));//data is string to save
            BufferedWriter writer = new BufferedWriter(new FileWriter(f));
            String str;
            while((str = reader.readLine())!= null){
                writer.write(str + System.getProperty("line.separator"));
        }
        }catch(Exception ex){
            System.out.println("Error!");
                    }
        }

    }

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}

// Variables declaration - do not modify
private java.awt.Label Imeiprezime;
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private java.awt.Label label2;
private java.awt.Label label3;
private java.awt.Label label4;
private java.awt.Label label5;
private java.awt.Label label6;
private java.awt.Label label7;
private java.awt.TextField textField1;
private java.awt.TextField textField2;
private java.awt.TextField textField4;
private java.awt.TextField textField5;
// End of variables declaration
</code>```

`

答: I think is not possible not storing info on the computer for retrieving before close it. I mean: when you close a program, all data is destroyed getting its RAM blocks free. So you must use something like XML file builder where you can dump the info, store it temporally on the computer (in the program folder F. E.), and then retrieve it and deleting the file. </p>

Body:
I have some problem, can somebody help me, I am new at java. I whant to save content from jframe on my computer, and I need option to again open in program after I save that on my computer, not txt file, not pdf? Can somebody help me?
This is the jframe enter image description here

And this is code for now but it doesn't work

 package servis1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.StringReader;
import javax.swing.JFileChooser;

/**
 *
 * @author Boris
 */
public class NewJFrame extends javax.swing.JFrame {
     private String data;
    JFileChooser chooser = new JFileChooser();

/**
 * Creates new form NewJFrame
 */
public NewJFrame() {
    initComponents();
}
 @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    Imeiprezime = new java.awt.Label();
    textField1 = new java.awt.TextField();
    label2 = new java.awt.Label();
    textField2 = new java.awt.TextField();
    label3 = new java.awt.Label();
    label4 = new java.awt.Label();
    textField4 = new java.awt.TextField();
    label5 = new java.awt.Label();
    textField5 = new java.awt.TextField();
    label6 = new java.awt.Label();
    label7 = new java.awt.Label();
    jComboBox1 = new javax.swing.JComboBox();
    jLabel2 = new javax.swing.JLabel();
    jComboBox2 = new javax.swing.JComboBox();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea2 = new javax.swing.JTextArea();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
    jLabel1.setText("POTVDA O PRIJEMU NA SERVIS");

    Imeiprezime.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    Imeiprezime.setText("Ime i prezime:");

    label2.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    label2.setText("Broj telefona:");

    label3.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    label3.setText("Proizvodjac:");

    label4.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    label4.setText("Model:");

    label5.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    label5.setText("IMEI:");

    label6.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    label6.setText("Opis kvara:");

    label7.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
    label7.setText("Napomena:");

    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Apple", "Samsung", "HTC", "Huawei" }));

    jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
    jLabel2.setText("Primio na servis:");

    jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Marko Markovic", "Petar Petrovic", "Janko Jankovic" }));

    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);

    jTextArea2.setColumns(20);
    jTextArea2.setRows(5);
    jScrollPane2.setViewportView(jTextArea2);

    jButton1.setText("Sacuvaj");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(23, 23, 23)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(Imeiprezime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jComboBox1, 0, 400, Short.MAX_VALUE)
                    .addComponent(textField1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(textField2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(textField4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(textField5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addGap(49, 49, 49))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                    .addComponent(jScrollPane2)))
            .addContainerGap(79, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(30, 30, 30)
            .addComponent(jLabel1)
            .addGap(25, 25, 25)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(Imeiprezime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(24, 24, 24)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(textField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(textField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(22, 22, 22)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton1))
            .addGap(60, 60, 60))
    );

    pack();
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
           int retValue = chooser.showSaveDialog(null);
        if(retValue == chooser.APPROVE_OPTION){
        File f = chooser.getSelectedFile();
        try{
            BufferedReader reader = new BufferedReader(new StringReader(data));//data is string to save
            BufferedWriter writer = new BufferedWriter(new FileWriter(f));
            String str;
            while((str = reader.readLine())!= null){
                writer.write(str + System.getProperty("line.separator"));
        }
        }catch(Exception ex){
            System.out.println("Error!");
                    }
        }

    }

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}

// Variables declaration - do not modify
private java.awt.Label Imeiprezime;
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextArea jTextArea2;
private java.awt.Label label2;
private java.awt.Label label3;
private java.awt.Label label4;
private java.awt.Label label5;
private java.awt.Label label6;
private java.awt.Label label7;
private java.awt.TextField textField1;
private java.awt.TextField textField2;
private java.awt.TextField textField4;
private java.awt.TextField textField5;
// End of variables declaration

`


答:
You are using / as your sed separator, AND it is used in your paths. Try using | as your separator instead.

```<code>sed -i '12s|image: /currentimage/myimage|image: /newimage/otherimage|' ./myfile
</code>```

Additionally you can escape each / in the file path like so \/ .

Title: bash sed replace a line number in a file containing a colon

Body:
You are using / as your sed separator, AND it is used in your paths. Try using | as your separator instead.

sed -i '12s|image: /currentimage/myimage|image: /newimage/otherimage|' ./myfile

Additionally you can escape each / in the file path like so \/ .


问:
Trigger event on selection of second box, Angular
I have 2 boxes the first you select parent, second you select the child of a selected parent.

How do I run the function bellow after the second selection ?

angular function

```<code>$scope.myFunc = function() {
            var jsonItem = JSON.parse($scope.formData.formatType.id);
            sessionStorage.setItem('format', jsonItem);
        }
</code>```

HTML

```<code><select ng-model="formData.ProductType.name" ng-change="productTypeChange()" ng-options="product.name as product.name for product in productsandformats">
    <option value="">- Please Choose -</option>
</select>

<select ng-model="formData.formatType" ng-options="format.Fname for format in formats.format" ng-if="formData.ProductType.name">
    <option value="">- Please Choose -</option>
</select>
</code>```

答:
Use ng-change

```<code>    <select ng-model="formData.formatType"
            ng-options="format.Fname for format in formats.format"
            ng-if="formData.ProductType.name" ng-change="myFunc()">
        <option value="">- Please Choose -</option>
    </select>`
</code>```

Body:
I have 2 boxes the first you select parent, second you select the child of a selected parent.

How do I run the function bellow after the second selection ?

angular function

$scope.myFunc = function() {
            var jsonItem = JSON.parse($scope.formData.formatType.id);
            sessionStorage.setItem('format', jsonItem);
        }

HTML

<select ng-model="formData.ProductType.name" ng-change="productTypeChange()" ng-options="product.name as product.name for product in productsandformats">
    <option value="">- Please Choose -</option>
</select>

<select ng-model="formData.formatType" ng-options="format.Fname for format in formats.format" ng-if="formData.ProductType.name">
    <option value="">- Please Choose -</option>
</select>

Body:
Use ng-change

    <select ng-model="formData.formatType"
            ng-options="format.Fname for format in formats.format"
            ng-if="formData.ProductType.name" ng-change="myFunc()">
        <option value="">- Please Choose -</option>
    </select>`


问:
How are values assigned to non-class types?
If non-class types, like pointers and int, do not have member functions like constructors, how are values assigned to them?
For instance:

```<code>int x = 1;
int p = x;
p = 2;
int a = int();
</code>```

When I did int p = x; would that simply perform a shallow copy, like an implicit copy constructor? Same goes for all other implicit member functions, since non-class types tend to work in the same way as with class types in those situations.

Also, when you have a class, that class would probably have an object that stores a certain value(if the class is supposed to represent a value), but is there some sort of buffer for these non-class types? Otherwise, how can a value be copied from one to another?

答:
If non-class types, like pointers and int, do not have member functions like constructors, how are values assigned to them?

A constructor is not magic. The compiler and computer do not randomly find themselves incapable of performing basic memory copy operations just because a type does not have the concept of constructors.

Internally the logic is similar but the copy operation is simpler. A copy constructor is a way to compose operations over the members of a class, which themselves may be other class instances or built-in types. The built-in types are the "base case" and I can assure you that the compiler knows how to generate code to copy them.

Of course, because they are the "base case", there is no meaningful application of the terms "shallow copy" and "deep copy" here — a copy is a copy is a copy. An int has no indirect resources that could be copied or not copied, which is where shallow/deep copying comes in with classes and pointers.

A more in-depth analysis of how compilers work is out of scope.

Body:
If non-class types, like pointers and int, do not have member functions like constructors, how are values assigned to them?
For instance:

int x = 1;
int p = x;
p = 2;
int a = int();

When I did int p = x; would that simply perform a shallow copy, like an implicit copy constructor? Same goes for all other implicit member functions, since non-class types tend to work in the same way as with class types in those situations.

Also, when you have a class, that class would probably have an object that stores a certain value(if the class is supposed to represent a value), but is there some sort of buffer for these non-class types? Otherwise, how can a value be copied from one to another?


问:
Programmatically Inserting Data into an InDesign Document
I have to use Adobe InDesign for creating documents. We basically need to have a couple variables throughout the document (company name, project name, etc) that need to be filled in.

I was wondering if there is a way to take an existing template and maybe programmatically fill these in using a language I'm comfortable with (Ruby, Python, etc). I have tried to open the Adobe InDesign file using a text editor - but when I make modifications using Notepad++ and then open the file in InDesign, it tells me the file is corrupted.

If you have any insight with programmatically building InDesign documents or know of any tutorials that would be much appreciated.

P.S. I tried to check out Adobe's ExtendScript but wasn't finding much documentation applying to InDesign.

Thanks for the help!

答:
You can use the DataMerge-feature of Indesign --> https://helpx.adobe.com/indesign/using/data-merge.html

I think this is exactly what you are looking for.

Or you can use the Indesign API. Have a look at Extendscript-Toolkit especially the ObjectModell-Viewer.