问:
Virtual Assistant in Python
I'm trying to code a virtual assistant in Python, but I want it the more "human" possible. I want her to interpret my question, not compare with an string.
So, my doubt is:

To cover all variations of the same request, like "Will rain tomorrow?" and "Tomorrow I'll need an umbrella?" I have to put each request in an If statement?
For example:

```<code>if audio == "Will rain tomorrow?":
    checkWeather()...

if audio == "Tomorrow I'll need an umbrella?":
    checkWeather()...

another if statements...
</code>```

This is the way that the great virtual assistants (Siri, Google Now, etc) are coded or is there a method to cover the variations without repeating a condition statement for every possibility? Is a technique for modeling the code or something that I need to know?

答:
First thing you should do is take a look at NLTK and learn about natural language processing. Learn about tokenization and tagging and I think you may get somewhere.

This link might have some interesting topics:

http://xrds.acm.org/blog/2017/01/build-natural-language-processing-based-intelligent-assistant-using-python-easy/

But be aware that what you are trying to do is not an easy task!

Title: Virtual Assistant in Python

Body:
I'm trying to code a virtual assistant in Python, but I want it the more "human" possible. I want her to interpret my question, not compare with an string.
So, my doubt is:

To cover all variations of the same request, like "Will rain tomorrow?" and "Tomorrow I'll need an umbrella?" I have to put each request in an If statement?
For example:

if audio == "Will rain tomorrow?":
    checkWeather()...

if audio == "Tomorrow I'll need an umbrella?":
    checkWeather()...

another if statements...

This is the way that the great virtual assistants (Siri, Google Now, etc) are coded or is there a method to cover the variations without repeating a condition statement for every possibility? Is a technique for modeling the code or something that I need to know?


来源: stackexchange

问:
Status Monitor in Eclipse?
I am pretty new at developing larger software and I am using Eclipse as IDE.

When my program is running, I want to have certain informations about the status in different classes (like values of certain objects). Up until now I was just printing it all out on the console with System.out.println(object.value);.

After a while the console became confusing with all the different values printed higgledy-piggledy. Now I am searching for a plugin or something, with which I can do something like

```<code>StatusMonitor monitorSize = new StatusMonitor();
StatusMonitor monitorHeight = new StatusMonitor();
monitorSize.print(object.size);
monitorHeight.print(object.height);
</code>```

And then Eclipse has two different terminals/windows where the specific variables are printed.

Is there a possibility to achieve that?

答:
YOU SHOULD DEBUG IT. FOR THIS ADD BREAKPOINTS IN THE CODE(To define a breakpoint in your source code, right-click in the left margin in the Java editor and select Toggle Breakpoint. Alternatively you can double-click on this position.) WHERE YOU WANT TO CHECK THE VALUES OF VARIABLES. WHEN YOU HAVE PUT THE BREAKPOINTS IN YOUR CODE THEN RIGHT CLICK ON THE CLASS WITH MAIN METHOD THEN SELECT --> DEBUG AS--> JAVA APPLICATION. THEN A DIALOG BOX WLL OPEN CLICK YES ON IT AND NOW YOUR CODE WILL BE OPEN IN DEBUG MODE. ON THE TOP PANEL .There  will be options such as STEP INTO ETC. ALSO THERE WILL ARE FEW SHORTCUTS:
F5-->Executes the currently selected line and goes to the next line in your program. If the selected line is a method call the debugger steps into the associated code.
F6-->F6 steps over the call, i.e. it executes a method without stepping into it in the debugger.
F7-->F7 steps out to the caller of the currently executed method. This finishes the execution of the current method and returns to the caller of this method.
F8-->F8 tells the Eclipse debugger to resume the execution of the program code until is reaches the next breakpoint or watchpoint.</p>

ContentLicense: CC BY-SA 3.0

Title: Status Monitor in Eclipse?

Body:
I am pretty new at developing larger software and I am using Eclipse as IDE.

When my program is running, I want to have certain informations about the status in different classes (like values of certain objects). Up until now I was just printing it all out on the console with System.out.println(object.value);.

After a while the console became confusing with all the different values printed higgledy-piggledy. Now I am searching for a plugin or something, with which I can do something like

StatusMonitor monitorSize = new StatusMonitor();
StatusMonitor monitorHeight = new StatusMonitor();
monitorSize.print(object.size);
monitorHeight.print(object.height);

And then Eclipse has two different terminals/windows where the specific variables are printed.

Is there a possibility to achieve that?


问:
CloudBerry PowerShell Multipart
I've written a powershell script to upload from a windows system to an  Amazon S3 Bucket.  The script successfully uploads all files, except those over 5Gb.  I have the Cloud Berry Explorer Pro license which allows for multipart upload on files up to 5TB.  However there is no flag for multipart on the powershell snapin documentation.  Cloudberry support directed me here as they only support the GUI not the powershell snapin.  When running my script I get the error

"WARNING: Your proposed upload exceeds the maximum allowed object size (5 Gb)".

So question is, does anyone know if there is a command line option, or another way to enable multipart upload to Amazon S3 using Cloudberry Explorer Pro's Powershell Snapin?

答:
I'm looking for the same in Powershell.

I believe in GUI, the original chunking mechanism has been depreciated. I have not tested myself, but I assume Powershell option UseChunks=true is still using the old mechanism? If so, files may be split into multiple parts and not automatically recombined when they arrive on S3.  The new GUI Multipart Upload facility sorts this all out for you.

Annoyed Cloudberry still advertise Powershell as a component of Explorer (Free & Pro), but don't support it, even for fully paid up PRO support customers.

Title: CloudBerry PowerShell Multipart


问:
phpunit no tests executed
I have a 'No tests executed' with phpunit..

This line works

```<code>$ phpunit install/InstallDbTest.php
...
<result expected>
...

$ cat suites/installtests.xml
<phpunit>
    <testsuites>
        <testsuite name="database">
            <file>install/InstallDbTest.php</file>
        </testsuite>
    </testsuites>
</phpunit>

$ phpunit -c suites/installtests.xml
PHPUnit 4.7.4 by Sebastian Bergmann and contributors.

Time: 130 ms, Memory: 11.25Mb

No tests executed!
</code>```

Does anyone can tell me what I am doing wrong ?

Thanks in advance!

答:
Maybe in the InstallDbTest.php file you are missing:

```<code><?php
...
</code>```

Title: phpunit no tests executed

Body:
I have a 'No tests executed' with phpunit..

This line works

$ phpunit install/InstallDbTest.php
...
<result expected>
...

$ cat suites/installtests.xml
<phpunit>
    <testsuites>
        <testsuite name="database">
            <file>install/InstallDbTest.php</file>
        </testsuite>
    </testsuites>
</phpunit>

$ phpunit -c suites/installtests.xml
PHPUnit 4.7.4 by Sebastian Bergmann and contributors.

Time: 130 ms, Memory: 11.25Mb

No tests executed!

Does anyone can tell me what I am doing wrong ?

Thanks in advance!

Body:
Maybe in the InstallDbTest.php file you are missing:

<?php
...


问:
Split string at different characters into 2d array
When I want to split a string at a character and put it into an array I use:

```<code>var arr = data.split("\n");
</code>```

This time however I need to split a string at different characters and need to store it into an 2d-array.
The string is as follows:

```<code>PMC12365AB
PMC23456AB
PMC34567AB
</code>```

The desired outcome

```<code>arr = [
    ["PMC", "12365", "AB"],
    ["PMC", "23456", "AB"],
    ["PMC", "34567", "AB"]
];
</code>```

Any ideas

答:
```<code>var input = "PMC12365AB\nPMC23456AB\nPMC34567AB";
var output = input.split('\n').map(function(line)
{
    var a = line.match(/^(...)(.....)(..)$/);
    a.shift();
    return a;
});
</code>```

Obviously, the exact regex depends on how you want to cut each line, not sure if they're fixed-width, or based on letters vs numbers...

Body:
When I want to split a string at a character and put it into an array I use:

var arr = data.split("\n");

This time however I need to split a string at different characters and need to store it into an 2d-array.
The string is as follows:

PMC12365AB
PMC23456AB
PMC34567AB

The desired outcome

arr = [
    ["PMC", "12365", "AB"],
    ["PMC", "23456", "AB"],
    ["PMC", "34567", "AB"]
];

Any ideas

Body:
var input = "PMC12365AB\nPMC23456AB\nPMC34567AB";
var output = input.split('\n').map(function(line)
{
    var a = line.match(/^(...)(.....)(..)$/);
    a.shift();
    return a;
});

Obviously, the exact regex depends on how you want to cut each line, not sure if they're fixed-width, or based on letters vs numbers...


问:
Slider with Prototype javascript
I am creating a slider using prototype javascrtipt

My problem is when slider goes to 5 th slide it again slides back to 1 st slide in sequence(5,4,3,2,1) and it is starting from 1 slide

Can any one explain how should i over come this thank you very much..

```<code>var slider;
Event.observe(window, 'load', function() {
    slider = new MOSS('moss_panel', '', 'moss_panel', null, 1, true, false, 1);
    m_TimeOutSlider = setTimeout("MOSSSlideShow('1')", 1000);
});

function MOSSSlideShow() {

    clearTimeout(m_TimeOutSlider);
    slider.next();
    if (slider.offset == 5) {
        slider.offset = -1;
    }
    m_TimeOutSlider = setTimeout("MOSSSlideShow()",5000);
}
</code>```

this is my code in javascript

答:
This simple javascript timer code will give you some idea and your logic can be derived from that -

Code for a simple JavaScript countdown timer?

ContentLicense: CC BY-SA 2.5

Title: Slider with Prototype javascript

Body:
I am creating a slider using prototype javascrtipt

My problem is when slider goes to 5 th slide it again slides back to 1 st slide in sequence(5,4,3,2,1) and it is starting from 1 slide

Can any one explain how should i over come this thank you very much..

var slider;
Event.observe(window, 'load', function() {
    slider = new MOSS('moss_panel', '', 'moss_panel', null, 1, true, false, 1);
    m_TimeOutSlider = setTimeout("MOSSSlideShow('1')", 1000);
});

function MOSSSlideShow() {

    clearTimeout(m_TimeOutSlider);
    slider.next();
    if (slider.offset == 5) {
        slider.offset = -1;
    }
    m_TimeOutSlider = setTimeout("MOSSSlideShow()",5000);
}

this is my code in javascript


问:
convert utf8 to ISO8859-1 using iconv command
I want to convert some utf8 files (text files) to ISO-8859-1 files. I use this command line :

```<code>iconv -c -f UTF-8 -t ISO8859-1 input_file > output_file
</code>```

The file created (output_file) is indeed in the new encoding, even accentuated letters are good.

Just one character is not : the apostrophe... not the one corresponding to the one displayed on key 4 but one like the one you can do in a word file.

```<code>’
</code>```

The problem is that it is converted to a SUB character, like something you would see if you open a word file in notepad++.

```<code> (I copy the SUB here seen in notepad++ and it displays like that, obviously invisible when I submit this page)
</code>```

In notepad++, there is a menu option to convert files from an encoding to another. There is no problem with any character. Is there something equivalent in Unix that can do the job?

Thank you

答:
Well, you could replace the ’ with something else (' below) before converting with iconv, like:

```<code>echo Frank’s ’ | sed "s/’/'/g" | iconv -f utf8 -t iso8859-1
Frank's '
</code>```

To convert a file like that:

```<code>sed "s/’/'/g" input_file | iconv [your params here] > output_file
</code>```

Body:
I want to convert some utf8 files (text files) to ISO-8859-1 files. I use this command line :

iconv -c -f UTF-8 -t ISO8859-1 input_file > output_file

The file created (output_file) is indeed in the new encoding, even accentuated letters are good.

Just one character is not : the apostrophe... not the one corresponding to the one displayed on key 4 but one like the one you can do in a word file.

’

The problem is that it is converted to a SUB character, like something you would see if you open a word file in notepad++.

 (I copy the SUB here seen in notepad++ and it displays like that, obviously invisible when I submit this page)

In notepad++, there is a menu option to convert files from an encoding to another. There is no problem with any character. Is there something equivalent in Unix that can do the job?

Thank you

Body:
Well, you could replace the ’ with something else (' below) before converting with iconv, like:

echo Frank’s ’ | sed "s/’/'/g" | iconv -f utf8 -t iso8859-1
Frank's '

To convert a file like that:

sed "s/’/'/g" input_file | iconv [your params here] > output_file


问:
Neither xcopy nor MSBuild CopyTask actually copy outfile file
I have a main application, which uses MEF to load plugins, as well as several projects for plugins.
For the plugin projects, I'm trying to define a post-build action for each, which copies all output files into a \plugins\ subdirectory of my main application.

So for example copy all files from
C:\path to solution\MySolution\DummyPlugin\bin\x86\Debug\*.*  into
C:\path to solution\MySolution\MainApplication\bin\x86\Debug\Plugins\

I'm using a build event

```<code>xcopy "$(ProjectDir)$(OutDir)*" "$(SolutionDir)MainApplication\$(OutDir)Plugins\" /D /y /s /r
</code>```

Which seems to work fine for 2 out of my 3 plugin projects.
But for my last project, whose output assembly is Service.dll, this seems to fail - as in, the file isn't copied.

I've tried substituting the build event with a MSBuild Task as follows,

```<code><Target Name="AfterBuild">
  <CreateItem Include="$(ProjectDir)$(OutDir)*.*">
    <Output TaskParameter="Include" ItemName="PluginFiles"/>
  </CreateItem>
  <Copy SourceFiles="@(PluginFiles)" DestinationFolder="$(SolutionDir)MainApplication\$(OutDir)Plugins\" ContinueOnError="false" />
</Target>
</code>```

and even tried just coying Service.dll specifically,

```<code><Target Name="AfterBuild">
  <Copy SourceFiles="$(ProjectDir)$(OutDir)Service.dll" DestinationFolder="$(SolutionDir)MainApplication\$(OutDir)Plugins\" ContinueOnError="false" />
</Target>
</code>```

In each case, compiling works fine, there is no error output or anything whatsoever. But the files just aren't being copied.

Does anyhave have any clue what's going on there?!
This is probably some really stupid problem, but since there are no errors or no output whatsoever, not sure how to track down the issue any further..

Thanks

答: file probably still be 'in use' by msbuild (buffered write) - sometimes the post build already starts before done fully writing.</p>

Body:
I have a main application, which uses MEF to load plugins, as well as several projects for plugins.
For the plugin projects, I'm trying to define a post-build action for each, which copies all output files into a \plugins\ subdirectory of my main application.

So for example copy all files from
C:\path to solution\MySolution\DummyPlugin\bin\x86\Debug\*.*  into
C:\path to solution\MySolution\MainApplication\bin\x86\Debug\Plugins\

I'm using a build event

xcopy "$(ProjectDir)$(OutDir)*" "$(SolutionDir)MainApplication\$(OutDir)Plugins\" /D /y /s /r

Which seems to work fine for 2 out of my 3 plugin projects.
But for my last project, whose output assembly is Service.dll, this seems to fail - as in, the file isn't copied.

I've tried substituting the build event with a MSBuild Task as follows,

<Target Name="AfterBuild">
  <CreateItem Include="$(ProjectDir)$(OutDir)*.*">
    <Output TaskParameter="Include" ItemName="PluginFiles"/>
  </CreateItem>
  <Copy SourceFiles="@(PluginFiles)" DestinationFolder="$(SolutionDir)MainApplication\$(OutDir)Plugins\" ContinueOnError="false" />
</Target>

and even tried just coying Service.dll specifically,

<Target Name="AfterBuild">
  <Copy SourceFiles="$(ProjectDir)$(OutDir)Service.dll" DestinationFolder="$(SolutionDir)MainApplication\$(OutDir)Plugins\" ContinueOnError="false" />
</Target>

In each case, compiling works fine, there is no error output or anything whatsoever. But the files just aren't being copied.

Does anyhave have any clue what's going on there?!
This is probably some really stupid problem, but since there are no errors or no output whatsoever, not sure how to track down the issue any further..

Thanks


问:
Stop saving into coredata in background while tapping a button
I want to stop all my background save and update in CoreData when i click my logout button so that i can safely delete all the data related to current user deleted. My code to delete the CoreData objects are

```<code>  static func logoutAction(){
    SVProgressHUD.show()
    let deviceToken = kSharedUserDefaults.getDeviceToken()
    self.perform(#selector(deletecoreData), with: self, afterDelay: 3)

    print("Reset All data in userddefaults.")
    kSharedUserDefaults.setDeviceToken(token: deviceToken)
    SVProgressHUD.dismiss()
    kSharedAppDelegate.configureLoginViewController()

}

static func deletecoreData(){
    for str in ["JobStatusTransition","JobImages","CustomField","Attribute","Booking","Job","Notification","Person","Status"]{
        deleteObjEntity(entity: str)
    }
    if let bundle = Bundle.main.bundleIdentifier {
        UserDefaults.standard.removePersistentDomain(forName: bundle)
    }
}
   static func deleteObjEntity(entity:String){
    let moc = CoreDataHelper.sharedInstance.bgManagedObjectContext
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)

    let result = try? moc.fetch(fetchRequest)
    let resultData = result

    for object in resultData! {
        moc.delete(object as! NSManagedObject)
    }

    do {
        try moc.save()
        print("saved!")
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    } catch {

    }
}
</code>```

currently it is crashing when there is any background save into db these are my errors

CoreData: error: Mutating a managed object 0x1951ade0  (0x19558580) after it has been removed from its context.
2017-06-06 16:37:32.448 WheelTech[2242:256244] CoreData: error: Mutating a managed object 0x1951ade0  (0x19558580) after it has been removed from its context.
2017-06-06 16:37:32.465 WheelTech[2242:256244] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'booking' between objects in different contexts (source =  (entity: Job; id: 0x1951ade0  ;
* First throw call stack:
(0x24eb391b 0x2464ee17 0x269a2475 0x269a0fb1 0xa7c00 0xa8338 0x11bb38 0x26a0d4b7 0x1f72493 0x1f6ade1 0x1f73ecf 0x1f737cf 0x24be5b29 0x24be5718)
libc++abi.dylib: terminating with uncaught exception of type NSException

答:
"attempt to establish a relationship between objects in different contexts" is a serious problem which points to deep problems in how you are dealing with threading and core-data in your app.  I would recommend watching this: https://vimeo.com/89370886 which explains how a properly setup core data stack should look.  The basic idea is that you want ALL you changes to core-data to be done in a serial queue.  Each operation creates it own context, fetches the objects it needs, modifies them, saves the context and then discards it.  You NEVER pass managedObjects into or out of the operation.

This setup is from before NSPersistentContainer, but NSPersistentContainer is basically the same setup under the hood so the lecture still has a huge amount of value.  All write that are done using performBackgroundTask are in a private serial queue.  To use it:

NEVER write to the viewContext

only write using performBackgroundTask.

Do not use any managedObjects or context from performBackgroundTask

Do not use any viewContext managedObject inside of performBackgroundTask - pass the objectID and refetch it inside the context.

don't use newBackgroundContext - it is useful only in very rare situations that you are unlikely to encounter.

Once you have a property setup stack your problems will go aways.  You enqueue an operation to delete all objects.  All future operation will fail on their fetches and do nothing.

Body:
I want to stop all my background save and update in CoreData when i click my logout button so that i can safely delete all the data related to current user deleted. My code to delete the CoreData objects are

  static func logoutAction(){
    SVProgressHUD.show()
    let deviceToken = kSharedUserDefaults.getDeviceToken()
    self.perform(#selector(deletecoreData), with: self, afterDelay: 3)

    print("Reset All data in userddefaults.")
    kSharedUserDefaults.setDeviceToken(token: deviceToken)
    SVProgressHUD.dismiss()
    kSharedAppDelegate.configureLoginViewController()

}

static func deletecoreData(){
    for str in ["JobStatusTransition","JobImages","CustomField","Attribute","Booking","Job","Notification","Person","Status"]{
        deleteObjEntity(entity: str)
    }
    if let bundle = Bundle.main.bundleIdentifier {
        UserDefaults.standard.removePersistentDomain(forName: bundle)
    }
}
   static func deleteObjEntity(entity:String){
    let moc = CoreDataHelper.sharedInstance.bgManagedObjectContext
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)

    let result = try? moc.fetch(fetchRequest)
    let resultData = result

    for object in resultData! {
        moc.delete(object as! NSManagedObject)
    }

    do {
        try moc.save()
        print("saved!")
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    } catch {

    }
}

currently it is crashing when there is any background save into db these are my errors

CoreData: error: Mutating a managed object 0x1951ade0  (0x19558580) after it has been removed from its context.
2017-06-06 16:37:32.448 WheelTech[2242:256244] CoreData: error: Mutating a managed object 0x1951ade0  (0x19558580) after it has been removed from its context.
2017-06-06 16:37:32.465 WheelTech[2242:256244] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'booking' between objects in different contexts (source =  (entity: Job; id: 0x1951ade0  ;
* First throw call stack:
(0x24eb391b 0x2464ee17 0x269a2475 0x269a0fb1 0xa7c00 0xa8338 0x11bb38 0x26a0d4b7 0x1f72493 0x1f6ade1 0x1f73ecf 0x1f737cf 0x24be5b29 0x24be5718)
libc++abi.dylib: terminating with uncaught exception of type NSException


问:
Why can't I view or edit Umbraco templates?
When I open the Umbraco (7.6.3) backoffice, I'm unable to view or make changes to templates. It seems like other functionality is unaffected, and I can create & edit specific pages. However, attempting to open the templates themselves just leads to a white screen. This problem exists across browsers:

Other screens render just fine:

What gives?

Checking the console when attempting to load gives an interesting error:

```<code>Error: Argument 'Umbraco.Editors.Templates.EditController' is not a function, got undefined...
</code>```

Resolution:

The issue seemed to be caused by outdated files in the Umbraco folder. Copying most directories over from packages\UmbracoCms.7.6.3\UmbracoFiles\umbraco\ seems to have done the trick.

Looking at the changelog, it seems like the JS folder was the most influential in getting this fixed.

答:
Are you sure that you're on 7.6.3? The UI appears to be pre-7.6 (I can tell because the colours haven't been updated).

If you have just upgraded, it's possible that your browser has cached the JS which is used - hard refresh your browser to see if the UI updates.

Umbraco also uses a dependency service to compile all of the used JS/CSS files together into one large one. This service will not be used if your website is in debug mode. Either:

Turn debug mode on in the Web.config

Delete any files in the \App_Data\ClientDependency\ folder as this is where the cached compiled files are kept (these will be regenerated)

Body:
When I open the Umbraco (7.6.3) backoffice, I'm unable to view or make changes to templates. It seems like other functionality is unaffected, and I can create & edit specific pages. However, attempting to open the templates themselves just leads to a white screen. This problem exists across browsers:

Other screens render just fine:

What gives?

Checking the console when attempting to load gives an interesting error:

Error: Argument 'Umbraco.Editors.Templates.EditController' is not a function, got undefined...

Resolution:

The issue seemed to be caused by outdated files in the Umbraco folder. Copying most directories over from packages\UmbracoCms.7.6.3\UmbracoFiles\umbraco\ seems to have done the trick.

Looking at the changelog, it seems like the JS folder was the most influential in getting this fixed.


问:
Apache Ignite - setting IP and Port on EC2
Installed Apache Ignite on EC2 and started Ignite node with:

```<code>bin/ignite.sh examples/config/example-cache.xml
</code>```

That worked fine on EC2 but could not access node from remote host.

Then changed inside exmaple-cache.xml part under:

```<code><!-- In distributed environment, replace with actual host IP address. -->
</code>```

and added ip of that EC2 and then port 80 (which is open for that EC2):

```<code><value>x.x.x.x:80</value>
</code>```

Restarted Ignite but was still not accessible from remote host after that.
What is the correct way to enable remote access? Where exactly should be specified IP and Port in order to be accessible from outside of EC2?

答:
If you use TcpDiscoveryMulticastIpFinder, you should add addresses of all nodes, that should be in cluster, for example:

```<code><bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">
       <property name="addresses">
           <list>
                   <value>127.0.0.1:47500..47509</value>
                   <value>127.0.0.2:47500..47509</value>
           </list>
       </property>
</bean>
</code>```

But for AWS you also could use TcpDiscoveryS3IpFinder, that was created specially for Amazon S3. Here is a documentation

Also, all nodes in cluster should have same configuration for Discovery.

ContentLicense: CC BY-SA 4.0

Body:
Installed Apache Ignite on EC2 and started Ignite node with:

bin/ignite.sh examples/config/example-cache.xml

That worked fine on EC2 but could not access node from remote host.

Then changed inside exmaple-cache.xml part under:

and added ip of that EC2 and then port 80 (which is open for that EC2):

<value>x.x.x.x:80</value>

Restarted Ignite but was still not accessible from remote host after that.
What is the correct way to enable remote access? Where exactly should be specified IP and Port in order to be accessible from outside of EC2?

Body:
If you use TcpDiscoveryMulticastIpFinder, you should add addresses of all nodes, that should be in cluster, for example:

<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">
       <property name="addresses">
           <list>
                   <value>127.0.0.1:47500..47509</value>
                   <value>127.0.0.2:47500..47509</value>
           </list>
       </property>
</bean>

But for AWS you also could use TcpDiscoveryS3IpFinder, that was created specially for Amazon S3. Here is a documentation

Also, all nodes in cluster should have same configuration for Discovery.


问:
Django: How to get all users with profiles as JSON (extended User model)
I have extended the default User model in Django. Now my models look like following:

```<code>class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birth_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.now)
phone_number = models.CharField(max_length=13, blank=True, default="")
address = models.CharField(max_length=100, blank=True, default="")
organization = models.ForeignKey(Organization, blank=True, null=True)
</code>```

Everything works fine, I am able to add new users through admin panel and so on.
However, I have got a problem. I need to return a customize JSON response to certain request in form of:

```<code>[
{"firs_name": first_name, "phone_number": phone_number, ...},
{"firs_name": first_name, "phone_number": phone_number, ...},
...
]
</code>```

As you can see, the phone_number attribute belongs to the Profile model, and I cannot get ALL users with their Profiles included (I am able to get only id of user).
Here is the response I get for now:

```<code>[{"username": "user", "profile": 2, "first_name": "User", "last_name": "User"}, {"username": "user1", "profile": 3, "first_name": "User1", "last_name": "User1"}, {"username": "user2", "profile": 4, "first_name": "User2", "last_name": "User2"}]
</code>```

Question: Is there any way to get all user objects with profile information included in it through User.Objects.all()?

Thanks!

P.S.:
This is how I make custom JSON response:

```<code>def get_users_as_json(request):
all_users = User.objects.all().values("username", "first_name", "last_name", 'profile')
user_list = list(all_users)
return JsonResponse(user_list, safe=False)
</code>```

答:
You can implement Django-rest-framework and then just repeat this instruction Django Rest Framework nested object response

I will recommend you to read about how to extend Django user model because it looks like you model Profile is just extended User model
https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#extending-user

Body:
I have extended the default User model in Django. Now my models look like following:

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birth_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.now)
phone_number = models.CharField(max_length=13, blank=True, default="")
address = models.CharField(max_length=100, blank=True, default="")
organization = models.ForeignKey(Organization, blank=True, null=True)

Everything works fine, I am able to add new users through admin panel and so on.
However, I have got a problem. I need to return a customize JSON response to certain request in form of:

[
{"firs_name": first_name, "phone_number": phone_number, ...},
{"firs_name": first_name, "phone_number": phone_number, ...},
...
]

As you can see, the phone_number attribute belongs to the Profile model, and I cannot get ALL users with their Profiles included (I am able to get only id of user).
Here is the response I get for now:

[{"username": "user", "profile": 2, "first_name": "User", "last_name": "User"}, {"username": "user1", "profile": 3, "first_name": "User1", "last_name": "User1"}, {"username": "user2", "profile": 4, "first_name": "User2", "last_name": "User2"}]

Question: Is there any way to get all user objects with profile information included in it through User.Objects.all()?

Thanks!

P.S.:
This is how I make custom JSON response:

def get_users_as_json(request):
all_users = User.objects.all().values("username", "first_name", "last_name", 'profile')
user_list = list(all_users)
return JsonResponse(user_list, safe=False)


问:
Join many tables using query
I want to add Count(Taskid),and Count(Complete) on first queries when Restaurantid = StoreID. But I have no idea how to make one query to make one table. Any ideas please?</p>

```<code> private DataTable GetData() //get any data from database SeongsilApp
{
    string connString = @"aa.net;Initial Catalog=db_c;Persist Security Info=True;User ID=db_c_ExternalWriter;Password=aa";
    string query = "Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem as 'Taskid' FROM Stores a, tblConcepts b, tblStates c WHERE a.ConceptID = b.Restaurantid AND  a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime)";
    string query2 = "SELECT StoreID, Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID";
    string query3 = "SELECT StoreID, Count(Complete) FROM tblAssignedTasks WHERE TargetDate <= cast(cast(getdate() as date) as datetime) AND Complete = 'True' GROUP BY StoreID";

    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                    sda.Fill(dt);
                    return dt;
            }
        }
    }
}
</code>```

答:
You can write inner SELECT queries to get the counts along with the main query. Also, for JOIN, it's better to use ON syntax than specifying conditions in WHERE clause, e.g.:

```<code>Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem as 'Taskid',
(SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' AND StoreID = b.Restaurantid) AS `completed`,
(SELECT Count(Complete) FROM tblAssignedTasks WHERE TargetDate <= cast(cast(getdate() as date) as datetime) AND Complete = 'True' AND StoreID = b.Restaurantid) AS `target`
FROM Stores a JOIN tblConcepts b ON a.ConceptID = b.Restaurantid
JOIN tblStates c ON a.State = c.Stateid
WHERE a.[Open Date] >= cast(cast(getdate() as date) as datetime)
</code>```

Title: Join many tables using query

Body:
I want to add Count(Taskid),and Count(Complete) on first queries when Restaurantid = StoreID. But I have no idea how to make one query to make one table. Any ideas please?

 private DataTable GetData() //get any data from database SeongsilApp
{
    string connString = @"aa.net;Initial Catalog=db_c;Persist Security Info=True;User ID=db_c_ExternalWriter;Password=aa";
    string query = "Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem as 'Taskid' FROM Stores a, tblConcepts b, tblStates c WHERE a.ConceptID = b.Restaurantid AND  a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime)";
    string query2 = "SELECT StoreID, Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID";
    string query3 = "SELECT StoreID, Count(Complete) FROM tblAssignedTasks WHERE TargetDate <= cast(cast(getdate() as date) as datetime) AND Complete = 'True' GROUP BY StoreID";

    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                    sda.Fill(dt);
                    return dt;
            }
        }
    }
}

Body:
You can write inner SELECT queries to get the counts along with the main query. Also, for JOIN, it's better to use ON syntax than specifying conditions in WHERE clause, e.g.:

Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem as 'Taskid',
(SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' AND StoreID = b.Restaurantid) AS `completed`,
(SELECT Count(Complete) FROM tblAssignedTasks WHERE TargetDate <= cast(cast(getdate() as date) as datetime) AND Complete = 'True' AND StoreID = b.Restaurantid) AS `target`
FROM Stores a JOIN tblConcepts b ON a.ConceptID = b.Restaurantid
JOIN tblStates c ON a.State = c.Stateid
WHERE a.[Open Date] >= cast(cast(getdate() as date) as datetime)


问:
Compare query results against integer in PL/SQL
I have written following query.

```<code>  IF ( select count(*)
        from source_table
       where id=Code
         and to_date(start_date, 'dd/mm/yyyy') <= sysdate
         and to_date(end_date, 'dd/mm/yyyy')>=sysdate)>0
  THEN
    checkWithinDateTime:=1;
  END IF;
</code>```

every time i try to execute my procedure, it shows error on if condition.

答:
You can not check the result of a query that way; you need a variable to handle the result of the query:

```<code>SQL> begin
  2      if (select count(1) from dual) = 1 then
  3          dbms_output.put_line('One');
  4      else
  5          dbms_output.put_line('Not one');
  6      end if;
  7  end;
  8  /
    if (select count(1) from dual) = 1 then
        *
ERROR at line 2:
ORA-06550: line 2, column 9:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:[...]
</code>```

You need instead:

```<code>SQL> declare
  2      vCount number;
  3  begin
  4      select count(1)
  5      into vCount
  6      from dual;
  7      if vCount = 1 then
  8          dbms_output.put_line('One');
  9      else
 10          dbms_output.put_line('Not one');
 11      end if;
 12  end;
 13  /
One

PL/SQL procedure successfully completed.

SQL>
</code>```

Body:
I have written following query.

  IF ( select count(*)
        from source_table
       where id=Code
         and to_date(start_date, 'dd/mm/yyyy') <= sysdate
         and to_date(end_date, 'dd/mm/yyyy')>=sysdate)>0
  THEN
    checkWithinDateTime:=1;
  END IF;

every time i try to execute my procedure, it shows error on if condition.

Body:
You can not check the result of a query that way; you need a variable to handle the result of the query:

SQL> begin
  2      if (select count(1) from dual) = 1 then
  3          dbms_output.put_line('One');
  4      else
  5          dbms_output.put_line('Not one');
  6      end if;
  7  end;
  8  /
    if (select count(1) from dual) = 1 then
        *
ERROR at line 2:
ORA-06550: line 2, column 9:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:[...]

You need instead:

SQL> declare
  2      vCount number;
  3  begin
  4      select count(1)
  5      into vCount
  6      from dual;
  7      if vCount = 1 then
  8          dbms_output.put_line('One');
  9      else
 10          dbms_output.put_line('Not one');
 11      end if;
 12  end;
 13  /
One

PL/SQL procedure successfully completed.

SQL>


问:
Convert binary number 5 into list of intergers (4,1)
I have a configuration value expressed as a binary number to allow several options within the same value.

E.g. the value of 5 would be "101" or both 4 and 1.

Does anyone know of the best/fastest way to "input" the value '5' and get a list of {1,4} back?

答:
The naive approach:

```<code>int originalInput = 42;
int input = originalInput;

// Generate binary numbers
var binaryNumbers = Enumerable.Range(0, 31).Select(n => (int)Math.Pow(2, n)).ToArray();

// Largest first
Array.Reverse(binaryNumbers);

var result = new List<int>();

foreach (var bin in binaryNumbers)
{
    if (input >= bin)
    {
        result.Add(bin);
        input -= bin;
    }
}

Console.WriteLine($"{originalInput} decomposed: " + string.Join(" ", result));
</code>```

Generate a range of power-of-two numbers, ranging from 2^31 (1073741824) to 2^0 (1), then check whether the input is equal to or larger than those numbers, and if so, add that number to the result list and subtract it from the input.

Now that that's all written out, see how Sergey's answer greatly reduces the code required by some Linq and bitshifting magic.

A hybrid solution, inspired by combining both answers:

```<code>var input = 42;

var output = Enumerable.Range(0, 31)
                       .Select(n => (int)Math.Pow(2, n))
                       .Where(p => (p & input) > 0);

Console.WriteLine($"{input} decomposed: " + string.Join(" ", output));
</code>```

Body:
The naive approach:

int originalInput = 42;
int input = originalInput;

// Generate binary numbers
var binaryNumbers = Enumerable.Range(0, 31).Select(n => (int)Math.Pow(2, n)).ToArray();

// Largest first
Array.Reverse(binaryNumbers);

var result = new List<int>();

foreach (var bin in binaryNumbers)
{
    if (input >= bin)
    {
        result.Add(bin);
        input -= bin;
    }
}

Console.WriteLine($"{originalInput} decomposed: " + string.Join(" ", result));

Generate a range of power-of-two numbers, ranging from 2^31 (1073741824) to 2^0 (1), then check whether the input is equal to or larger than those numbers, and if so, add that number to the result list and subtract it from the input.

Now that that's all written out, see how Sergey's answer greatly reduces the code required by some Linq and bitshifting magic.

A hybrid solution, inspired by combining both answers:

var input = 42;

var output = Enumerable.Range(0, 31)
                       .Select(n => (int)Math.Pow(2, n))
                       .Where(p => (p & input) > 0);

Console.WriteLine($"{input} decomposed: " + string.Join(" ", output));


答:
I have made this little sample. Here you obtain from an integer its value as a sum of its powers of two. Thosw powers should be your input options

```<code>class Program
    {
        static void Main(string[] args)
        {
            var input = 5;
            var options = new List<uint>();

            for (uint currentPow = 1; currentPow != 0; currentPow <<= 1)
                if ((currentPow & input) != 0)
                    options.Add(currentPow);

            foreach (var option in options)
                Console.WriteLine(option);

            Console.ReadLine();
        }
    }
</code>```

And the output is: 1 4

EDIT>>> In fact this does the same as @Sergey Berezovskiy answer but without LINQ

Hope it helps

Title: Convert binary number 5 into list of intergers (4,1)

Body:
I have a configuration value expressed as a binary number to allow several options within the same value.

E.g. the value of 5 would be "101" or both 4 and 1.

Does anyone know of the best/fastest way to "input" the value '5' and get a list of {1,4} back?

Body:
I have made this little sample. Here you obtain from an integer its value as a sum of its powers of two. Thosw powers should be your input options

class Program
    {
        static void Main(string[] args)
        {
            var input = 5;
            var options = new List<uint>();

            for (uint currentPow = 1; currentPow != 0; currentPow <<= 1)
                if ((currentPow & input) != 0)
                    options.Add(currentPow);

            foreach (var option in options)
                Console.WriteLine(option);

            Console.ReadLine();
        }
    }

And the output is: 1 4

EDIT>>> In fact this does the same as @Sergey Berezovskiy answer but without LINQ

Hope it helps


问:
Multiparty read uploaded file content
How can I get uploaded file content using multiparty in node.js? I don't need temp file, I need to redirect all stream into Google Cloud Storage in order to save the file content, but I can't find the way to get this content with events.</p>

答:
Found the answer. We need to use part stream a subscribe to standard streams events, like, data and end in order to receive file's data.

```<code>part.on("data", chunk => {
    writeStream.write(chunk);
});

part.on("end", chunk => {
    writeStream.end(chunk);
});
</code>```

writeStream - is a another stream where you want to put your data. In my case that was Google Cloud Storage file PUT request via signedUrl.
part - is a part object of a form part event

Title: Multiparty read uploaded file content

Body:
Found the answer. We need to use part stream a subscribe to standard streams events, like, data and end in order to receive file's data.

part.on("data", chunk => {
    writeStream.write(chunk);
});

part.on("end", chunk => {
    writeStream.end(chunk);
});

writeStream - is a another stream where you want to put your data. In my case that was Google Cloud Storage file PUT request via signedUrl.
part - is a part object of a form part event


问:
Does MonoTouch work on a virtualized Mac OS?
Is it possible to install it on VirtualBox or other virtualization solution? If yes, how fast it works?</p>

答:
We were able to develop and deploy apps to real devices under VMWare Player and WMWare workstation.  The problem we have is MonoTouch activations.  It would activate and randomly need reactivation.  It would work for a while then it would fail to activate.

Each time it failed we would need to contact support and reset the key so we could continue working.  They do not support virtualized hardware and do not plan to fix the activation issue.

In the end we purchased real hardware.


问:
To pull 1 record out of multiple records having same data in a field based on other fields
```<code> A | B | C | D | E
 a   y   6   12  21
 b   n   3   10  5
 c   n   4   12  12
 c   n   7   12   2
 c   y   1   12  22
 d   n   6   10  32
 d   n   7   10  32
</code>```

OUTPUT TABLE:

```<code>A | B | C | F
a   y   6   21
b   n   3   12
c   y   1   22
d   n   6   10
</code>```

I have a table that contains certain fields. From that table I want to remove duplicate records in A and produce the output table.

Now, the field F is calculated based on the field C when there are no duplicates for the records in A. So, if there is only one record of a in A then if C>5 then the F Column(Output table) pulls the record in E column. So, if record b has the value <5 in field C, then the F column (output table) will pull the record in D column for b. I have been able to achieve this using a case statement.

However, when there are duplicate records in column A, I want only one of the records based on the column B. Only that record should be pulled that has the value 'y' in column B and where the column F contains the value from column E. If none of the duplicate records in A have a value of 'n' in the B column, then pull any record with column D as column F in the output table. I am not able to figure out this part.

Please let me know if anything is not clear.

Code I am using:

```<code>SELECT A,B,C,
  CASE
    WHEN (SELECT COUNT(*) FROM MyTable t2 WHERE t1.A=t2.A)>1
      THEN (SELECT TOP 1 CASE WHEN b='y' THEN E ELSE D END
            FROM MyTable t3
            WHERE t3.A=t1.A
            ORDER BY CASE WHEN b='y' THEN 0 ELSE 1 END)
    ELSE {

case when cast(C  as float) >= 5.00  then (Case when E = '0.00' then D else E end)
     when  cast(C  as float)< 5.00   then D end )

}
  END AS F
FROM MyTable t1
</code>```

答:
You might want to encapsulate this logic in a Function to make it look cleaner, but the logic would go like this:

IF the record count of rows in the table with the same value for A as the current row is greater than 1, THEN SELECT the TOP 1 record with this value for A ORDER BY CASE WHEN b='y' THEN 0 ELSE 1 END

Use another CASE WHEN b='y' to determine if you will use column E or D for output column F.

And ELSE (the record count is not greater than 1), use your existing CASE expression.

EDIT:   Here is a more psuedo-codey explanation:

```<code>WITH cte AS (SELECT A,B,C,
  ROW_NUMBER() OVER (PARTITION BY A, ORDER BY CASE WHEN b='y' THEN 0 ELSE 1 END) rn
FROM MyTable
)
 SELECT A,B,C,
  CASE
    WHEN (SELECT COUNT(*) FROM MyTable t2 WHERE t1.A=t2.A)>1
      THEN CASE WHEN b='y' THEN E ELSE D END
    ELSE {use your existing CASE Expression}
  END AS F
FROM cte t1
WHERE rn=1
</code>```

Body:
 A | B | C | D | E
 a   y   6   12  21
 b   n   3   10  5
 c   n   4   12  12
 c   n   7   12   2
 c   y   1   12  22
 d   n   6   10  32
 d   n   7   10  32

OUTPUT TABLE:

A | B | C | F
a   y   6   21
b   n   3   12
c   y   1   22
d   n   6   10

I have a table that contains certain fields. From that table I want to remove duplicate records in A and produce the output table.

Now, the field F is calculated based on the field C when there are no duplicates for the records in A. So, if there is only one record of a in A then if C>5 then the F Column(Output table) pulls the record in E column. So, if record b has the value <5 in field C, then the F column (output table) will pull the record in D column for b. I have been able to achieve this using a case statement.

However, when there are duplicate records in column A, I want only one of the records based on the column B. Only that record should be pulled that has the value 'y' in column B and where the column F contains the value from column E. If none of the duplicate records in A have a value of 'n' in the B column, then pull any record with column D as column F in the output table. I am not able to figure out this part.

Please let me know if anything is not clear.

Code I am using:

SELECT A,B,C,
  CASE
    WHEN (SELECT COUNT(*) FROM MyTable t2 WHERE t1.A=t2.A)>1
      THEN (SELECT TOP 1 CASE WHEN b='y' THEN E ELSE D END
            FROM MyTable t3
            WHERE t3.A=t1.A
            ORDER BY CASE WHEN b='y' THEN 0 ELSE 1 END)
    ELSE {

case when cast(C  as float) >= 5.00  then (Case when E = '0.00' then D else E end)
     when  cast(C  as float)< 5.00   then D end )

}
  END AS F
FROM MyTable t1

Body:
You might want to encapsulate this logic in a Function to make it look cleaner, but the logic would go like this:

IF the record count of rows in the table with the same value for A as the current row is greater than 1, THEN SELECT the TOP 1 record with this value for A ORDER BY CASE WHEN b='y' THEN 0 ELSE 1 END

Use another CASE WHEN b='y' to determine if you will use column E or D for output column F.

And ELSE (the record count is not greater than 1), use your existing CASE expression.

EDIT:   Here is a more psuedo-codey explanation:

WITH cte AS (SELECT A,B,C,
  ROW_NUMBER() OVER (PARTITION BY A, ORDER BY CASE WHEN b='y' THEN 0 ELSE 1 END) rn
FROM MyTable
)
 SELECT A,B,C,
  CASE
    WHEN (SELECT COUNT(*) FROM MyTable t2 WHERE t1.A=t2.A)>1
      THEN CASE WHEN b='y' THEN E ELSE D END
    ELSE {use your existing CASE Expression}
  END AS F
FROM cte t1
WHERE rn=1


问:
Send a message to Kerberized Kafka. from kafka template (spring-kafka) version 1.15 (not using Spring boot)
Using this kafka integration project  version 1.15 due to compatible issues.How to use send message to Kerberized kafka ,we are not using spring boot .how to set the properties to send the message to kafka?i tried to look for the documentation but couldnt find properties related to kerberos in ProducerConfig.</p>

答:
See the kafka documentation.

Set the sasl.jaas.config property as described there:

```<code>sasl.jaas.config=com.sun.security.auth.module.Krb5LoginModule required \
    useKeyTab=true \
    storeKey=true  \
    keyTab="/etc/security/keytabs/kafka_client.keytab" \
    principal="kafka-client-1@EXAMPLE.COM";
</code>```

and also

```<code>security.protocol=SASL_PLAINTEXT (or SASL_SSL)
sasl.mechanism=GSSAPI
sasl.kerberos.service.name=kafka
</code>```

Body:
See the kafka documentation.

Set the sasl.jaas.config property as described there:

sasl.jaas.config=com.sun.security.auth.module.Krb5LoginModule required \
    useKeyTab=true \
    storeKey=true  \
    keyTab="/etc/security/keytabs/kafka_client.keytab" \
    principal="kafka-client-1@EXAMPLE.COM";

and also

security.protocol=SASL_PLAINTEXT (or SASL_SSL)
sasl.mechanism=GSSAPI
sasl.kerberos.service.name=kafka


问:
Abstract class and unique pointer
I have the following error in my code:

error: allocating an object of abstract class type 'Material'

I don't know how to handle this case.

I'm aware that std::make_unique performs an allocation, so it can't allocate the object of type Material, but I don't know how to correct it.

```<code>#include <iostream>
#include <memory>

struct Material
{
  Material() = default;
  virtual int get_color() const = 0;
};

struct Basic : public Material
{
  Basic() = default;
  virtual int get_color() const override
  {
    return 1;
  }
};

struct Mix : public Material
{
  Mix(const Material& mat1, const Material& mat2)
    : mat1_(std::make_unique<Material>(mat1))
    , mat2_(std::make_unique<Material>(mat2))
  {}

  virtual int get_color() const override
  {
    return mat1_->get_color() + mat2_->get_color();
  }
private:
  std::unique_ptr<Material> mat1_;
  std::unique_ptr<Material> mat2_;
};

int main()
{
  auto mix = Mix(Basic(), Basic());
  std::cout << mix.get_color() << '\n';
}
</code>```

答:
This call:

```<code>std::make_unique<Material>(mat1)
</code>```

tries to create an instance of class Material, it is irrelevant what type mat1 has. You seem to need method clone() in your class:

```<code>class Material {
...
    virtual std::unique_ptr<Material> clone() const = 0;
};
</code>```

then Mix ctor would be:

```<code>Mix(const Material& mat1, const Material& mat2)
    : mat1_(mat1.clone())
    , mat2_(mat2.clone())
  {}
</code>```

and you need to implement clone() in every derived class:

```<code>struct Basic : public Material
{
  Basic() = default;

  virtual std::unique_ptr<Material> clone() const override
  {
      return std::make_unique<Basic>( *this );
  }

  virtual int get_color() const override
  {
    return 1;
  }
};
</code>```

Title: Abstract class and unique pointer

Body:
I have the following error in my code:

error: allocating an object of abstract class type 'Material'

I don't know how to handle this case.

I'm aware that std::make_unique performs an allocation, so it can't allocate the object of type Material, but I don't know how to correct it.

#include <iostream>
#include <memory>

struct Material
{
  Material() = default;
  virtual int get_color() const = 0;
};

struct Basic : public Material
{
  Basic() = default;
  virtual int get_color() const override
  {
    return 1;
  }
};

struct Mix : public Material
{
  Mix(const Material& mat1, const Material& mat2)
    : mat1_(std::make_unique<Material>(mat1))
    , mat2_(std::make_unique<Material>(mat2))
  {}

  virtual int get_color() const override
  {
    return mat1_->get_color() + mat2_->get_color();
  }
private:
  std::unique_ptr<Material> mat1_;
  std::unique_ptr<Material> mat2_;
};

int main()
{
  auto mix = Mix(Basic(), Basic());
  std::cout << mix.get_color() << '\n';
}

Body:
This call:

std::make_unique<Material>(mat1)

tries to create an instance of class Material, it is irrelevant what type mat1 has. You seem to need method clone() in your class:

class Material {
...
    virtual std::unique_ptr<Material> clone() const = 0;
};

then Mix ctor would be:

Mix(const Material& mat1, const Material& mat2)
    : mat1_(mat1.clone())
    , mat2_(mat2.clone())
  {}

and you need to implement clone() in every derived class:

struct Basic : public Material
{
  Basic() = default;

  virtual std::unique_ptr<Material> clone() const override
  {
      return std::make_unique<Basic>( *this );
  }

  virtual int get_color() const override
  {
    return 1;
  }
};


问:
In Java, why have a code block with no keywords, just curly brackets
I'm re-factoring some inherited code, but was stumped by the design decision and can't figure out the proper terms to google this. My predecessor would use blocks like this one:

```<code>public class ChildClass extends ParentClass {
    {
        inheritedVar = "someVal";
    }

    public ChildClass(){ /* constructor exists */ }
    // rest of code
}
</code>```

What is the point of declaring a block of code with no keyword? It doesn't behave like a static block, I don't believe. Is it an alternative to setting in the constructor? Would this have some effect if a factory was being used (which in this case it's not)? I found a related thread here on this happening in C but the reasoning (scope & variable declaration) didn't seem relevant to Java.

Any thoughts or ideas on the "why" of this would be appreciated. It's easy enough to re-factor this, I'm just curious at this point.

答:
Your predecessor was still learning.

That's the best explanation you're likely to get.  Perhaps at one point in time there was a need to have the code split up like this.  It's hard to say.  The code should certainly be written like this instead:

```
public class ChildClass extends ParentClass {
    public ChildClass() {
        inheritedVar = "someVal";
    }
    // rest of code
}
```

As for the initializer block, its purpose has been given by the other answers here.  I threw my answer in as an attempt to answer the "why", which you requested.  Unfortunately, for the real answer, you would have to ask your predecessor.

Body:
I'm re-factoring some inherited code, but was stumped by the design decision and can't figure out the proper terms to google this. My predecessor would use blocks like this one:

public class ChildClass extends ParentClass {
    {
        inheritedVar = "someVal";
    }

    public ChildClass(){ /* constructor exists */ }
    // rest of code
}

What is the point of declaring a block of code with no keyword? It doesn't behave like a static block, I don't believe. Is it an alternative to setting in the constructor? Would this have some effect if a factory was being used (which in this case it's not)? I found a related thread here on this happening in C but the reasoning (scope & variable declaration) didn't seem relevant to Java.

Any thoughts or ideas on the "why" of this would be appreciated. It's easy enough to re-factor this, I'm just curious at this point.

Body:
Your predecessor was still learning.

That's the best explanation you're likely to get.  Perhaps at one point in time there was a need to have the code split up like this.  It's hard to say.  The code should certainly be written like this instead:

public class ChildClass extends ParentClass {
    public ChildClass() {
        inheritedVar = "someVal";
    }
    // rest of code
}

As for the initializer block, its purpose has been given by the other answers here.  I threw my answer in as an attempt to answer the "why", which you requested.  Unfortunately, for the real answer, you would have to ask your predecessor.


问:
Objective C generate random id for object that does not repeat
I want to generate unique ids for object identification, I've come across [[NSUUID UUID] UUIDString], can it be used for unique identification? or there's a better approach for generating?

答:
You may use the following </p>

```<code>CFUUIDRef udidCFUUIDRef = CFUUIDCreate(NULL);
NSString *UUIDString = (NSString *) CFBridgingRelease(CFUUIDCreateString(NULL, udidCFUUIDRef));
</code>```

Body:
You may use the following

CFUUIDRef udidCFUUIDRef = CFUUIDCreate(NULL);
NSString *UUIDString = (NSString *) CFBridgingRelease(CFUUIDCreateString(NULL, udidCFUUIDRef));


答:
If your data is just like you showed, you needn't worry about the brackets. You may use a POSIX ERE enabled with -E (or -r in some other distributions) like this:

```<code>sed -i -E 's/([0-9]{2})([0-9]*)\.([0-9]+)/\1.\2\3/g' large_file.geojson
</code>```

Or a POSIX BRE:

```<code>sed -i 's/\([0-9]\{2\}\)\([0-9]*\)\.\([0-9]\+\)/\1.\2\3/g' large_file.geojson
</code>```

See an online demo.

You may see how this regex works here (just a demo, not proof).

Note that in POSIX BRE you need to escape { and } in limiting / range quantifiers and ( and ) in grouping constructs, and the + quantifier, else they denote literal symbols. In POSIX ERE, you do not need to escape the special chars to make them special, this POSIX flavor is closer to the modern regexes.

Also, you need to use \n notation inside the replacement pattern, not $n.

Title: sed regexp, number reformatting: how to escape for bash

Body:
I have a working (in macOS app Patterns) RegExp that reformats GeoJSON MultiPolygon coordinates, but don't know how to escape it for sed.

The file I'm working on is over 90 Mb in size, so bash terminal looks like the ideal place and sed the perfect tool for the job.

Search Text Example:

[[[379017.735,6940036.7955],[379009.8431,6940042.5761],[379000.4869,6940048.9545],[378991.5455,6940057.8128],[378984.0665,6940066.0744],[378974.7072,6940076.2152],[378962.8639,6940090.5283],[378954.5822,6940101.4028],[378947.9369,6940111.3128],[378941.4564,6940119.5094],[378936.2565,6940128.1229],[378927.6089,6940141.4764],[378919.6611,6940154.0312],[378917.21,6940158.7053],[378913.7614,6940163.4443],[378913.6515,6940163.5893],[378911.4453,6940166.3531],

Desired outcome:

[[[37.9017735,69.400367955],[37.90098431,69.400425761],[37.90004869,69.400489545],[37.89915455,69.400578128],[37.89840665,69.400660744],[37.89747072,69.400762152],[37.89628639,69.400905283],[37.89545822,69.401014028],[37.89479369,69.401113128],[37.89414564,69.401195094],[37.89362565,69.401281229],[37.89276089,69.401414764],[37.89196611,69.401540312],[37.891721,69.401587053],[37.89137614,69.401634443],[37.89136515,69.401635893],[37.89114453,69.401663531],

My current RegExp:

((?:\[)[0-9]{2})([0-9]+)(\.)([0-9]+)(,)([0-9]{2})([0-9]+)(\.)([0-9]+(?:\]))

and reformatting:

$1\.$2$4,$6.$7$9

The command should be something along these lines:

sed -i -e 's/ The RegExp escaped /$1\.$2$4,$6.$7$9/g' large_file.geojson

But what should be escaped in the RegExp to make it work?
My attempts always complain of being unbalanced.

I'm sorry if this has already been answered elsewhere, but I couldn't find even after extensive searching.

Edit: 2017-01-07: I didn't make it clear that the file contains properties other than just the GPS-points. One of the other example values picked from GeoJSON Feature properties is "35.642.1.001_001", which should be left unchanged. The braces check in my original regex is there for this reason.

Body:
If your data is just like you showed, you needn't worry about the brackets. You may use a POSIX ERE enabled with -E (or -r in some other distributions) like this:

sed -i -E 's/([0-9]{2})([0-9]*)\.([0-9]+)/\1.\2\3/g' large_file.geojson

Or a POSIX BRE:

sed -i 's/\([0-9]\{2\}\)\([0-9]*\)\.\([0-9]\+\)/\1.\2\3/g' large_file.geojson

See an online demo.

You may see how this regex works here (just a demo, not proof).

Note that in POSIX BRE you need to escape { and } in limiting / range quantifiers and ( and ) in grouping constructs, and the + quantifier, else they denote literal symbols. In POSIX ERE, you do not need to escape the special chars to make them special, this POSIX flavor is closer to the modern regexes.

Also, you need to use \n notation inside the replacement pattern, not $n.


问:
flyway4, repeatable migration, dynamic checksum change, maven, always execute
I have a repeatable flyway sql migration script, that I want executed everytime flyway:migrate is called.

R__Always_Executed.sql:

```<code>/* Version: ${timestamp} <- changes on each execution */
...
</code>```

I define the placeholder timestamp in pom.xml:

```<code><properties>
    <flyway.placeholders.timestamp>${maven.build.timestamp}</flyway.placeholders.timestamp>
</properties>
</code>```

Each time I do

```<code>mvn clean install flyway:migrate
</code>```

the timestamp changes, therefore the file contents and with it the checksum should be different. Hence the script should get executed. It does not, however.

Anyone any idea, why flyway doesn't consider the placeholder replacements when calculating the checksum?

答:
Flyway calculates the migration checksum before the placeholders are replaced with actual values. This means ${timestamp} won't do the trick.

Instead of a repeatable migrations, you could use Flyway's callback mechanism. Create a SQL file called afterMigrate.sql and put it in the same directory as your migrations. It will be executed every time flyway:migrate is called. It's run after all the migrations have been executed – if you need to run it before the migrations, use beforeMigrate.sql.

Body:
I have a repeatable flyway sql migration script, that I want executed everytime flyway:migrate is called.

R__Always_Executed.sql:

/* Version: ${timestamp} <- changes on each execution */
...

I define the placeholder timestamp in pom.xml:

<properties>
    <flyway.placeholders.timestamp>${maven.build.timestamp}</flyway.placeholders.timestamp>
</properties>

Each time I do

mvn clean install flyway:migrate

the timestamp changes, therefore the file contents and with it the checksum should be different. Hence the script should get executed. It does not, however.

Anyone any idea, why flyway doesn't consider the placeholder replacements when calculating the checksum?


问:
Refreshing a div every 30 second with JavaScript
I'm trying to automatically update a div every 30 seconds.

```<code><script type="text/javascript">

    function refresh_handler() {
        function refresh() {
           $.get('/refresh/3', function(result) {
               $(".roek").innerHtml = result;
               console.log(result);
           });
        }
        setInterval(refresh, 3000); //every 5 minutes
    }

    $(document).ready(refresh_handler);

</script>
</code>```

Here I'm trying to refresh the div every 30 seconds.

```<code><div class="col-md-12">
    <div class="roek">
        @foreach ($hours as $hour)
            @if ($hour->repeat_day === "Monday")
                <p>
                    <div class="col-md-3">
                        <b> Day: </b> {{ $hour->repeat_day }} <a href="/deletehour/{{ $hour->id }}"> <span class="glyphicon glyphicon-info-sign" aria-hidden="true" style="color: cyan"></span></a> <br>

                        <b> Start: </b> {{ strftime("%H:%M", strtotime($hour->starttime))}} <br>
                        <b> End: </b> {{ strftime("%H:%M", strtotime($hour->endtime))}} <br>
                    </div>
                </p>
            @endif
        @endforeach
    </div>
</div>
</code>```

Currently it's trying to refresh the Div but it doesn't update it on the refresh.
In my web.php I have the following:

```<code>Route::get('/refresh/{id}', 'RefreshController@workhoursrefresh');
</code>```

And this is the query I'm using after the refresh:

```<code>//show all standard workhours per specific user
public function workhoursrefresh()
{
    $hours = Availability::FindAvailabilitys()->where([['user_id', '=', Auth::id()],
                                                       ['type', '=', 'standard']])
                                              ->orderBy('starttime', 'asc')
                                              ->get();
}
</code>```

答:
Debugging steps

Check the console tab of your browser's development tools for errors

Ensure the url /refresh/3 is being called using the network tab of your browser's development tools

Ensure that the url /refresh/3 returns the data you expect

Ensure at least one element with class="roek" is on your page

In your case, you are using jQuery - so use the html() method on the jQuery object as there is no innerHTML on jQuery.

Code:

```<code>function refresh_handler() {
    function refresh() {
         $.get('/refresh/3', function(result) {
             $(".roek").html(result);
             console.log(result);
         });
    }

    setInterval(refresh, 30000);
}

$(document).ready(refresh_handler);
</code>```

Body:
I'm trying to automatically update a div every 30 seconds.

Here I'm trying to refresh the div every 30 seconds.

        @foreach ($hours as $hour)
            @if ($hour->repeat_day === "Monday")

                         Day:  {{ $hour->repeat_day }} id }}">

                         Start:  {{ strftime("%H:%M", strtotime($hour->starttime))}}

                         End:  {{ strftime("%H:%M", strtotime($hour->endtime))}}

            @endif
        @endforeach

Currently it's trying to refresh the Div but it doesn't update it on the refresh.
In my web.php I have the following:

Route::get('/refresh/{id}', 'RefreshController@workhoursrefresh');

And this is the query I'm using after the refresh:

//show all standard workhours per specific user
public function workhoursrefresh()
{
    $hours = Availability::FindAvailabilitys()->where([['user_id', '=', Auth::id()],
                                                       ['type', '=', 'standard']])
                                              ->orderBy('starttime', 'asc')
                                              ->get();
}

Body:
Debugging steps

Check the console tab of your browser's development tools for errors

Ensure the url /refresh/3 is being called using the network tab of your browser's development tools

Ensure that the url /refresh/3 returns the data you expect

Ensure at least one element with class="roek" is on your page

In your case, you are using jQuery - so use the html() method on the jQuery object as there is no innerHTML on jQuery.

Code:

function refresh_handler() {
    function refresh() {
         $.get('/refresh/3', function(result) {
             $(".roek").html(result);
             console.log(result);
         });
    }

    setInterval(refresh, 30000);
}

$(document).ready(refresh_handler);


问:
Grunt not working: [nodemon] app crashed - waiting for file changes before starting
I am trying to do this tutoral mean app:

https://youtu.be/a-dn6k6Frq4?t=4m47s

When I run grunt i keep getting this and hav no idea what it means or what to do:

meanBlog $ grunt

Local Npm module "grunt-node-inspector" not found. Is it installed?
    (node:7760) DeprecationWarning: process.EventEmitter is deprecated. Use require('events') instead.

Running "env:dev" (env) task

Running "sass:dist" (sass) task

Running "less:dist" (less) task

Running "jshint:all" (jshint) task

87 files lint free.

Running "csslint:all" (csslint) task

2 files lint free.

Running "mkdir:upload" task

Running "copy:localConfig" (copy) task

Running "concurrent:default" (concurrent) task

Local Npm module "grunt-node-inspector" not found. Is it installed?
    Local Npm module "grunt-node-inspector" not found. Is it installed?

```<code>Running "watch" task
Waiting...
(node:7652) DeprecationWarning: process.EventEmitter is deprecated. Use require('events') instead.

Running "nodemon:dev" (nodemon) task
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: server.js config/**/*.js modules/*/server/**/*.js
[nodemon] starting `node --debug server.js`
(node:6160) DeprecationWarning: process.EventEmitter is deprecated. Use require('events') instead.
Debugger listening on [::]:5858

Could not connect to MongoDB!
{ MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
    at Pool.<anonymous> (C:\Users\andre\code\meanBlog\node_modules\mongoose\node_modules\mongodb-core\lib\topologies\server.js:328:35)
    at emitOne (events.js:96:13)
    at Pool.emit (events.js:188:7)
    at Connection.<anonymous> (C:\Users\andre\code\meanBlog\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:280:12)
    at Connection.g (events.js:292:16)
    at emitTwo (events.js:106:13)
    at Connection.emit (events.js:191:7)
    at Socket.<anonymous> (C:\Users\andre\code\meanBlog\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:177:49)
    at Socket.g (events.js:292:16)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at emitErrorNT (net.js:1277:8)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
  name: 'MongoError',
  message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]' }
C:\Program Files\nodejs\node.exe: src\debug-agent.cc:149: Assertion `(err) == (0)' failed.
[nodemon] app crashed - waiting for file changes before starting...
</code>```

答:
The mongodb was not installed.</p>

```<code>sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

sudo apt-get update

sudo apt-get install -y mongodb-org
</code>```

Body:
I am trying to do this tutoral mean app:

https://youtu.be/a-dn6k6Frq4?t=4m47s

When I run grunt i keep getting this and hav no idea what it means or what to do:

meanBlog $ grunt

Local Npm module "grunt-node-inspector" not found. Is it installed?
    (node:7760) DeprecationWarning: process.EventEmitter is deprecated. Use require('events') instead.

Running "env:dev" (env) task

Running "sass:dist" (sass) task

Running "less:dist" (less) task

Running "jshint:all" (jshint) task

87 files lint free.

Running "csslint:all" (csslint) task

2 files lint free.

Running "mkdir:upload" task

Running "copy:localConfig" (copy) task

Running "concurrent:default" (concurrent) task

Local Npm module "grunt-node-inspector" not found. Is it installed?
    Local Npm module "grunt-node-inspector" not found. Is it installed?

Running "watch" task
Waiting...
(node:7652) DeprecationWarning: process.EventEmitter is deprecated. Use require('events') instead.

Running "nodemon:dev" (nodemon) task
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: server.js config/**/*.js modules/*/server/**/*.js
[nodemon] starting `node --debug server.js`
(node:6160) DeprecationWarning: process.EventEmitter is deprecated. Use require('events') instead.
Debugger listening on [::]:5858

Could not connect to MongoDB!
{ MongoError: failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
    at Pool.<anonymous> (C:\Users\andre\code\meanBlog\node_modules\mongoose\node_modules\mongodb-core\lib\topologies\server.js:328:35)
    at emitOne (events.js:96:13)
    at Pool.emit (events.js:188:7)
    at Connection.<anonymous> (C:\Users\andre\code\meanBlog\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:280:12)
    at Connection.g (events.js:292:16)
    at emitTwo (events.js:106:13)
    at Connection.emit (events.js:191:7)
    at Socket.<anonymous> (C:\Users\andre\code\meanBlog\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:177:49)
    at Socket.g (events.js:292:16)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at emitErrorNT (net.js:1277:8)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
  name: 'MongoError',
  message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]' }
C:\Program Files\nodejs\node.exe: src\debug-agent.cc:149: Assertion `(err) == (0)' failed.
[nodemon] app crashed - waiting for file changes before starting...

Body:
The mongodb was not installed.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

sudo apt-get update

sudo apt-get install -y mongodb-org


问:
Angular 2 - Array of Objects is still undefined after a HTTP Request
I'm using this guide to learn angular 2 http requests. My array of objects is still undefined after an http.get() request.

Service code:

```<code>getUserCompaniesByUserId(userId: string) : Observable<ApplicationUserCompany[]> {
    return this.http.get(`${this.url}/${userId}`)
                    .map(res => res.json())
                    .catch(this.handleError);
}

private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }

    console.error(errMsg);
    return Observable.throw(errMsg);
}
</code>```

Component code:

```<code>getCompanies() {
    this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id'))
                            .subscribe(
                                uc => this.userCompanies = uc,
                                error => this.errorMsg = <any>error
                        );

    this.userCompanies.forEach(uc => {
        ...
        ...
    });
}
</code>```

Because the userCompanies array is undefined after the request, it won't enter in the forEach() loop. It throws this error: "TypeError: Cannot read property 'forEach' of undefined".

Not the request is the error, because I tested it with Postman and Application Insights (my API is .NET Core API). The response code is 200.
Somewhere else is the problem, but I cannot find it.

Thank you!

答:
I believe the issue is caused by the below code being fired before the http request is finished. Since the http request is ajax it get fired and then the code after that is fired.

You need to drop the below code into the callback of the subscription so that it only fires once you are sure response has been returned from the server.

```<code>this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id')).subscribe(
    uc => {
      this.userCompanies = uc;
      this.userCompanies.forEach(uc => { ... });
   },
   error => this.errorMsg = <any>error
  );
</code>```

Body:
I'm using this guide to learn angular 2 http requests. My array of objects is still undefined after an http.get() request.

Service code:

getUserCompaniesByUserId(userId: string) : Observable<ApplicationUserCompany[]> {
    return this.http.get(`${this.url}/${userId}`)
                    .map(res => res.json())
                    .catch(this.handleError);
}

private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }

    console.error(errMsg);
    return Observable.throw(errMsg);
}

Component code:

getCompanies() {
    this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id'))
                            .subscribe(
                                uc => this.userCompanies = uc,
                                error => this.errorMsg = <any>error
                        );

    this.userCompanies.forEach(uc => {
        ...
        ...
    });
}

Because the userCompanies array is undefined after the request, it won't enter in the forEach() loop. It throws this error: "TypeError: Cannot read property 'forEach' of undefined".

Not the request is the error, because I tested it with Postman and Application Insights (my API is .NET Core API). The response code is 200.
Somewhere else is the problem, but I cannot find it.

Thank you!

Body:
I believe the issue is caused by the below code being fired before the http request is finished. Since the http request is ajax it get fired and then the code after that is fired.

You need to drop the below code into the callback of the subscription so that it only fires once you are sure response has been returned from the server.

this.companyService.getUserCompaniesByUserId(localStorage.getItem('user_id')).subscribe(
    uc => {
      this.userCompanies = uc;
      this.userCompanies.forEach(uc => { ... });
   },
   error => this.errorMsg = <any>error
  );


问:
RichFaces FileUpload without Add Button and call by commandLink
I am using Richfaces 4 fileupload to upload one file.

But in my case i just want to click in one link and see the browser to select the file.

So in my code i have commandLink:

```<code><a4j:commandLink id="showFileUpload"
                    execute="@this"
                action="#{doSomething.Something(a)}"
                render="@none"
                oncomplete="#{rich:element('stratFileUpload')}.click();"
                >
                <h:graphicImage value="/images/A.png" />
            </a4j:commandLink>
</code>```

And the part of the fileUpload is just a form with the fileUpload on it:

```<code><h:form id="stratFileUploadForm">
    <rich:fileUpload id="stratFileUpload" execute="@this"
        fileUploadListener="#{doUploadedFile}"
        onuploadcomplete="
                                    jQuery(#{rich:element('stratFileUpload')}).find('.rf-fu-itm-lnk').click();
                                    "
        noDuplicate="true" maxFilesQuantity="1"
        sizeExceededLabel="#{msg['sizeExceeded']}"
        uploadLabel="#{msg['upload']}" />
</h:form>
</code>```

I already call in the commandLink the id form and rich:fileUpload id but nothing works.

The only way for this to work is with popup, and in that case it came with the "+ Add" button.

答:
Are you sure it's RichFaces 2.0?

Clicking on the fileUpload does nothing (just like if you click manually). You have to click on the file input, e.g.

```<code>$(".rf-fu-btn-cnt-add input").click()
</code>```

but I'm not sure if all browsers let you do that when the button is hidden.

Body:
I am using Richfaces 4 fileupload to upload one file.

But in my case i just want to click in one link and see the browser to select the file.

So in my code i have commandLink:

<a4j:commandLink id="showFileUpload"
                    execute="@this"
                action="#{doSomething.Something(a)}"
                render="@none"
                oncomplete="#{rich:element('stratFileUpload')}.click();"
                >
                <h:graphicImage value="/images/A.png" />
            </a4j:commandLink>

And the part of the fileUpload is just a form with the fileUpload on it:

<h:form id="stratFileUploadForm">
    <rich:fileUpload id="stratFileUpload" execute="@this"
        fileUploadListener="#{doUploadedFile}"
        onuploadcomplete="
                                    jQuery(#{rich:element('stratFileUpload')}).find('.rf-fu-itm-lnk').click();
                                    "
        noDuplicate="true" maxFilesQuantity="1"
        sizeExceededLabel="#{msg['sizeExceeded']}"
        uploadLabel="#{msg['upload']}" />
</h:form>

I already call in the commandLink the id form and rich:fileUpload id but nothing works.

The only way for this to work is with popup, and in that case it came with the "+ Add" button.

Body:
Are you sure it's RichFaces 2.0?

Clicking on the fileUpload does nothing (just like if you click manually). You have to click on the file input, e.g.

$(".rf-fu-btn-cnt-add input").click()

but I'm not sure if all browsers let you do that when the button is hidden.


问:
An easy if-statement
So there is probably a really easy solution to this, but I'm trying to get a message in a P when two players are inputted.. So far I've got this(some norwegian words there, sorry):

var spillere = [];

```<code>function myFunction() {
if(spillere.length > 0) {
 document.getElementById("printAppear").innerHTML = '<button onclick="Printresultat()">Print resultat</button>';
 }
if(spillere.length < 2) {
    var player_navn = document.getElementById('navn').value;
    var player_poeng = document.getElementById('poeng').value;
    spillere.push([player_navn, parseFloat(player_poeng)]);

    spillere.sort(function(a,b){
        return a[1] - b[1];
    });

    document.getElementById("demo").innerHTML = "";
    for(i = 0; i < spillere.length; i++) {
        document.getElementById("demo").innerHTML += (i+1) + ". " + spillere[i][0] + " - " + spillere[i][1] + " poeng<br />";
    }

}
</code>```

So I'm basically just wanting to get a text where it says "Congratulations" and then the name of the player who won in this:

```<code><p id="vinner"></p>
</code>```

spillere=players and vinner=winner

Hope you understand what I'm trying to do

答:
You could just add this line to the end of the function and assign the words you need and the name from first item of the array, which is obviously sorted by points.

```<code>document.getElementById("vinner").innerHTML = "Congratulations " + spillere[0][0];
</code>```

Edit, just with testing length of the array of having 8 items:

```<code>if (spillere.length === 8) {
    document.getElementById("vinner").innerHTML = "Congratulations " + spillere[0][0];
}
</code>```

Title: An easy if-statement

Body:
So there is probably a really easy solution to this, but I'm trying to get a message in a P when two players are inputted.. So far I've got this(some norwegian words there, sorry):

var spillere = [];

function myFunction() {
if(spillere.length > 0) {
 document.getElementById("printAppear").innerHTML = '<button onclick="Printresultat()">Print resultat</button>';
 }
if(spillere.length < 2) {
    var player_navn = document.getElementById('navn').value;
    var player_poeng = document.getElementById('poeng').value;
    spillere.push([player_navn, parseFloat(player_poeng)]);

    spillere.sort(function(a,b){
        return a[1] - b[1];
    });

    document.getElementById("demo").innerHTML = "";
    for(i = 0; i < spillere.length; i++) {
        document.getElementById("demo").innerHTML += (i+1) + ". " + spillere[i][0] + " - " + spillere[i][1] + " poeng
";
    }

}

So I'm basically just wanting to get a text where it says "Congratulations" and then the name of the player who won in this:

spillere=players and vinner=winner

Hope you understand what I'm trying to do

Body:
You could just add this line to the end of the function and assign the words you need and the name from first item of the array, which is obviously sorted by points.

document.getElementById("vinner").innerHTML = "Congratulations " + spillere[0][0];

Edit, just with testing length of the array of having 8 items:

if (spillere.length === 8) {
    document.getElementById("vinner").innerHTML = "Congratulations " + spillere[0][0];
}


问:
FuncOne() -and FuncTwo() not working
This is my code:

```<code>if (FuncOne($valOne) -and FuncTwo($valTwo)) {
    ...
}
</code>```

When both of those functions evaluate to $false, the code within the if statement still executes. Why is that? This also does not work as expected:

```<code>if (FuncOne($valOne) -eq $true -and FuncTwo($valTwo) -eq $true) {
    ...
}
</code>```

When written this way, it works as expected.

```<code>$a = FuncOne($valOne)
$b = FuncTwo($valTwo)

if($a -and $b) {
    ...
}
</code>```

What's going on?

答:
This is a syntax issue.

The correct syntax for invoking functions in PowerShell is not:

```<code>functionName($arg1[,$arg2,$arg3])
</code>```

but rather:

```<code>functionName [-parameterName1] $arg1 [[-parameterName2] $arg2]
</code>```

Now, let's apply this to your if() sample expression:

```<code>FuncOne $valOne -and FuncTwo $valTwo
</code>```

You'll notice that explicit parameter names (-ParameterName) and operators (-and) are completely indistinguishable - there's no way for the parser to tell whether -and is supposed to be interpreted as a parameter name or an operator. Additionally, the string literal FuncTwo can just as well be interpreted as a parameter argument, which is exactly what happens.

In order for the parser to know that you intend it to treat the expression as two separate expressions, force evaluation order with ():

```<code>if ((FuncOne $valOne) -and (FuncTwo $valTwo)) {
    # They both returns a truthy value
}
</code>```

Title: FuncOne() -and FuncTwo() not working

Body:
This is my code:

if (FuncOne($valOne) -and FuncTwo($valTwo)) {
    ...
}

When both of those functions evaluate to $false, the code within the if statement still executes. Why is that? This also does not work as expected:

if (FuncOne($valOne) -eq $true -and FuncTwo($valTwo) -eq $true) {
    ...
}

When written this way, it works as expected.

$a = FuncOne($valOne)
$b = FuncTwo($valTwo)

if($a -and $b) {
    ...
}

What's going on?

Body:
This is a syntax issue.

The correct syntax for invoking functions in PowerShell is not:

functionName($arg1[,$arg2,$arg3])

but rather:

functionName [-parameterName1] $arg1 [[-parameterName2] $arg2]

Now, let's apply this to your if() sample expression:

FuncOne $valOne -and FuncTwo $valTwo

You'll notice that explicit parameter names (-ParameterName) and operators (-and) are completely indistinguishable - there's no way for the parser to tell whether -and is supposed to be interpreted as a parameter name or an operator. Additionally, the string literal FuncTwo can just as well be interpreted as a parameter argument, which is exactly what happens.

In order for the parser to know that you intend it to treat the expression as two separate expressions, force evaluation order with ():

if ((FuncOne $valOne) -and (FuncTwo $valTwo)) {
    # They both returns a truthy value
}


问:
c# Serial port close
Already use this class, in Form1 and Form2

```<code>public class DataInput
{
    public event Action<string> DataReceived;

    private readonly SerialPort mySerialPort;

    public DataInput(string portName)
    {
        mySerialPort = new SerialPort();
        mySerialPort.PortName = portName;
        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
        mySerialPort.Open();
    }

    private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string received = mySerialPort.ReadExisting();
        DataReceived?.Invoke(received);
    }
}
</code>```

Now when i close Form2 with this.Close(); i need close the Serial port too.
Because when i opend the form again it says Access to the port 'COM1' is denied.

How can i close the port??

答:
You need to close serial port connection. You can call mySerialPort.Close() in Form2 closing event as below:

```<code>private void Form2_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
  if(mySerialPort.IsOpen)
  {
    mySerialPort.Close();
  }
}
</code>```

Title: c# Serial port close

Body:
Already use this class, in Form1 and Form2

public class DataInput
{
    public event Action<string> DataReceived;

    private readonly SerialPort mySerialPort;

    public DataInput(string portName)
    {
        mySerialPort = new SerialPort();
        mySerialPort.PortName = portName;
        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
        mySerialPort.Open();
    }

    private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string received = mySerialPort.ReadExisting();
        DataReceived?.Invoke(received);
    }
}

Now when i close Form2 with this.Close(); i need close the Serial port too.
Because when i opend the form again it says Access to the port 'COM1' is denied.

How can i close the port??

Body:
You need to close serial port connection. You can call mySerialPort.Close() in Form2 closing event as below:

private void Form2_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
  if(mySerialPort.IsOpen)
  {
    mySerialPort.Close();
  }
}


问:
The Program is not recording the first array, set as a null -- Java
I have a code here that creates an array and puts in people's names into it. However, the first array does not get recorded.

```<code>Scanner newscan = new Scanner(System.in);

    System.out.println("How many people in the group?");
    int groupnum = newscan.nextInt();

    String[] people = new String[groupnum];

    System.out.println("Put in the names of the people in the group");
    String name;

    int i = 0;
    do{
        System.out.println("Input Name");
        name = newscan.nextLine();
        people[i] = name;
        i++;
    }while(i<groupnum);
</code>```

The console shows results like this:

```<code>How many people in the group?
5
Put in the names of the people in the group
Input Name
Input Name
John
Input Name
Bob
Input Name
Denis
Input Name
Andrew
</code>```

I have tried using the debugger on IntelliJ, and it shows that whatever value I put in the first array, gets ignored and is set as a "" null value.

I have no idea to approach this problem.
It would be very helpful if you can tell me what part of my code is causing this problem and how to fix it.

答:
modify your code to this:

```<code>int groupnum = newscan.nextInt();
newscan.nextLine();
String[] people = new String[groupnum];
</code>```

and remember that newscan.nextInt(); is not consumming the newline character, that is the reason why the code is not working and why you get:

```<code>Input Name
Input Name
</code>```

twice in a row

Body:
I have a code here that creates an array and puts in people's names into it. However, the first array does not get recorded.

Scanner newscan = new Scanner(System.in);

    System.out.println("How many people in the group?");
    int groupnum = newscan.nextInt();

    String[] people = new String[groupnum];

    System.out.println("Put in the names of the people in the group");
    String name;

    int i = 0;
    do{
        System.out.println("Input Name");
        name = newscan.nextLine();
        people[i] = name;
        i++;
    }while(i<groupnum);

The console shows results like this:

How many people in the group?
5
Put in the names of the people in the group
Input Name
Input Name
John
Input Name
Bob
Input Name
Denis
Input Name
Andrew

I have tried using the debugger on IntelliJ, and it shows that whatever value I put in the first array, gets ignored and is set as a "" null value.

I have no idea to approach this problem.
It would be very helpful if you can tell me what part of my code is causing this problem and how to fix it.

Body:
modify your code to this:

int groupnum = newscan.nextInt();
newscan.nextLine();
String[] people = new String[groupnum];

and remember that newscan.nextInt(); is not consumming the newline character, that is the reason why the code is not working and why you get:

Input Name
Input Name

twice in a row


问:
2sxc | removing file path by trimming w/ Javascript method
I have the following file path displaying:

And I want to display only file name 'Doc1' (minus path and extension).

I have tried unsucessfully the following and would appreciate any further light you could share as to what I am doing wrong...

```<code>    @functions{
    public static string SplitWord(string text, int length)
    {
        string str = text;
        int n = str.LastIndexOf(".");
        string str1=str.Substring(n,str.LastIndexOf("/"));
        str1=str1.Substring(1,str1.Length);
        return str1;
    }
}
<ol>
    @foreach (var q in AsDynamic(App.Data["CatFilter"]))
    {
    <li class="sc-element faq-set faq-setOne" data-tags="@String.Join(",", ((List<DynamicEntity>)q.Categories).Select(a => AsDynamic(a).EntityId))">
        @q.Toolbar @Edit.Toolbar(actions: "edit,new", contentType: "CatFilter")
        <a class="faq-question" style="cursor: pointer">
            @if(!String.IsNullOrEmpty(q.LinkText))
            {
               SplitWord(@q.LinkText,@q.LinkText.Length);
            } else {
               SplitWord(@q.Link,@q.Link.Length);
            }
        </a>
    </li>
    }
</ol>
</code>```

I have also tried variations of the following within the IF condition but again no luck.

```<code>,,,,@:var str = q.Link;
,,,,@:var n = str.lastIndexOf(".");
,,,,@:var str1=str.Substring(n,str.lastIndexOf("/"))
,,,,@:str1=str1.Substring(1,str1.Length);
</code>```

Thx,

答:
You're actually just using Substring the wrong way. You probably want

```<code>public static string SplitWord(string text, int length)
{
    int slash = text.LastIndexOf("/");
    int dot = text.LastIndexOf(".");
    return text.Substring(slash + 1, dot - slash);
}
</code>```

Give it a try - might need another +1 or -1 on one of the values, but that should do the trick.

Body:
I have the following file path displaying:

And I want to display only file name 'Doc1' (minus path and extension).

I have tried unsucessfully the following and would appreciate any further light you could share as to what I am doing wrong...

    @functions{
    public static string SplitWord(string text, int length)
    {
        string str = text;
        int n = str.LastIndexOf(".");
        string str1=str.Substring(n,str.LastIndexOf("/"));
        str1=str1.Substring(1,str1.Length);
        return str1;
    }
}

    @foreach (var q in AsDynamic(App.Data["CatFilter"]))
    {
    <li class="sc-element faq-set faq-setOne" data-tags="@String.Join(",", ((List<DynamicEntity>)q.Categories).Select(a => AsDynamic(a).EntityId))">
        @q.Toolbar @Edit.Toolbar(actions: "edit,new", contentType: "CatFilter")

            @if(!String.IsNullOrEmpty(q.LinkText))
            {
               SplitWord(@q.LinkText,@q.LinkText.Length);
            } else {
               SplitWord(@q.Link,@q.Link.Length);
            }

    }

I have also tried variations of the following within the IF condition but again no luck.

,,,,@:var str = q.Link;
,,,,@:var n = str.lastIndexOf(".");
,,,,@:var str1=str.Substring(n,str.lastIndexOf("/"))
,,,,@:str1=str1.Substring(1,str1.Length);

Thx,

Body:
You're actually just using Substring the wrong way. You probably want

public static string SplitWord(string text, int length)
{
    int slash = text.LastIndexOf("/");
    int dot = text.LastIndexOf(".");
    return text.Substring(slash + 1, dot - slash);
}

Give it a try - might need another +1 or -1 on one of the values, but that should do the trick.