问:
rails helper to give a upload file a unique name?
Hey guys
I'm now working on a project that require upload a lot of videos, Does rails have this helper can handle this, like the address of youtube video :

www.youtube.com/watch?v=KYUhtPV_Lk4

Thanks

答:
are you using activerecord to model the files or are they simply flat files somewhere?

if you have a model like UploadedFile << ActiveRecord::Base for each file you can just use the id of the model or if you want a string you can hash it with some string added as salt.

```<code>irb(main):021:0> file_id = 1
=> 1
irb(main):022:0> Digest::SHA1.hexdigest('SomeRandomString' + file_id.to_s)
=> "70f5eedc8d4f02fd8f5d4e09ca8925c2f8d6b942"
</code>```

if you are simply keeping them as flat files on the system, you can hash their path+filename to create a unique string.

```<code>irb(main):016:0> Digest::SHA1.hexdigest '/home/bob/somefile.mp4'
=> "204a038eddff90637c529af7003e77d600428271"
</code>```

and you can always add in a timestamp of the current time and a random number to prevent dupes.

Body:
are you using activerecord to model the files or are they simply flat files somewhere?

if you have a model like UploadedFile << ActiveRecord::Base for each file you can just use the id of the model or if you want a string you can hash it with some string added as salt.

irb(main):021:0> file_id = 1
=> 1
irb(main):022:0> Digest::SHA1.hexdigest('SomeRandomString' + file_id.to_s)
=> "70f5eedc8d4f02fd8f5d4e09ca8925c2f8d6b942"

if you are simply keeping them as flat files on the system, you can hash their path+filename to create a unique string.

irb(main):016:0> Digest::SHA1.hexdigest '/home/bob/somefile.mp4'
=> "204a038eddff90637c529af7003e77d600428271"

and you can always add in a timestamp of the current time and a random number to prevent dupes.


来源: stackexchange

问:
How to append to appended element through JQuery?
My question is related more to why is this happening, not to knowing how to solve it.

I want to firstly append a
 to a div and then an  to the
.

I have the following jQuery code:

```<code>$('.patches').empty();
for(i=0;i<patches.length;i++){
    $('.patches').append($('<li>', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    }));
    $('#li'+patches[i].name).append($('<a>',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    }));
    $('#a'+patches[i].name).append('Version : '+patches[i].version+' Author : '+patches[i].author);
}
</code>```

The
 is appended but the  isn't, why isn't this working?

EDIT: I have modified the code as follows and it works perfectly:

```<code>$('.patches').empty();
for(i=0;i<patches.length;i++){
    var listItem=$('<li>', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    });
    $('.patches').append(listItem);
    var aItem=$('<a>',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    });
    listItem.append(aItem);
    listItem.append('<p>Version : '+patches[i].version+' Author : '+patches[i].author+'</p>');
}
</code>```

This version is almost the same as the previous one, I am just using variables. I would still like to know why the previous version of the code was not working. Could someone explain this?

答:
You are querying DOM before even appending to the DOM.

Append to li directly

```<code>for(i=0;i<patches.length;i++){
    $('.patches').append($('<li>', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    }).append($('<a>',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    })));
    $('#a'+patches[i].name).append('Version : '+patches[i].version+' Author : '+patches[i].author);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My question is related more to why is this happening, not to knowing how to solve it.

I want to firstly append a
 to a div and then an  to the
.

I have the following jQuery code:

$('.patches').empty();
for(i=0;i<patches.length;i++){
    $('.patches').append($('
', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    }));
    $('#li'+patches[i].name).append($('',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    }));
    $('#a'+patches[i].name).append('Version : '+patches[i].version+' Author : '+patches[i].author);
}

The
 is appended but the  isn't, why isn't this working?

EDIT: I have modified the code as follows and it works perfectly:

$('.patches').empty();
for(i=0;i<patches.length;i++){
    var listItem=$('
', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    });
    $('.patches').append(listItem);
    var aItem=$('',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    });
    listItem.append(aItem);
    listItem.append('
Version : '+patches[i].version+' Author : '+patches[i].author+'
');
}

This version is almost the same as the previous one, I am just using variables. I would still like to know why the previous version of the code was not working. Could someone explain this?

Body:
You are querying DOM before even appending to the DOM.

Append to li directly

for(i=0;i<patches.length;i++){
    $('.patches').append($('<li>', {
        id:'li'+ patches[i].name,
        class: 'list-group-item'
    }).append($('<a>',{
        href:patches[i].downloadUrl,
        text:patches[i].name,
        id:'a'+patches[i].name
    })));
    $('#a'+patches[i].name).append('Version : '+patches[i].version+' Author : '+patches[i].author);
}


问:
Issue scaling different sized images in CircleImageView
I'm using this repo for circular images and it works quite well. The problem I'm having is when I want to use images of different sizes, say a really big square and a small rectangle. The library uses scaleType = "CenterCrop" which works well for the bigger image, it gets a bit zoomed in when cropped, but that's okay since it is a big image and still fills the entire imageView.

The problem is that small images get "too cropped" and too zoomed in in order to match the edges of the imageView (as is the definition of CenterCrop). Is there a way to still use CenterCrop, but make sure the smaller images don't get bigger than their original size (like when using: scaletype="fitcenter") but also make the bigger images crop correctly?

Simply, I need to use something like CenterCrop, but not as "zoomed in", as the images are smaller than the imageView should be displayed like with fitCenter and not horribly zoomed in as they are right now.

I used this guide in order to try to understand this problem, but I can't seem to reach a solution.

How do I solve this? Is it possible with this library or should I try to use some other library? Thanks!

答: The lib has issue with this, check the issue tracker, you need the height width / weight</p>


问:
Why DefaultHttpClient.execute fails for not finding a certifcate when accessing a regular http address?
We're using a java application, running on jboss and rhel image. This app works as a forward proxy; users must authenticate on it and then all requests are forward to another mvc app and responses redirected to forward proxy/authentication app. It also uses a webservice to check user credentials. This check on webservice works just fine.

The mvc behind the java forward proxy is a .NET mvc application. This architecture works fine on our physical servers, but I'm struggling for more than a week to get it working on openshift pod.

After credentials are successfully validated against the web service, the java app tries to reach a resource on mvc app, which after making sure that the caller is safe (it actually just receive a get request with a client code, and check if the code is valid http://Mvc/Administration/Administration?membershipNumber=409738467360), redirect the request to the Welcome view.

Looking at the log files, I can see that the mvc app returns 200 first for the get request. It also receives the redirect (302) to Welcome view (note that all this communication is done through http, not https).

After that, it crashes.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Here is the DefaultHttpClient redirect code:

```<code>httpClient.setRedirectStrategy(new DefaultRedirectStrategy(){
        @Override
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {

            logger.info("Reverse proxy response: " + response.getStatusLine().getStatusCode());

            boolean isRedirect = super.isRedirected(request, response, context);
            int responseCode = response.getStatusLine().getStatusCode();
            logger.info("Is redirect " + isRedirect);
            if (!isRedirect) {
                if (responseCode == 301 || responseCode == 302) {
                    logger.info("Forward proxy returning true");
                    return true;
                }
            }
            logger.info("Forward proxy returning " + isRedirect);
            return isRedirect;

        }
    });
</code>```

I'm quite clueless on what's wrong, don't what to try. Any help is appreciate!

Thanks!

答:
As the error says, the connection can't be secured with the parameter you gave. As you can't handshake, you may be on a false website pretending to be xxx site.
If that's the desired behavior, you can use this workaround:

```<code>SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext(), new NoopHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
        .setMaxConnPerRoute(20)
        .setMaxConnTotal(200)
        .setSSLSocketFactory(csf)
        .build();
</code>```

This will basically disable the certificate handshakes.

Body:
We're using a java application, running on jboss and rhel image. This app works as a forward proxy; users must authenticate on it and then all requests are forward to another mvc app and responses redirected to forward proxy/authentication app. It also uses a webservice to check user credentials. This check on webservice works just fine.

The mvc behind the java forward proxy is a .NET mvc application. This architecture works fine on our physical servers, but I'm struggling for more than a week to get it working on openshift pod.

After credentials are successfully validated against the web service, the java app tries to reach a resource on mvc app, which after making sure that the caller is safe (it actually just receive a get request with a client code, and check if the code is valid http://Mvc/Administration/Administration?membershipNumber=409738467360), redirect the request to the Welcome view.

Looking at the log files, I can see that the mvc app returns 200 first for the get request. It also receives the redirect (302) to Welcome view (note that all this communication is done through http, not https).

After that, it crashes.

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Here is the DefaultHttpClient redirect code:

httpClient.setRedirectStrategy(new DefaultRedirectStrategy(){
        @Override
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {

            logger.info("Reverse proxy response: " + response.getStatusLine().getStatusCode());

            boolean isRedirect = super.isRedirected(request, response, context);
            int responseCode = response.getStatusLine().getStatusCode();
            logger.info("Is redirect " + isRedirect);
            if (!isRedirect) {
                if (responseCode == 301 || responseCode == 302) {
                    logger.info("Forward proxy returning true");
                    return true;
                }
            }
            logger.info("Forward proxy returning " + isRedirect);
            return isRedirect;

        }
    });

I'm quite clueless on what's wrong, don't what to try. Any help is appreciate!

Thanks!

Body:
As the error says, the connection can't be secured with the parameter you gave. As you can't handshake, you may be on a false website pretending to be xxx site.
If that's the desired behavior, you can use this workaround:

SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext(), new NoopHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
        .setMaxConnPerRoute(20)
        .setMaxConnTotal(200)
        .setSSLSocketFactory(csf)
        .build();

This will basically disable the certificate handshakes.


问:
How Do I Save All User Inputs To A Notepad text File In Python 3.5
I've made a program for my GCSE Coursework and need some help regarding saving all of the users inputs to a text file in notepad can any help would be greatly appreciated

the code is

```<code>print("Use Yes Or No For Answers That Require It")
from datetime import datetime #imports time package count=0 #sets count to 0
    while True:
        count +=1
        if count >3:
            break
        name=input("what is your name\n")
        yob=int(input("what is your yob\n"))
        year = datetime.now().year #sets year
        age=year-yob # sets age as a constant
        print("so you are",age,)
        user_input=input ("is this correct\n")
        if user_input==("yes"):
            print("nice")
        else:
            print("oops, you must be",age-1)
</code>```

答:
For the example you have pasted, I would add the write to the statement where you confirm if everything is correct.

```<code>    if user_input==("yes"):
        print("nice")
        with open('file.txt', 'a') as outfile:
            outfile.write("%s\t%d\t%d\n"%(name, yob, year))
    else:
        print("oops, you must be",age-1)
</code>```

Although, you could put it anywhere. Check this answer for a bit more information about writing files in python,

Body:
I've made a program for my GCSE Coursework and need some help regarding saving all of the users inputs to a text file in notepad can any help would be greatly appreciated

the code is

print("Use Yes Or No For Answers That Require It")
from datetime import datetime #imports time package count=0 #sets count to 0
    while True:
        count +=1
        if count >3:
            break
        name=input("what is your name\n")
        yob=int(input("what is your yob\n"))
        year = datetime.now().year #sets year
        age=year-yob # sets age as a constant
        print("so you are",age,)
        user_input=input ("is this correct\n")
        if user_input==("yes"):
            print("nice")
        else:
            print("oops, you must be",age-1)

Body:
For the example you have pasted, I would add the write to the statement where you confirm if everything is correct.

    if user_input==("yes"):
        print("nice")
        with open('file.txt', 'a') as outfile:
            outfile.write("%s\t%d\t%d\n"%(name, yob, year))
    else:
        print("oops, you must be",age-1)

Although, you could put it anywhere. Check this answer for a bit more information about writing files in python,


问:
Easy ways to crop out the status bar when taking iOS Screenshots?
Apple recommends cropping out the status bar from screenshots submitted to the app store.  Doing this manually in Preview is a very tedious and error-prone process.

Do any developers have any best-practices recommendations or automated techniques for speeding up this process?  The goal would be to take as input iPad and/or iPhone screenshots, and output them with the toolbar cropped off. We need to support both portrait and landscape orientation, and Retina-resolution iPhone screens.

I've found a few utilities online that purport to help with this, but the ones I have found seem to fail on Retina-display resolution screens.  And another that works via the iOS Simulator requires a 1920x1080 resolution monitor to process iPad screenshots - making it useless for non-17" laptop-based developers.

Any other recommendations for taking good screenshots for the AppStore? I know (based on my searching) that there are a lot of other developers who would be interested in a quicker workflow to handle this.

Bonus points for being able to bulk-process an entire directory.

答:
Here are two ways, assuming you mean status bar and not toolbar (which you probably shouldn't crop out of the screenshots).

If you have photoshop, just change the canvas size by subtracting 20 (low-res) or 40 (retina) and anchoring the bottom of the image. This works perfectly.

It's also easy in iPhoto using the Edit/Crop feature. Set the dimensions to the correct size (Portrait: 320x460 or 640x920 and Landscape: 480x300 or 960x600) and move the crop screen to the bottom of the image. This does it perfectly as well.

ContentLicense: CC BY-SA 2.5


问:
R: Error when running rattle() - "Invalid root element: 'requires'"
I installed rattle package and associated GTK+ library for windows (I work in Windows 7, R version 3.4.0). No issues installing them.
The library(rattle) command runs ok (no error messages), however when I run rattle() I got this error:

```<code>Error in method(obj, ...) : Invalid root element: 'requires'
</code>```

Any recommendation on how to fix it?

答:
The development version of rattle (currently 5.0.18) now works with the latest version of RGtk2 (2.20.33) and the earlier version (2.20.31) under recent versions of R.

install.packages("devtools")

devtools::install_bitbucket("kayontoga/rattle")

Hope that helps.

Body:
I installed rattle package and associated GTK+ library for windows (I work in Windows 7, R version 3.4.0). No issues installing them.
The library(rattle) command runs ok (no error messages), however when I run rattle() I got this error:

Error in method(obj, ...) : Invalid root element: 'requires'

Any recommendation on how to fix it?


答:
Modify your logic to first add  tag to the
, and then add that
 tag to the
...

Title: How to append to appended element through JQuery?

Body: Modify your logic to first add <a> tag to the <li>, and then add that <li> tag to the <div>...


问:
react js warnings in console unknown prop
I've got a reactJS application with react-toolbox

in console I got this error:

```<code>Warning: Unknown prop `raised` on <a> tag. Remove this prop from the element.
</code>```

Any Idea how I can solve this warning?
I don't want to remove the tag, is there workaround to get this worked with not removing this?

thanks

Update

```<code> <Button icon='save' type="submit" label={<T value='processes.new.save'/>} raised primary/>
</code>```

I use this stuff: http://react-toolbox.com/#/components/button

答:
This is happening because the 'raised' prop is being added as a prop to the  that the <Link> makes. You can include additional information through the state property of the location.

check Link docs

Body:
I've got a reactJS application with react-toolbox

in console I got this error:

Warning: Unknown prop `raised` on  tag. Remove this prop from the element.

Any Idea how I can solve this warning?
I don't want to remove the tag, is there workaround to get this worked with not removing this?

thanks

Update

 <Button icon='save' type="submit" label={<T value='processes.new.save'/>} raised primary/>

I use this stuff: http://react-toolbox.com/#/components/button

Body:
This is happening because the 'raised' prop is being added as a prop to the <a> that the <Link> makes. You can include additional information through the state property of the location.

check Link docs


问:
Understanding IOPS and IOPS Burst
Ok so I am going through A Cloud Guru's course for the solutions architect associate and I am having trouble understanding what IOP burst are. Here are the notes from the course:

```<code>EBS Volume Types
   General Purpose SSD (GP2)
     General purpose, balances both price and performance.
     Ratio of 3 IOPS per GB with up to 10,000 IOPS and the ability to burst up
     to 3000 IOPS for extended periods of time for volumes under 1Gib.
</code>```

After doing some research I understand IOPS to mean input/output operations. Meaning read and write to disk I assume. What I don't understand about this is, what does it mean to have 3IOPS per Gig. Does that mean for every gig of space on the drive you can read/write 3 times to the disk? That doesn't seem right. The other part I don't understand  is what does "the ability to burst" mean? My guess is that means how much can be read/written at once over the course of the read/write operation but I'm just guessing.

答:
Actually, IOPS means Input/Output PER SECOND. When you choose your EBS Type it has a baseline IOPS value, meaning that the quantity of operations per second is limited by the volume architecture.

With 3000 IOPS/Gib you have 3000 operations of input/output per second, with the capacity to transfer 1Gib. There are some techinal details here that I'm no the best one to tell you about block sizes and all. But this is a summary.

One thing you must understand is that the IOPS is not just a techical thing but also a comercial thing for Amazon. They sell the EBS with a limited IOPS (baseline), but if you need more IOPS you can pay an extra and create volumes with Provisioned IOPS (that can fo up to 20000).

About the burst, what I tell here is not exactly how it works, but can help you understand a little more that you undersand now. Some volumes can upgrade your IOPS for a brief periodo of time in case is needed without extra costs. This is a temporary burst, an normally with works for just a few minutes. It means that if receive a request for data that extends your defined IOPS, the service will provide with more of your defined for a brief period, to keep your service quality consistent. But if you need it for a long period will need to pay for it.

I think that this burst is based on some type of credits, like if you don't use your availabe IOPS for a time it generate some credits to be used in burst. But this last information must be confirmed with more experienced people.

Title: Understanding IOPS and IOPS Burst

Body:
Ok so I am going through A Cloud Guru's course for the solutions architect associate and I am having trouble understanding what IOP burst are. Here are the notes from the course:

EBS Volume Types
   General Purpose SSD (GP2)
     General purpose, balances both price and performance.
     Ratio of 3 IOPS per GB with up to 10,000 IOPS and the ability to burst up
     to 3000 IOPS for extended periods of time for volumes under 1Gib.

After doing some research I understand IOPS to mean input/output operations. Meaning read and write to disk I assume. What I don't understand about this is, what does it mean to have 3IOPS per Gig. Does that mean for every gig of space on the drive you can read/write 3 times to the disk? That doesn't seem right. The other part I don't understand  is what does "the ability to burst" mean? My guess is that means how much can be read/written at once over the course of the read/write operation but I'm just guessing.


问:
Where does Gradle store downloaded jars on the local file system
How does Gradle store downloaded jar files on the local file system? Maven stores them in the .m2 directory under USER_HOME, but where does Gradle store them? I checked the .gradle folder there, but saw only compiled scripts.

答:
Gradle's local repository folder is:

$USER_HOME/.gradle/caches/modules-2/files-2.1

Defined dependencies will be loaded from remote repositories into gradle's local repository folder. For each loaded file, gradle will be create a new folder named with md5 value of the original file (pom,jar,..). Full path for the dependency file is made up from :

groupid + artifactid + version + FILE_MD5_VALUE + FILE_NAME

If our defined dependency is:

compile 'org.springframework:spring-jdbc:4.3.4.RELEASE'

Then the library will be loaded into :

/$USER_HOME/.gradle/caches/modules-2/files-2.1/org.springframework/spring-jdbc/4.3.4.RELEASE/42175d194cf6aa7c716c0887f30255e5c0a5262c/spring-jdbc-4.3.4.RELEASE.jar

ContentLicense: CC BY-SA 4.0


问:
How to open Master page by clicking my own button in the datail page in Xamarin.Forms
Usually when creating a MasterDetailPage, a toobar with hamburger button are created automatically, I need to create a normal button in middle of the screen and the master page would open and swipe automatically from the left without seeing the toolbar with its hamburger button, I wanna hide the toolbar entirly. Is there anyway to achieve that?</p>

答:
You can use the property IsPresented. Personally I used MessagingCenter to Hide or Show menu as below</p>

```<code> MessagingCenter.Subscribe<HideMenu>(this, AppConstants.MessagingKeys.HideMenu, (sender) =>
            {
                IsPresented = false;
            });
</code>```

Body:
You can use the property IsPresented. Personally I used MessagingCenter to Hide or Show menu as below

 MessagingCenter.Subscribe<HideMenu>(this, AppConstants.MessagingKeys.HideMenu, (sender) =>
            {
                IsPresented = false;
            });


问:
Frequency of events in a week
My data has trips with datetime info, user id for each trip and trip type (single, round, pseudo).

Here's a data sample (pandas dataframe), named All_Data:

```<code>HoraDTRetirada        idpass        type
2016-02-17 15:36:00  39579449489   'single'
2016-02-18 19:13:00  39579449489   'single'
2016-02-26 09:20:00  72986744521   'pseudo'
2016-02-27 12:11:00  72986744521   'round'
2016-02-27 14:55:00  11533148958   'pseudo'
2016-02-28 12:27:00  72986744521   'round'
2016-02-28 16:32:00  72986744521   'round'
</code>```

I would like to count the number of times each category repeats in a "week of year" by user.

For example, if the event happens on a monday and the next event happens on a thursday for a same user, that makes two events on the same week; however, if one event happens on a saturday and the next event happens on the following monday, they happened in different weeks.

The output I am looking for would be in a form like this:

```<code>idpass        weekofyear   type      frequency
39579449489    1           'single'   2
72986744521    2           'round'    3
72986744521    2           'pseudo'   1
11533148958    2           'pseudo'   1
</code>```

Edit: this older question approaches a similar problem, but I don't know how to do it with pandas.

Title: Frequency of events in a week

Body:
My data has trips with datetime info, user id for each trip and trip type (single, round, pseudo).

Here's a data sample (pandas dataframe), named All_Data:

HoraDTRetirada        idpass        type
2016-02-17 15:36:00  39579449489   'single'
2016-02-18 19:13:00  39579449489   'single'
2016-02-26 09:20:00  72986744521   'pseudo'
2016-02-27 12:11:00  72986744521   'round'
2016-02-27 14:55:00  11533148958   'pseudo'
2016-02-28 12:27:00  72986744521   'round'
2016-02-28 16:32:00  72986744521   'round'

I would like to count the number of times each category repeats in a "week of year" by user.

For example, if the event happens on a monday and the next event happens on a thursday for a same user, that makes two events on the same week; however, if one event happens on a saturday and the next event happens on the following monday, they happened in different weeks.

The output I am looking for would be in a form like this:

idpass        weekofyear   type      frequency
39579449489    1           'single'   2
72986744521    2           'round'    3
72986744521    2           'pseudo'   1
11533148958    2           'pseudo'   1

Edit: this older question approaches a similar problem, but I don't know how to do it with pandas.

Body:
import pandas as pd

data = {"HoraDTRetirada": ["2016-02-17 15:36:00", "2016-02-18 19:13:00", "2016-12-31 09:20:00", "2016-02-28 12:11:00",
                           "2016-02-28 14:55:00", "2016-02-29 12:27:00", "2016-02-29 16:32:00"],
        "idpass": ["39579449489", "39579449489", "72986744521", "72986744521", "11533148958", "72986744521",
                   "72986744521"],
        "type": ["single", "single", "pseudo", "round", "pseudo", "round", "round"]}
df = pd.DataFrame.from_dict(data)
print(df)
df["HoraDTRetirada"] = pd.to_datetime(df['HoraDTRetirada'])
df["week"] = df['HoraDTRetirada'].dt.strftime('%U')
k = df.groupby(["idpass", "week", "type"],as_index=False).count()
print(k)

Output:

        HoraDTRetirada       idpass    type
0  2016-02-17 15:36:00  39579449489  single
1  2016-02-18 19:13:00  39579449489  single
2  2016-12-31 09:20:00  72986744521  pseudo
3  2016-02-28 12:11:00  72986744521   round
4  2016-02-28 14:55:00  11533148958  pseudo
5  2016-02-29 12:27:00  72986744521   round
6  2016-02-29 16:32:00  72986744521   round
        idpass week    type  HoraDTRetirada
0  11533148958   09  pseudo               1
1  39579449489   07  single               2
2  72986744521   09   round               3
3  72986744521   52  pseudo               1


问:
Trash using memcpy
I'm using memcpy to copy a specific number of chars from a char array to a char *. But when I read the char * have always trash in the end.

I'm using libssh2 lib to send commands to my raspberry pi and receive the output.

libssh2_channel_read will return the number of chars of the output int x and the output text will be on the char buffer[32].

Code I'm using:

```<code>char buffer[32];
int x = libssh2_channel_read(channel, buffer, sizeof(buffer));
char * output = (char *)malloc(sizeof(char)*x);
memcpy(output, buffer, x-2); // x - 2 because of "\r\n"
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;
</code>```

Example of output:

```<code>0══²²²²
</code>```

I only want the 0

答:
I think you shouldn't be using raw arrays and memcpy and the like here.

You are probably better off with the containers from the C++ standard library:

http://en.cppreference.com/w/cpp/container/vector

http://en.cppreference.com/w/cpp/string/basic_string

Directly write into char* buffer of std::string

Example:

```<code>std::vector<char> buffer(32);
int x = libssh2_channel_read(channel, &buffer[0], buffer.size());
// probably x will be smaller or equal the current size of the buffer
buffer.resize(x);
// if it's a string, why not have it as a std::string
std::string data(buffer.begin(), buffer.end());
std::cout << data << '\n';
</code>```

Title: Trash using memcpy

Body:
I'm using memcpy to copy a specific number of chars from a char array to a char *. But when I read the char * have always trash in the end.

I'm using libssh2 lib to send commands to my raspberry pi and receive the output.

libssh2_channel_read will return the number of chars of the output int x and the output text will be on the char buffer[32].

Code I'm using:

char buffer[32];
int x = libssh2_channel_read(channel, buffer, sizeof(buffer));
char * output = (char *)malloc(sizeof(char)*x);
memcpy(output, buffer, x-2); // x - 2 because of "\r\n"
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;

Example of output:

0══²²²²

I only want the 0

Body:
I think you shouldn't be using raw arrays and memcpy and the like here.

You are probably better off with the containers from the C++ standard library:

http://en.cppreference.com/w/cpp/container/vector

http://en.cppreference.com/w/cpp/string/basic_string

Directly write into char* buffer of std::string

Example:

std::vector<char> buffer(32);
int x = libssh2_channel_read(channel, &buffer[0], buffer.size());
// probably x will be smaller or equal the current size of the buffer
buffer.resize(x);
// if it's a string, why not have it as a std::string
std::string data(buffer.begin(), buffer.end());
std::cout << data << '\n';


问:
Add Sass (.scss) to ejected create-react-app config
I want to add .scss support in my app, which was created using create-react-app.

I did eject npm run eject and installed necessary dependencies: npm install sass-loader node-sass --save-dev

Inside config/webpack.config.dev.js I added to the loaders this snippet:

```<code>{
   test: /\.scss$/,
   include: paths.appSrc,
   loaders: ["style", "css", "scss"]
},
</code>```

So the beginning of the loaders array now look like so:

```<code>loaders: [
      // Process JS with Babel.
      {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: 'babel',
        query: require('./babel.dev')
      },
      // "postcss" loader applies autoprefixer to our CSS.
      // "css" loader resolves paths in CSS and adds assets as dependencies.
      // "style" loader turns CSS into JS modules that inject <style> tags.
      // In production, we use a plugin to extract that CSS to a file, but
      // in development "style" loader enables hot editing of CSS.
      {
        test: /\.css$/,
        loader: 'style!css!postcss'
      },
      // LOAD & COMPILE SCSS
      {
        test: /\.scss$/,
        include: paths.appSrc,
        loaders: ["style", "css", "scss"]
      },
</code>```

Now in my jsx when I try to import scss file:

```<code>import './assets/app.scss';
</code>```

I get an error:

Uncaught Error: Cannot find module "./assets/app.scss"

So my config must be wrong as I'm not able to load .scss files. How to adjust config to load .scss files in ejected create-react-app?

答:
When trying to integrate sass into empty react project I used this article. The solution presented there did not work and received the similar error as in the subject.
In my case replacing style-loader with require.resolve('style-loader') helped:

```<code> {
        test: /\.scss$/,
        include: paths.appSrc,
        loaders: [require.resolve('style-loader'), require.resolve('css-loader'), require.resolve('sass-loader')]
  },
</code>```

Body:
I want to add .scss support in my app, which was created using create-react-app.

I did eject npm run eject and installed necessary dependencies: npm install sass-loader node-sass --save-dev

Inside config/webpack.config.dev.js I added to the loaders this snippet:

{
   test: /\.scss$/,
   include: paths.appSrc,
   loaders: ["style", "css", "scss"]
},

So the beginning of the loaders array now look like so:

loaders: [
      // Process JS with Babel.
      {
        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: 'babel',
        query: require('./babel.dev')
      },
      // "postcss" loader applies autoprefixer to our CSS.
      // "css" loader resolves paths in CSS and adds assets as dependencies.
      // "style" loader turns CSS into JS modules that inject

Body:
When trying to integrate sass into empty react project I used this article. The solution presented there did not work and received the similar error as in the subject.
In my case replacing style-loader with require.resolve('style-loader') helped:

 {
        test: /\.scss$/,
        include: paths.appSrc,
        loaders: [require.resolve('style-loader'), require.resolve('css-loader'), require.resolve('sass-loader')]
  },


问:
Java: Pattern behaves differently in Scanner
Came across a strange behavior of regex matching in Java. The first output command prints true as expected, but when the same string is packed into Scanner, the output is false. What am I doing wrong?

```<code>public static void main(String[] args) {
  Pattern p = Pattern.compile(" *\\[");
  System.out.println(p.asPredicate().test("[]")); //true

  Scanner s = new Scanner("[]");
  System.out.println(s.hasNext(" *\\[")); //false
}
</code>```

答:
As per Predicate.test description from Javadoc:

. true if the input argument matches the predicate, otherwise false

What is not written explicitly in Javadoc but implied is that test(T t) method doesn't match like String.matches(String) method, where start and end anchors are implicit. test method on the other hand doesn't match complete string and you will need to use anchors in your regex to make it behave like String.matches or Scanner.hasNext(Pattern ) methods.

Following code will give consistent false result from both the calls

```<code>final String input = "[]";
final String re = "^ *\\[$"; // note use of anchors in the regex
final Pattern p = Pattern.compile(re);

System.out.println(p.asPredicate().test(input)); // false

Scanner s = new Scanner(input);
System.out.println(s.hasNext(p)); //false
s.close();
</code>```

Body:
Came across a strange behavior of regex matching in Java. The first output command prints true as expected, but when the same string is packed into Scanner, the output is false. What am I doing wrong?

public static void main(String[] args) {
  Pattern p = Pattern.compile(" *\\[");
  System.out.println(p.asPredicate().test("[]")); //true

  Scanner s = new Scanner("[]");
  System.out.println(s.hasNext(" *\\[")); //false
}

Body:
As per Predicate.test description from Javadoc:

. true if the input argument matches the predicate, otherwise false

What is not written explicitly in Javadoc but implied is that test(T t) method doesn't match like String.matches(String) method, where start and end anchors are implicit. test method on the other hand doesn't match complete string and you will need to use anchors in your regex to make it behave like String.matches or Scanner.hasNext(Pattern ) methods.

Following code will give consistent false result from both the calls

final String input = "[]";
final String re = "^ *\\[$"; // note use of anchors in the regex
final Pattern p = Pattern.compile(re);

System.out.println(p.asPredicate().test(input)); // false

Scanner s = new Scanner(input);
System.out.println(s.hasNext(p)); //false
s.close();


问:
Warbler executable won't start
I have some trouble packing my JRuby-application with warbler and running it.

I've created a simple sqlite3-app with one model which works fine when running via jruby -S rails s.

However, if I try packing it with jruby -S warble executable war the packed Winstone-server crashes with

```<code>[Winstone 2010/12/20 10:33:48] - Beginning extraction from war file
[Winstone 2010/12/20 10:33:50] - WARNING: The Servlet 2.4/2.5 spec XSD was unavailable inside the winstone classpath. Will be retrieved from the web if required (slow)
[Winstone 2010/12/20 10:33:50] - No webapp classes folder found - C:\Temp\winstone908137348044208817webroot\sqlite-test.war\WEB-INF\classes
[webapp 2010/12/20 10:33:51] - Warning: error application could not be initialized org.jruby.rack.RackInitializationException: no such file to load -- builtin/core_ext/symbol

    at org.jruby.rack.DefaultRackApplicationFactory.newRuntime(DefaultRackApplicationFactory.java:85)
    at org.jruby.rack.DefaultRackApplicationFactory.createApplication(DefaultRackApplicationFactory.java:177)
    at org.jruby.rack.DefaultRackApplicationFactory.newErrorApplication(DefaultRackApplicationFactory.java:127)
    at org.jruby.rack.DefaultRackApplicationFactory.init(DefaultRackApplicationFactory.java:45)
    at org.jruby.rack.PoolingRackApplicationFactory.init(PoolingRackApplicationFactory.java:50)
    at org.jruby.rack.RackServletContextListener.contextInitialized(RackServletContextListener.java:40)
    at winstone.WebAppConfiguration.<init>(WebAppConfiguration.java:889)
    at winstone.HostConfiguration.initWebApp(HostConfiguration.java:131)
    at winstone.HostConfiguration.<init>(HostConfiguration.java:73)
    at winstone.HostGroup.initHost(HostGroup.java:85)
    at winstone.HostGroup.<init>(HostGroup.java:45)
    at winstone.Launcher.<init>(Launcher.java:196)
    at winstone.Launcher.main(Launcher.java:391)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at Main.launchWinstone(Main.java:67)
    at Main.start(Main.java:72)
    at Main.main(Main.java:97)
Caused by: org.jruby.exceptions.RaiseException: no such file to load -- builtin/core_ext/symbol
    at (unknown).new(:1)
    at (unknown).(unknown)(:1)
</code>```

Where does this come from, and how do I get this running?

答:
This is due to a bug in JRuby 1.5.5 and earlier versions that affect running the executable jar on Windows and in paths that contain spaces. See JRUBY-4774 or WARBLER-15.

Try upgrading JRuby to 1.5.6 (gem update jruby-jars), rebuild the war file, and try again.

Title: Warbler executable won't start

Body:
I have some trouble packing my JRuby-application with warbler and running it.

I've created a simple sqlite3-app with one model which works fine when running via jruby -S rails s.

However, if I try packing it with jruby -S warble executable war the packed Winstone-server crashes with

[Winstone 2010/12/20 10:33:48] - Beginning extraction from war file
[Winstone 2010/12/20 10:33:50] - WARNING: The Servlet 2.4/2.5 spec XSD was unavailable inside the winstone classpath. Will be retrieved from the web if required (slow)
[Winstone 2010/12/20 10:33:50] - No webapp classes folder found - C:\Temp\winstone908137348044208817webroot\sqlite-test.war\WEB-INF\classes
[webapp 2010/12/20 10:33:51] - Warning: error application could not be initialized org.jruby.rack.RackInitializationException: no such file to load -- builtin/core_ext/symbol

    at org.jruby.rack.DefaultRackApplicationFactory.newRuntime(DefaultRackApplicationFactory.java:85)
    at org.jruby.rack.DefaultRackApplicationFactory.createApplication(DefaultRackApplicationFactory.java:177)
    at org.jruby.rack.DefaultRackApplicationFactory.newErrorApplication(DefaultRackApplicationFactory.java:127)
    at org.jruby.rack.DefaultRackApplicationFactory.init(DefaultRackApplicationFactory.java:45)
    at org.jruby.rack.PoolingRackApplicationFactory.init(PoolingRackApplicationFactory.java:50)
    at org.jruby.rack.RackServletContextListener.contextInitialized(RackServletContextListener.java:40)
    at winstone.WebAppConfiguration.<init>(WebAppConfiguration.java:889)
    at winstone.HostConfiguration.initWebApp(HostConfiguration.java:131)
    at winstone.HostConfiguration.<init>(HostConfiguration.java:73)
    at winstone.HostGroup.initHost(HostGroup.java:85)
    at winstone.HostGroup.<init>(HostGroup.java:45)
    at winstone.Launcher.<init>(Launcher.java:196)
    at winstone.Launcher.main(Launcher.java:391)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at Main.launchWinstone(Main.java:67)
    at Main.start(Main.java:72)
    at Main.main(Main.java:97)
Caused by: org.jruby.exceptions.RaiseException: no such file to load -- builtin/core_ext/symbol
    at (unknown).new(:1)
    at (unknown).(unknown)(:1)

Where does this come from, and how do I get this running?


问:
Kibana status page load number meaning
What does these Load numbers mean in kibana status page?

答:
Ok its actulally node stats load_1m load_5m load_15m

```<code> GET _cat/nodes?v
</code>```

https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-nodes.html

Title: Kibana status page load number meaning

Body:
Ok its actulally node stats load_1m load_5m load_15m

 GET _cat/nodes?v

https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-nodes.html


问:
PHP returning a string with the first char of every words in lowercase
There is already a function in PHP called ucwords which does just the opposite of what i need.

Is there such php library called lcwords? where instead of capitalizing the first of every words it converts them to lower case.

Thanks.

答:
```<code>function lcwords(string $str) :string
{
    return preg_replace_callback('/(?<=^|\s)\w/', function (array $match) :string {
        return strtolower($match[0]);
    }, $str);
}
</code>```


问:
ViewModels in Repository
I have read that the repository layer should not deal with ViewModels because of separation of concerns and should instead deal only with Models. This is also true for the service layer (in my case this is where my business logic is). So then the controller is left to deal with the population of the ViewModels.

I have a Model Category:

```<code>public class Category
{

 public int ID { get; set; }

 public int? ParentCategoryID { get; set; }

 public virtual ICollection<Product> Products{ get; set; }

 public virtual ICollection<CategoryName> CategoryNames{ get; set; }
}
</code>```

I have a ViewModel CategoryListViewModel used when displaying all Categories

```<code>public class CategoryListViewModel
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string ParentName { get; set; }
    }
</code>```

My view takes IEnumerable<...CategoryListViewModel>

This is how I populate the ViewModel from the controller:

```<code>public ActionResult Index()
        {
            IEnumerable<CategoryListViewModel> model;
            List<CategoryListViewModel> list = new List<CategoryListViewModel>();
            IEnumerable<Category> categoryList = categoryService.GetAllCategoriesList(RouteData);

            foreach (var item in categoryList)
            {
                CategoryListViewModel temp = new CategoryListViewModel()
                {
                    ID = item.ID,
                    Name = categoryService.GetCategoryName(RouteData, item.ID)
                };
                if (item.ParentCategoryID != null)
                {
                    temp.ParentName = categoryService.GetCategoryName(RouteData, (int)item.ParentCategoryID);
                }
                list.Add(temp);
            }
            model = list;
            return View(model);
        }
</code>```

My service methods:

```<code>public IEnumerable<Category> GetAllCategoriesList(RouteData data)
        {
            LanguageService languageService = new LanguageService();
            Languages langEnum = languageService.LanguageStringToEnum(languageService.DetermineSelectedLanguage(data));

            IEnumerable<Category> allCategories = repository.getAllCategoriesTest();

            return allCategories;
        }

public string GetCategoryName(RouteData data, int categoryId)
        {
            LanguageService languageService = new LanguageService();
            Languages langEnum = languageService.LanguageStringToEnum(languageService.DetermineSelectedLanguage(data));
            return repository.GetCategoryName(langEnum, categoryId);
        }
</code>```

And finally my repository methods:

```<code>public IEnumerable<Category> getAllCategoriesTest()
        {
            return db.Category.ToList();
        }

public string GetCategoryName(Languages lang, int categoryId)
        {
            return db.CategoryName.Where(cn => cn.CategoryID == categoryId && cn.Language == lang).Select(cn => cn.Name).FirstOrDefault();
        }
</code>```

This approach looks very bad to me. My Controller is not thin anymore and I am running a lot of queries for something that simple.

If I allow ViewModels in my repository I get a much cleaner solution.

My Controller method:

```<code>public ActionResult Index()
        {
            return View(categoryService.GetAllCategories(RouteData));
        }
</code>```

Service method:

```<code>public IEnumerable<CategoryListViewModel> GetAllCategories(RouteData data)
        {
            LanguageService languageService = new LanguageService();
            Languages langEnum = languageService.LanguageStringToEnum(languageService.DetermineSelectedLanguage(data));

            return repository.SelectAllCategories(langEnum);
        }
</code>```

And repository method:

```<code>public IEnumerable<CategoryListViewModel> SelectAllCategories(Languages lang)
        {
            var categories = db.Category.Include(c => c.CategoryNames).Select(names => new CategoryListViewModel
            {
                ID = names.ID,
                Name = names.CategoryNames.Where(cn => cn.Language == lang).Select(cn => cn.Name).FirstOrDefault(),
                ParentName = db.CategoryName.Where(cn => cn.Language == lang && cn.CategoryID == names.ParentCategoryID)
                .Select(cn => cn.Name).FirstOrDefault()
            }).ToList();
            return categories;
        }
</code>```

This approach, although violating separation of concerns seems to be "cleaner" to me.

My question is isn't the other approach more efficient in term of queries? Also is there any other way that this could be done so as not to write heavy controller methods and not execute that many queries? It seems to me that I am missing something.

答:
First, bear in mind that even though it has "MVC" in the name, ASP.NET MVC only very loosely implements the MVC pattern. MVC tells you to have thin controllers because the Model is an active record, which handles all the business logic, including that around querying itself. This does not apply to ASP.NET MVC. There, your Model is actually a combination of your DAL, service layer, entity and one or more view models. This means the controller inevitably must do at least a little more work than a controller in something like Ruby on Rails, if only to wire all this stuff together.

As @Liam suggested in the comments above, your best bet is factories. That way, the controller does not actually own the logic for how to map an entity to a view model. You'll of course still need to actually call the factory in your controller, but the logic remains abstracted.

Also, a proper service layer should roll up logic that would otherwise be in your controller. If you need the localized name for the category, your service should have a method that returns all the categories with their localized name already. If you're having to hit your service multiple times, that's a clear indication that you haven't provided a necessary endpoint for your application. You may need to introduce a DTO to handle this data, since the entity class may not have the appropriate properties. You'd then have a factory that maps your DTO to a view model.

Finally, for what it's worth, your repository is completely unnecessary. Just have your service interact directly with your Entity Framework context. Having a repository buys you nothing but just an additional thing you have to maintain.

Title: ViewModels in Repository

Body:
I have read that the repository layer should not deal with ViewModels because of separation of concerns and should instead deal only with Models. This is also true for the service layer (in my case this is where my business logic is). So then the controller is left to deal with the population of the ViewModels.

I have a Model Category:

public class Category
{

 public int ID { get; set; }

 public int? ParentCategoryID { get; set; }

 public virtual ICollection<Product> Products{ get; set; }

 public virtual ICollection<CategoryName> CategoryNames{ get; set; }
}

I have a ViewModel CategoryListViewModel used when displaying all Categories

public class CategoryListViewModel
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string ParentName { get; set; }
    }

My view takes IEnumerable<...CategoryListViewModel>

This is how I populate the ViewModel from the controller:

public ActionResult Index()
        {
            IEnumerable<CategoryListViewModel> model;
            List<CategoryListViewModel> list = new List<CategoryListViewModel>();
            IEnumerable<Category> categoryList = categoryService.GetAllCategoriesList(RouteData);

            foreach (var item in categoryList)
            {
                CategoryListViewModel temp = new CategoryListViewModel()
                {
                    ID = item.ID,
                    Name = categoryService.GetCategoryName(RouteData, item.ID)
                };
                if (item.ParentCategoryID != null)
                {
                    temp.ParentName = categoryService.GetCategoryName(RouteData, (int)item.ParentCategoryID);
                }
                list.Add(temp);
            }
            model = list;
            return View(model);
        }

My service methods:

public IEnumerable<Category> GetAllCategoriesList(RouteData data)
        {
            LanguageService languageService = new LanguageService();
            Languages langEnum = languageService.LanguageStringToEnum(languageService.DetermineSelectedLanguage(data));

            IEnumerable<Category> allCategories = repository.getAllCategoriesTest();

            return allCategories;
        }

public string GetCategoryName(RouteData data, int categoryId)
        {
            LanguageService languageService = new LanguageService();
            Languages langEnum = languageService.LanguageStringToEnum(languageService.DetermineSelectedLanguage(data));
            return repository.GetCategoryName(langEnum, categoryId);
        }

And finally my repository methods:

public IEnumerable<Category> getAllCategoriesTest()
        {
            return db.Category.ToList();
        }

public string GetCategoryName(Languages lang, int categoryId)
        {
            return db.CategoryName.Where(cn => cn.CategoryID == categoryId && cn.Language == lang).Select(cn => cn.Name).FirstOrDefault();
        }

This approach looks very bad to me. My Controller is not thin anymore and I am running a lot of queries for something that simple.

If I allow ViewModels in my repository I get a much cleaner solution.

My Controller method:

public ActionResult Index()
        {
            return View(categoryService.GetAllCategories(RouteData));
        }

Service method:

public IEnumerable<CategoryListViewModel> GetAllCategories(RouteData data)
        {
            LanguageService languageService = new LanguageService();
            Languages langEnum = languageService.LanguageStringToEnum(languageService.DetermineSelectedLanguage(data));

            return repository.SelectAllCategories(langEnum);
        }

And repository method:

public IEnumerable<CategoryListViewModel> SelectAllCategories(Languages lang)
        {
            var categories = db.Category.Include(c => c.CategoryNames).Select(names => new CategoryListViewModel
            {
                ID = names.ID,
                Name = names.CategoryNames.Where(cn => cn.Language == lang).Select(cn => cn.Name).FirstOrDefault(),
                ParentName = db.CategoryName.Where(cn => cn.Language == lang && cn.CategoryID == names.ParentCategoryID)
                .Select(cn => cn.Name).FirstOrDefault()
            }).ToList();
            return categories;
        }

This approach, although violating separation of concerns seems to be "cleaner" to me.

My question is isn't the other approach more efficient in term of queries? Also is there any other way that this could be done so as not to write heavy controller methods and not execute that many queries? It seems to me that I am missing something.


问:
Auto generating id(WEB API2)
I have  WebAPI2 project.

I controller I have POST method

```<code> [ResponseType(typeof(StartWorkingDay))]
    public IHttpActionResult PostStartWorkingDay(StartWorkingDay startWorkingDay)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.StartWorkingDays.Add(startWorkingDay);

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateException)
        {
            if (StartWorkingDayExists(startWorkingDay.Id))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay);
    }
</code>```

Here is my model:

```<code> public partial class StartWorkingDay
{
    public int Id { get; set; }
    public string Company { get; set; }
    public string Date { get; set; }
    public string Time { get; set; }
    public string INN { get; set; }
}
</code>```

At this point I need to add Id when send post request.

When I send first request it creates data in table with id:0

Next request is empty response and no data in table.

How I can make id generates automatically?

答:
You should generate id on the database side. It is easy to do with DatabaseGenerated attribute. Generating id value on inserting row is achieved this way:

```<code>[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
</code>```

Or with fluent configuration

```<code>modelBuilder.Entity<StartWorkingDay>().Property(d => d.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
</code>```

After you will modify the configuration, make sure that changes are propagated to the database. That will happen automatically if you are using DropCreateDatabaseAlways or DropCreateDatabaseIfModelChanges database initializer.

Title: Auto generating id(WEB API2)

Body:
I have  WebAPI2 project.

I controller I have POST method

 [ResponseType(typeof(StartWorkingDay))]
    public IHttpActionResult PostStartWorkingDay(StartWorkingDay startWorkingDay)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.StartWorkingDays.Add(startWorkingDay);

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateException)
        {
            if (StartWorkingDayExists(startWorkingDay.Id))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay);
    }

Here is my model:

 public partial class StartWorkingDay
{
    public int Id { get; set; }
    public string Company { get; set; }
    public string Date { get; set; }
    public string Time { get; set; }
    public string INN { get; set; }
}

At this point I need to add Id when send post request.

When I send first request it creates data in table with id:0

Next request is empty response and no data in table.

How I can make id generates automatically?

Body:
You should generate id on the database side. It is easy to do with DatabaseGenerated attribute. Generating id value on inserting row is achieved this way:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

Or with fluent configuration

modelBuilder.Entity<StartWorkingDay>().Property(d => d.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

After you will modify the configuration, make sure that changes are propagated to the database. That will happen automatically if you are using DropCreateDatabaseAlways or DropCreateDatabaseIfModelChanges database initializer.


问:
Setting up Knockd issues
I asked this question on security overflow last week, however there were no responses, so I am hoping that you can help here. The question is below:

So i'm busy setting up a knockd service on a VM to enable SSH login when the correct sequence of ports are "knocked on" using knockd and ufw.

The issue that I am currently having is that when the correct sequence of ports are selected, the user.rules for ufw is not able to write the new rule to a file.

I have tried using chmod 777 on all files within /etc/ufw as a test, however the file is still not writable.

The output for /etc/ufw/user.rules is as follows:

```<code>Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/after6.rules is world writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/after6.rules is group writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/user6.rules is world writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/user6.rules is group writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/applications.d is world writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/applications.d is group writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/user.rules is world writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/user.rules is group writable!
Jun 14 13:13:31 Pop knockd[4780]: ERROR: '/etc/ufw/user.rules' is not writable
Jun 14 13:13:31 Pop knockd[4780]: openSSH: command returned non-zero status code (1)
</code>```

The knockd file is shown in the code block below:

```<code>[options]
        logfile = /var/log/knockd.log

[openSSH]
        sequence    = 7000,8000,9000
        seq_timeout = 5
        command     = ufw allow 22/tcp
        tcpflags    = syn

[closeSSH]
        sequence    = 9000,8000,7000
        seq_timeout = 5
        command     = ufw delete allow 22/tcp
        tcpflags    = syn
</code>```

The output for /etc/default/knockd is shown below:

```<code># control if we start knockd at init or not
# 1 = start
# anything else = don't start
# PLEASE EDIT /etc/knockd.conf BEFORE ENABLING
START_KNOCKD=1

# command line options
KNOCKD_OPTS="-i enp0s3"
</code>```

Any advice would be greatly appreciated.

答:
I have hit the same problem with a knockd /etc/ufw/user.rules not writeable error.  The knock packets show up in syslog and the ufw insert 1 ... command is attempted.  My current best guess at the cause is the cgroups system.

Using iptables commands instead of ufw commands in /etc/knockd.conf works for me.

Title: Setting up Knockd issues

Body:
I asked this question on security overflow last week, however there were no responses, so I am hoping that you can help here. The question is below:

So i'm busy setting up a knockd service on a VM to enable SSH login when the correct sequence of ports are "knocked on" using knockd and ufw.

The issue that I am currently having is that when the correct sequence of ports are selected, the user.rules for ufw is not able to write the new rule to a file.

I have tried using chmod 777 on all files within /etc/ufw as a test, however the file is still not writable.

The output for /etc/ufw/user.rules is as follows:

Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/after6.rules is world writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/after6.rules is group writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/user6.rules is world writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/user6.rules is group writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/applications.d is world writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/applications.d is group writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/user.rules is world writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/user.rules is group writable!
Jun 14 13:13:31 Pop knockd[4780]: ERROR: '/etc/ufw/user.rules' is not writable
Jun 14 13:13:31 Pop knockd[4780]: openSSH: command returned non-zero status code (1)

The knockd file is shown in the code block below:

[options]
        logfile = /var/log/knockd.log

[openSSH]
        sequence    = 7000,8000,9000
        seq_timeout = 5
        command     = ufw allow 22/tcp
        tcpflags    = syn

[closeSSH]
        sequence    = 9000,8000,7000
        seq_timeout = 5
        command     = ufw delete allow 22/tcp
        tcpflags    = syn

The output for /etc/default/knockd is shown below:

# control if we start knockd at init or not
# 1 = start
# anything else = don't start
# PLEASE EDIT /etc/knockd.conf BEFORE ENABLING
START_KNOCKD=1

# command line options
KNOCKD_OPTS="-i enp0s3"

Any advice would be greatly appreciated.


问:
can magento add store with different subdomain?
it's my first time to use magento
my main domain for exmple domain .com with centos OS
my magento on store.domain .com with Ubuntu 16
can i use the same Ubuntu  server for another store with sub domain store2.domain .com ?
P.S my main domain domain .com uses wordpress Cms
thanks</p>

答:
Yes. You Can add store with different subdomain. Follow below steps:

Go to admin then select tab System->manage stores

Click create store view and complete the form and save store view

Change the Base URL for each Store view

1.Go to admin then select tab System->configuration

2.On the left side of the page General under that select web but before that you have to change the Current Configuration Scope to your store view name

3.Edit the base url to you subdomain(eg: http://en.yourdomain.com)

4.click save config.

Change .htaccess for redirecting to store view if you call the subdomain

1.Your .htaccess file is at the root folder of magento.

2.Search for "RewriteEngine on" word  in .htaccess file and write the code below it

```<code>RewriteCond %{HTTP_HOST} ^en.yourdomain.com
RewriteRule ^ - [E=MAGE_RUN_CODE:english]
RewriteCond %{HTTP_HOST} ^fr. yourdomain .com
RewriteRule ^ - [E=MAGE_RUN_CODE:french]
</code>```

then save the .htaccess file and try to clear all cache and browsing history from your browser as well as from magento.

Body:
Yes. You Can add store with different subdomain. Follow below steps:

Go to admin then select tab System->manage stores

Click create store view and complete the form and save store view

Change the Base URL for each Store view

1.Go to admin then select tab System->configuration

2.On the left side of the page General under that select web but before that you have to change the Current Configuration Scope to your store view name

3.Edit the base url to you subdomain(eg: http://en.yourdomain.com)

4.click save config.

Change .htaccess for redirecting to store view if you call the subdomain

1.Your .htaccess file is at the root folder of magento.

2.Search for "RewriteEngine on" word  in .htaccess file and write the code below it

RewriteCond %{HTTP_HOST} ^en.yourdomain.com
RewriteRule ^ - [E=MAGE_RUN_CODE:english]
RewriteCond %{HTTP_HOST} ^fr. yourdomain .com
RewriteRule ^ - [E=MAGE_RUN_CODE:french]

then save the .htaccess file and try to clear all cache and browsing history from your browser as well as from magento.


问:
How to convert and over write MongoDB date string into ISODate using Python PyMongo?
I'm trying to convert a number of document strings in the format "YYYY-MM-DD" into ISODates in MongoDB and have successfully written this for the console which has the desired effect:

```<code>db.address.find({ "date" : { $type : 2 } } ).forEach(function(element){  element.date = ISODate(element.date); db.address.save(element);})
</code>```

I'm trying to do the same in Python something like this:

```<code>client = MongoClient(my_mongodb_ip)
db = client.address
result = db.address.find( { "date" : { "$type" : 2 } } );
for r in result:
    print(r['date'])
    r["date"] = datetime.strptime(r["date"], "%Y-%m-%d")
    print(r['date'])
    db.address.update_one({"company": r['company']},
         {"$set": {"date" : r['date']}})
</code>```

Which I'd like to deliver this:

```<code>"date": {
  "$date": "2017-06-28T00:00:00.000Z"
},
</code>```

I don't get any updates to the DB.

答:
Try to use:</p>

```<code>import dateutil.parser

dateutil.parser.parse(<your time String>)
</code>```

Body:
I'm trying to convert a number of document strings in the format "YYYY-MM-DD" into ISODates in MongoDB and have successfully written this for the console which has the desired effect:

db.address.find({ "date" : { $type : 2 } } ).forEach(function(element){  element.date = ISODate(element.date); db.address.save(element);})

I'm trying to do the same in Python something like this:

client = MongoClient(my_mongodb_ip)
db = client.address
result = db.address.find( { "date" : { "$type" : 2 } } );
for r in result:
    print(r['date'])
    r["date"] = datetime.strptime(r["date"], "%Y-%m-%d")
    print(r['date'])
    db.address.update_one({"company": r['company']},
         {"$set": {"date" : r['date']}})

Which I'd like to deliver this:

"date": {
  "$date": "2017-06-28T00:00:00.000Z"
},

I don't get any updates to the DB.

Body:
Try to use:

import dateutil.parser

dateutil.parser.parse(<your time String>)


问:
Button click causes not post back in IE browser asp.net
Its very strange behavior that I'm facing. I have delete button, OnClick  I'm attaching it to that particular event. I'm storing my entire data in Session so, in if(!IsPostBack) i am clearing out the session when the page Initially loads. When i click on the delete button instead of doing IsPostBack = true it does IsPostBack = false in IE and resets the Session data. But, with other browser i do get the expected functionality.
Does any one have any clue about this issue ?

Button tag aspx file,

```<code><tr id="rowPurpose">
<td>
    <asp:Label ID="lblPurpose1" Font-Bold="true" runat="server">Purpose</asp:Label>
</td>
<td width="65">
    <asp:Button ID="btnDeletePurpose1"   Text="Delete" Visible="false" CommandArgument="lblPurpose1" OnClick="Delete_Purpose" runat="server" />
</td>
</tr>
</code>```

C# file:

```<code>void page_load()
{
    rowPurpose.Attributes["onclick"] = "javascript:Method('id')";
    if (!Page.IsPostBack)
    {
        Session["Key"] = null;
    }
}
</code>```

Thanks in advance!

答:
Are you using an HTML submit button or an <asp:Button>.  If you are not using the asp:Button then it will not perform a post back since the asp version wires up the PostBack functionality.  Also make sure you have the runat="server" attribute on the button and form.

Can you post your button and form tag in your ASPX page?

Body:
Its very strange behavior that I'm facing. I have delete button, OnClick  I'm attaching it to that particular event. I'm storing my entire data in Session so, in if(!IsPostBack) i am clearing out the session when the page Initially loads. When i click on the delete button instead of doing IsPostBack = true it does IsPostBack = false in IE and resets the Session data. But, with other browser i do get the expected functionality.
Does any one have any clue about this issue ?

Button tag aspx file,

    <asp:Label ID="lblPurpose1" Font-Bold="true" runat="server">Purpose</asp:Label>

    <asp:Button ID="btnDeletePurpose1"   Text="Delete" Visible="false" CommandArgument="lblPurpose1" OnClick="Delete_Purpose" runat="server" />

C# file:

void page_load()
{
    rowPurpose.Attributes["onclick"] = "javascript:Method('id')";
    if (!Page.IsPostBack)
    {
        Session["Key"] = null;
    }
}

Thanks in advance!


问:
How to link 3 drop down list together using HTML & javascript
I was able to link two drop down list together but, I am facing problem to link 3 drop down list together in such away that 2 depends on 1 and 3 depends on 2.

This is the code of my 2 drop down list linked together:-

```<code><head>

 <script type = "text/javascript">

function update()
 {
  var albania = ["Tirana","Durres","Vlore","Shkoder"];
    var kosovo = ["Prishtina","Mitrovica","Peje","Gjakove"];
    var germany = ["Berlin","Frankfurt","Hannover","Bonn"];

     var  countries = document.getElementById("1");
     enter code here`var cities = document.getElementById("2");
    var selected = countries.options[countries.selectedIndex].value;

     if(selected=="1"){
    for(var i = 0; i < albania.length; i++) {
    var opt1 = document.createElement('option');
    opt1.innerHTML = albania[i];
   opt1.value = albania[i];
    cities.appendChild(opt1);
    }
      }
     else if(selected=="2")
    {
     for(var j = 0; j < kosovo.length; j++) {
     var opt2 = document.createElement('option');
      opt2.innerHTML = kosovo[j];
     opt2.value = kosovo[j];
     cities.appendChild(opt2);
     }
      }
   else if(selected=="3")
      {
    for(var k = 0; k < germany.length; k++) {
    var opt3 = document.createElement('option');
    opt3.innerHTML = germany[k];
    opt3.value = germany[k];
     cities.appendChild(opt3);
     }
     }
      else
       var t =0;
     }
      </script>

        </head>
       <body>
<p><select  id= "1" onchange="update()">
   <option selected = "selected" >Select Country</option>
   <option value="1">Albania</option>
   <option value="2">Kosovo</option>
   <option value="3">Germany</option>
   </select>
   </p>
    <p><select  id="2">
   <option selected = "selected" ></option>

   </body>
</html>
</code>```

答:
The short answer is same way you did it for second select.
The code will look like this.

There are lots of improvements possible to question you asked and answer I added.

```<code><head>

<script type="text/javascript">
var albania = ["Tirana","Durres","Vlore","Shkoder"];
var kosovo = ["Prishtina","Mitrovica","Peje","Gjakove"];
var germany = ["Berlin","Frankfurt","Hannover","Bonn"];

function updateTwo() {
    var  countries = document.getElementById("1");
    var cities = document.getElementById("2");
    var selected = countries.options[countries.selectedIndex].value;
    var i;
    for(i = cities.options.length - 1 ; i >= 0 ; i--) {
        cities.remove(i);
    }
    if(selected=="1"){
        for(var i = 0; i < albania.length; i++) {
            addOption(cities,albania[i]);
        }
    } else if(selected=="2") {
        for(var j = 0; j < kosovo.length; j++) {
            addOption(cities,kosovo[j]);
        }
    } else if(selected=="3") {
        for(var k = 0; k < germany.length; k++) {
            addOption(cities,germany[k]);
        }
    }
}

updateThree = function() {
    var  cities = document.getElementById("2");
    var area = document.getElementById("3");
    var selected = cities.options[cities.selectedIndex].value;
    var i;
    for(i = area.options.length - 1 ; i >= 0 ; i--) {
        area.remove(i);
    }
    if(selected=="Tirana"){
        for(var i = 0; i < albania.length; i++) {
            addOption(area,albania[i]);
        }
    } else if(selected=="Durres") {
        for(var j = 0; j < kosovo.length; j++) {
            addOption(area,kosovo[j]);
        }
    } else if(selected=="Vlore") {
        for(var k = 0; k < germany.length; k++) {
            addOption(area,germany[k]);
        }
    } else if(selected=="Shkoder") {
        for(var k = 0; k < germany.length; k++) {
            addOption(area,germany[k]);
        }
    }
}

addOption = function(option, value) {
    var opt = document.createElement('option');
    opt.innerHTML = value;
    opt.value = value;
    option.appendChild(opt);
}
</script>
</head>
<body>
    <p>
        <select id="1" onchange="javaScript:updateTwo();">
            <option value="0" selected="selected">Select Country</option>
            <option value="1">Albania</option>
            <option value="2">Kosovo</option>
            <option value="3">Germany</option>
        </select>
    </p>
    <p>
        <select id="2" onchange="javaScript:updateThree();"></select>
    </p>
    <p>
        <select id="3"></select>
    </p>
</body>
</html>
</code>```

Here is working fiddle for same

Body:
I was able to link two drop down list together but, I am facing problem to link 3 drop down list together in such away that 2 depends on 1 and 3 depends on 2.

This is the code of my 2 drop down list linked together:-

<select  id= "1" onchange="update()">
   <option selected = "selected" >Select Country</option>
   <option value="1">Albania</option>
   <option value="2">Kosovo</option>
   <option value="3">Germany</option>
   </select>

<select  id="2">
   <option selected = "selected" ></option>

Body:
The short answer is same way you did it for second select.
The code will look like this.

There are lots of improvements possible to question you asked and answer I added.

<head>

<script type="text/javascript">
var albania = ["Tirana","Durres","Vlore","Shkoder"];
var kosovo = ["Prishtina","Mitrovica","Peje","Gjakove"];
var germany = ["Berlin","Frankfurt","Hannover","Bonn"];

function updateTwo() {
    var  countries = document.getElementById("1");
    var cities = document.getElementById("2");
    var selected = countries.options[countries.selectedIndex].value;
    var i;
    for(i = cities.options.length - 1 ; i >= 0 ; i--) {
        cities.remove(i);
    }
    if(selected=="1"){
        for(var i = 0; i < albania.length; i++) {
            addOption(cities,albania[i]);
        }
    } else if(selected=="2") {
        for(var j = 0; j < kosovo.length; j++) {
            addOption(cities,kosovo[j]);
        }
    } else if(selected=="3") {
        for(var k = 0; k < germany.length; k++) {
            addOption(cities,germany[k]);
        }
    }
}

updateThree = function() {
    var  cities = document.getElementById("2");
    var area = document.getElementById("3");
    var selected = cities.options[cities.selectedIndex].value;
    var i;
    for(i = area.options.length - 1 ; i >= 0 ; i--) {
        area.remove(i);
    }
    if(selected=="Tirana"){
        for(var i = 0; i < albania.length; i++) {
            addOption(area,albania[i]);
        }
    } else if(selected=="Durres") {
        for(var j = 0; j < kosovo.length; j++) {
            addOption(area,kosovo[j]);
        }
    } else if(selected=="Vlore") {
        for(var k = 0; k < germany.length; k++) {
            addOption(area,germany[k]);
        }
    } else if(selected=="Shkoder") {
        for(var k = 0; k < germany.length; k++) {
            addOption(area,germany[k]);
        }
    }
}

addOption = function(option, value) {
    var opt = document.createElement('option');
    opt.innerHTML = value;
    opt.value = value;
    option.appendChild(opt);
}
</script>
</head>
<body>
    <p>
        <select id="1" onchange="javaScript:updateTwo();">
            <option value="0" selected="selected">Select Country</option>
            <option value="1">Albania</option>
            <option value="2">Kosovo</option>
            <option value="3">Germany</option>
        </select>
    </p>
    <p>
        <select id="2" onchange="javaScript:updateThree();"></select>
    </p>
    <p>
        <select id="3"></select>
    </p>
</body>
</html>

Here is working fiddle for same


问:
spring mvc @ExceptionHandler method get same view
My problem is that I want to create an @ExceptionHandler method that will capture all un-handled exceptions. Once captured I would like to redirect to the current page instead of specifying a separate page just to display error.

Basically how do I get the value of someview returned by somemethod and set it dynamically in the method unhandledExceptionHandler below.

```<code>@ExceptionHandler(Exception.class)
protected ModelAndView unhandledExceptionHandler(Exception ex){
    System.out.println("unhandle exception here!!!");
    ModelAndView mv = new ModelAndView();
    mv.setViewName("currentview");
    mv.addObject("UNHANDLED_ERROR", "UNHANDLED ERROR. PLEASE CONTACT SUPPORT. "+ex.getMessage());
    return mv;
}

@RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(HttpSession session) throws Exception {
    String abc = null;
    abc.length();
    return "someview";
}
</code>```

So in JSP I can render this error message back into the current page something like that.

```<code><c:if test="${not empty UNHANDLED_ERROR}">
    <div class="messageError"> ${UNHANDLED_ERROR}</div>
</c:if>
</code>```

答:
Create a controller method annotated with @RequestMethod("/server-error")

Create a controller method annotated with @ExceptionHandler which will return "forward:/server-error";

Body:
My problem is that I want to create an @ExceptionHandler method that will capture all un-handled exceptions. Once captured I would like to redirect to the current page instead of specifying a separate page just to display error.

Basically how do I get the value of someview returned by somemethod and set it dynamically in the method unhandledExceptionHandler below.

@ExceptionHandler(Exception.class)
protected ModelAndView unhandledExceptionHandler(Exception ex){
    System.out.println("unhandle exception here!!!");
    ModelAndView mv = new ModelAndView();
    mv.setViewName("currentview");
    mv.addObject("UNHANDLED_ERROR", "UNHANDLED ERROR. PLEASE CONTACT SUPPORT. "+ex.getMessage());
    return mv;
}

@RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(HttpSession session) throws Exception {
    String abc = null;
    abc.length();
    return "someview";
}

So in JSP I can render this error message back into the current page something like that.

<c:if test="${not empty UNHANDLED_ERROR}">

 ${UNHANDLED_ERROR}

</c:if>


问:
Rendering OpenStreetMap in OpenLayers 3 with more detail and higher DPI
I'm using OpenLayers 3 and OpenStreetMap to print maps on paper, and for this I'd need to render the maps with more details and higher DPI than are shown on the screen. I'm using CSS to set the size of ol.Map's target in centimeters to the desired size for the printout (.map { width: 7cm; height: 6.3cm; }).

By default OpenLayers shows one of my maps like this, which is too low detail for my needs:

By changing the map size with map.setSize(map.getSize().map(function (x) { return x*2; })); I'm able to increase the detail closer to what I need:

But the problem with this hack is that when the window is resized, the size is reset and it will look wrong like this:

How would I be able to control the OSM zoom level and map DPI independently of the map's size on screen to achieve the desired outcome (the second picture) reliably?

答:
A solution I've found is to put the map inside two nested divs. The inner one has, for example, width: 200%; height: 200%, and the outer one would have transform: scale(.5) translate(-50%,-50%);. This would double the resolution the user sees.

This approach changes the pixel zoom level relative to the zoom level on screen. However, it needs to be recalculated and updated whenever the user zooms the map.


问:
Store the indexes of random elements correctly in an array
I got an array a which is filled by node objects. For example I got 200 nodes on my screen and all are saved inside this array. These nodes are labeled by individual indexes a[0], a[1], ect. Now, when I select a number of random nodes (for example with shortest path) and store them in a second array b which looks like b = [ object, object, object, object.....],
 is there a way to automatically return the position in array a? For example, when I click a random node, which is at the 3rd position in array a , that means at a[2], then I want that this position is returned or stored automatically, maybe in a third array c. And at the end, it could look like: c= [ a[2], a[6], a[18], a[7], a[0]  .....]. Hope someone can help me with my problem. Thanks so much!

答:
If I understand your problem correctly, your array a looks like this :

```<code>a = [{id:1} , {id:2} , {id:3} , {id:4}]
</code>```

and then you randomly click on elements, so that they are then stored in an array b as such :

```<code>b = [{id:3}, {id:1}]
</code>```

So eventually you want to memorize the information that a[2] is stored in position b[0], and a[0] is stored in position b[1], right?

What you could do is not store the entire objects in b, but just their id :

```<code>b = [3, 1]
</code>```

This way, you can easily find what position they're at :

```<code>findPosition(node){
 return b.indexOf( node.id )
}

console.log(findPosition(a[2])) // 0
</code>```

Body:
If I understand your problem correctly, your array a looks like this :

a = [{id:1} , {id:2} , {id:3} , {id:4}]

and then you randomly click on elements, so that they are then stored in an array b as such :

b = [{id:3}, {id:1}]

So eventually you want to memorize the information that a[2] is stored in position b[0], and a[0] is stored in position b[1], right?

What you could do is not store the entire objects in b, but just their id :

b = [3, 1]

This way, you can easily find what position they're at :

findPosition(node){
 return b.indexOf( node.id )
}

console.log(findPosition(a[2])) // 0


问:
PHP array_map callback function inside function
I have a function called createCost, and inside that function, I have an array_map that takes in an array and a function called checkDescription that's inside that createCost. Below is an example:

```<code>public function createCost{

  $cost_example = array();
  function checkDescription($array_item)
  {
    return $array_item;
  }

  $array_mapped = array_map('checkDescription', $cost_example);
}
</code>```

When I run this I get a

```<code>array_map() expects parameter 1 to be a valid callback, function 'checkDescription' not found or invalid function name
</code>```

Which to my understanding is that it looked for the function checkDescription outside that createCost but how can I call checkDescription from inside?

答:
Do like this</p>

```<code>public function createCost(){
    $cost_example = array();
    $array_mapped = array_map(function ($array_item){
        return $array_item;
    }, $cost_example);
}
</code>```

Body:
I have a function called createCost, and inside that function, I have an array_map that takes in an array and a function called checkDescription that's inside that createCost. Below is an example:

public function createCost{

  $cost_example = array();
  function checkDescription($array_item)
  {
    return $array_item;
  }

  $array_mapped = array_map('checkDescription', $cost_example);
}

When I run this I get a

array_map() expects parameter 1 to be a valid callback, function 'checkDescription' not found or invalid function name

Which to my understanding is that it looked for the function checkDescription outside that createCost but how can I call checkDescription from inside?

Body:
Do like this

public function createCost(){
    $cost_example = array();
    $array_mapped = array_map(function ($array_item){
        return $array_item;
    }, $cost_example);
}


问:
For loop not working in python
in outer loop i=156 ,it is not looping for other values of i=1,2,3,4.......I am trying to run this for loop in scrapy python . But first loop is not working

```<code>for i in range(1,157):
     start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
          "countryid=100&lang=en&page={}&pagesize={}&"
          "sortby=popular&licensetype=all&callback=_producttype_apps"
          "&_=1499255634459".format(i, page) for page in xrange(1,1001)]
</code>```

The first loop outside the start_urls is not working
The results required is like this for page=1 pagesize should run from 1 to 1000 and when page=2 pagesize should again run from 1 to 1000 and so on till page=156

答:
what your are probably trying to do is

```<code>start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
      "countryid=100&lang=en&page={}&pagesize={}&"
      "sortby=popular&licensetype=all&callback=_producttype_apps"
      "&_=1499255634459".format(i, page) for page in xrange(1,1001) for i in range(1,157)]
</code>```

if the order matters, you can do it the other way around by reversing the for loops:

```<code>start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
              "countryid=100&lang=en&page={}&pagesize={}&"
              "sortby=popular&licensetype=all&callback=_producttype_apps"
              "&_=1499255634459".format(i, page) for i in range(1,157) for page in xrange(1,1001)]
</code>```

you're using two different loops in different ways - your use of the outer for loop is wrong. Think about this:

```<code>for i in range(10):
    x = i
</code>```

for each iteration you assign the variable x with the value of i, but before you do anything else you reassign it to the next i. That is essentially what you're doing in your code.

alternatives include appending to a list:

```<code>x = []
for i in range(10):
    x.append(i)
</code>```

or list comprehensions like you are using in your code

```<code>x = [i for i in range(10)]
</code>```

obviously these are dumb examples because they are just reproducing the list from range(10)

Title: For loop not working in python

Body:
in outer loop i=156 ,it is not looping for other values of i=1,2,3,4.......I am trying to run this for loop in scrapy python . But first loop is not working

for i in range(1,157):
     start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
          "countryid=100&lang=en&page={}&pagesize={}&"
          "sortby=popular&licensetype=all&callback=_producttype_apps"
          "&_=1499255634459".format(i, page) for page in xrange(1,1001)]

The first loop outside the start_urls is not working
The results required is like this for page=1 pagesize should run from 1 to 1000 and when page=2 pagesize should again run from 1 to 1000 and so on till page=156

Body:
what your are probably trying to do is

start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
      "countryid=100&lang=en&page={}&pagesize={}&"
      "sortby=popular&licensetype=all&callback=_producttype_apps"
      "&_=1499255634459".format(i, page) for page in xrange(1,1001) for i in range(1,157)]

if the order matters, you can do it the other way around by reversing the for loops:

start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
              "countryid=100&lang=en&page={}&pagesize={}&"
              "sortby=popular&licensetype=all&callback=_producttype_apps"
              "&_=1499255634459".format(i, page) for i in range(1,157) for page in xrange(1,1001)]

you're using two different loops in different ways - your use of the outer for loop is wrong. Think about this:

for i in range(10):
    x = i

for each iteration you assign the variable x with the value of i, but before you do anything else you reassign it to the next i. That is essentially what you're doing in your code.

alternatives include appending to a list:

x = []
for i in range(10):
    x.append(i)

or list comprehensions like you are using in your code

x = [i for i in range(10)]

obviously these are dumb examples because they are just reproducing the list from range(10)


答:
First, it would help if you actually showed the full exception -- why and where did you get the NullPointerException?

Am I in the right path? What should I do in order to correctly read from the kafka topic and extract some fields and put them in a Ktable?

Your general approach is ok but it looks like your code has a few mistakes.  For example:

```<code>KTable<String, Long> counts = source.print();
</code>```

print() returns void, so the line above does not even compile.  Perhaps you should double-check whether your answer is actually containing all the relevant information?

I'd recommend to take a look at the many examples and demo applications available at https://github.com/confluentinc/examples.  They should give you some templates to use as a starting point.

Title: Using kafka streams to extract information from logs contained in a kafka topic

Body:
First, it would help if you actually showed the full exception -- why and where did you get the NullPointerException?

Am I in the right path? What should I do in order to correctly read from the kafka topic and extract some fields and put them in a Ktable?

Your general approach is ok but it looks like your code has a few mistakes.  For example:

KTable<String, Long> counts = source.print();

print() returns void, so the line above does not even compile.  Perhaps you should double-check whether your answer is actually containing all the relevant information?

I'd recommend to take a look at the many examples and demo applications available at https://github.com/confluentinc/examples.  They should give you some templates to use as a starting point.


问:
ElasticSearch.net NEST use a Wildcard index in query
Hi I'm new to Elastic Search and I'm making some experiments to understand the basics of query through ElasticSearch.net and NEST.
I'm trying to translate a query with this syntax:

```<code>curl -XGET 'http://myserver.com:9200/myindexes-*/XY/_search/?size=1000&pretty=1' -d '
{
  "query": {
    "bool": {
      "filter": [
        { "match":  { "LOGTYPE" : "XY" }},
        { "match": { "USER" : "mrossi" }},
        { "wildcard": { "DATA": "m.rossi*" }},
        { "match": { "CODE" : "WZ" }},
        { "range": { "timestamp": { "gte": "2015-05-02" }}}
      ]
    }
  }
}
'
</code>```

I've found how to build the multiple field query, (thanks to those who posted it) but I still need to understand how to create the Wildcard index in the query.
The team feeding the Elastic Search engine has created an index in the format MyIndexes-YYYYMMDD with an index per each date because each date has millions of rows of data (they are log files). I haven't yet found a way to make a query on more than one index, if it is so simple as writing the wildcard in the index name or if I need to do something different.
If you have any clue, Thank you in advance.

Edited after some tests on the answer received: I've tried some tests and even if the call to elastic search seems to be successful reading the results I'm not able to understand if I have a problem in my query or if there are no data.

```<code>Valid NEST response built from a successful low level call on POST: /myindex-%2A/ml/_search?pretty=true
# Audit trail of this API call:
 - [1] HealthyResponse: Node: http://username:pwd@mydomain.com:9200/ Took: 00:00:00.0580006
# Request:
{"size":1000,"query":{"bool":{"filter":[{"match":{"LOGTYPE":{"query":"XY"}}}]}}}
# Response:
{
  "took" : 31,
  "timed_out" : false,
  "_shards" : {
    "total" : 270,
    "successful" : 270,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}
</code>```

The above data is what I can see from the DebugInformation of the response. My uncertainty is connected with how the POST command is built, in fact even if my entity is named XY uppercase in the post appears in lowercase, and also the pretty variable has a value of true instead of 1. the size parameter is set inside the request and not as a variable of the POST as in the sample I posted in the first message.
I've simplified the filters to set just one filter and also in the request data I see that in my sample the "XY" filter has a query: instead of nothing as it is in the sample.
so at the moment the query seems to be sintactically correct but I don't know if it is correct on my index data.
can you suggest how to try and use something like select top 100 * from my table just to see if I can find the data, and then try and implement filters???
thank you again

答: You should be able to use the wildcard in the index... is your query not working?</p>

Body:
Hi I'm new to Elastic Search and I'm making some experiments to understand the basics of query through ElasticSearch.net and NEST.
I'm trying to translate a query with this syntax:

curl -XGET 'http://myserver.com:9200/myindexes-*/XY/_search/?size=1000&pretty=1' -d '
{
  "query": {
    "bool": {
      "filter": [
        { "match":  { "LOGTYPE" : "XY" }},
        { "match": { "USER" : "mrossi" }},
        { "wildcard": { "DATA": "m.rossi*" }},
        { "match": { "CODE" : "WZ" }},
        { "range": { "timestamp": { "gte": "2015-05-02" }}}
      ]
    }
  }
}
'

I've found how to build the multiple field query, (thanks to those who posted it) but I still need to understand how to create the Wildcard index in the query.
The team feeding the Elastic Search engine has created an index in the format MyIndexes-YYYYMMDD with an index per each date because each date has millions of rows of data (they are log files). I haven't yet found a way to make a query on more than one index, if it is so simple as writing the wildcard in the index name or if I need to do something different.
If you have any clue, Thank you in advance.

Edited after some tests on the answer received: I've tried some tests and even if the call to elastic search seems to be successful reading the results I'm not able to understand if I have a problem in my query or if there are no data.

Valid NEST response built from a successful low level call on POST: /myindex-%2A/ml/_search?pretty=true
# Audit trail of this API call:
 - [1] HealthyResponse: Node: http://username:pwd@mydomain.com:9200/ Took: 00:00:00.0580006
# Request:
{"size":1000,"query":{"bool":{"filter":[{"match":{"LOGTYPE":{"query":"XY"}}}]}}}
# Response:
{
  "took" : 31,
  "timed_out" : false,
  "_shards" : {
    "total" : 270,
    "successful" : 270,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}

The above data is what I can see from the DebugInformation of the response. My uncertainty is connected with how the POST command is built, in fact even if my entity is named XY uppercase in the post appears in lowercase, and also the pretty variable has a value of true instead of 1. the size parameter is set inside the request and not as a variable of the POST as in the sample I posted in the first message.
I've simplified the filters to set just one filter and also in the request data I see that in my sample the "XY" filter has a query: instead of nothing as it is in the sample.
so at the moment the query seems to be sintactically correct but I don't know if it is correct on my index data.
can you suggest how to try and use something like select top 100 * from my table just to see if I can find the data, and then try and implement filters???
thank you again