问:
Callback not a function - Mocha/Mongoose
So I've tried looking up this bug, but I can't seem to find an answer that caters to my bug. I'm using mocha and chai-http to test some API's. I'm just hitting the endpoints using their corresponding RESTFUL methods (POST, GET, PUT) and checking the response (really straight forward). The problem is, individually my test suites work (if I were to run them one at a time), but when I run them using my gulp command ... I get "callback not a function" for some of the test cases (the ones in the if hook if you're familiar with mocha)

Here's the error I'm getting:

```<code> Uncaught TypeError: callback.apply is not a function
          at Immediate.<anonymous> (node_modules/mongoose/lib/model.js:3683:16)
          at Immediate._onImmediate (node_modules/mongoose/node_modules/mquery/lib/utils.js:137:16)
</code>```

Here's the structure of my directory that my test cases reside:

```<code>test
   backend
       assignments_tests.js
       application_tests.js
       courses_test.js
</code>```

& I have a gulp file with the following:

```<code>// Set the environment variable for the test cases to point to production
gulp.task('set-testing-env', function() {
  return process.env.NODE_ENV = 'production';
})

// gulp task for backend
gulp.task('test-backend', ['set-testing-env'], function() {
  return gulp.src('test/backend/**/*.js', {read: false})
    .pipe(mocha({
      reporter: 'spec',
      timeout: 60000
    }))
    .on('error', function(err) {
      // console.log(err);
      process.exit();
    });
});
</code>```

& finally a sample of my test case:

```<code>    describe("testing GET" ....
     before(function(done) {
      ... setting up stuff here and calling done ...
     })

      describe("get courses information and courses offered", function() {
        it("gets a courses information", function(done) {
          const endpoint = test.endpoint + "/courseInfo/" + test.course
          chai.request(app)
              .get(endpoint)
              .end(function(err, res) {
                expect(err, "Error hitting endpoint").to.be.null;
                expect(res, "Expected data in json format").to.be.json;
                expect(res, "Expected status to be 200").to.have.status(200);
                expect(res.body, "Expected course info!").to.have.length(1);
                expect(res.body[0],"Missing keys").to.have.all.keys(courseInfo);
                done();
              })
        })
    })

   describe("testing POST" ...
     before(function(done) {
         ... setting up and calling done ...
     })

     describe(...
        it(...)
     })
  })
</code>```

I'm not too sure why I'm getting a callback not a function error. :(
Any help would be much appreciated!

答:
Probably in some part of code that you didn't include here you are calling a Mongoose method passing something like too many objects as parameters, like in this question:

Async.each throwing error

One of those objects gets interpreted as a function but cannot be called as such.

This is a common problem but you didn;t include any code that runs Mongoose methods so it's hard to tell if that is the issue here.

Body:
So I've tried looking up this bug, but I can't seem to find an answer that caters to my bug. I'm using mocha and chai-http to test some API's. I'm just hitting the endpoints using their corresponding RESTFUL methods (POST, GET, PUT) and checking the response (really straight forward). The problem is, individually my test suites work (if I were to run them one at a time), but when I run them using my gulp command ... I get "callback not a function" for some of the test cases (the ones in the if hook if you're familiar with mocha)

Here's the error I'm getting:

 Uncaught TypeError: callback.apply is not a function
          at Immediate.<anonymous> (node_modules/mongoose/lib/model.js:3683:16)
          at Immediate._onImmediate (node_modules/mongoose/node_modules/mquery/lib/utils.js:137:16)

Here's the structure of my directory that my test cases reside:

test
   backend
       assignments_tests.js
       application_tests.js
       courses_test.js

& I have a gulp file with the following:

// Set the environment variable for the test cases to point to production
gulp.task('set-testing-env', function() {
  return process.env.NODE_ENV = 'production';
})

// gulp task for backend
gulp.task('test-backend', ['set-testing-env'], function() {
  return gulp.src('test/backend/**/*.js', {read: false})
    .pipe(mocha({
      reporter: 'spec',
      timeout: 60000
    }))
    .on('error', function(err) {
      // console.log(err);
      process.exit();
    });
});

& finally a sample of my test case:

    describe("testing GET" ....
     before(function(done) {
      ... setting up stuff here and calling done ...
     })

      describe("get courses information and courses offered", function() {
        it("gets a courses information", function(done) {
          const endpoint = test.endpoint + "/courseInfo/" + test.course
          chai.request(app)
              .get(endpoint)
              .end(function(err, res) {
                expect(err, "Error hitting endpoint").to.be.null;
                expect(res, "Expected data in json format").to.be.json;
                expect(res, "Expected status to be 200").to.have.status(200);
                expect(res.body, "Expected course info!").to.have.length(1);
                expect(res.body[0],"Missing keys").to.have.all.keys(courseInfo);
                done();
              })
        })
    })

   describe("testing POST" ...
     before(function(done) {
         ... setting up and calling done ...
     })

     describe(...
        it(...)
     })
  })

I'm not too sure why I'm getting a callback not a function error. :(
Any help would be much appreciated!


来源: stackexchange

问:
Is it possible in Java to check if objects fields are null and then add default value to all those attributes?
I need to make sure that no object attribute is null and add default value in case if it is null. Is there any easy way to do this, or do I have to do it manually by checking every attribute by its getters and setters?</p>

答:
Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:

```<code>return Stream.of(id, name).allMatch(Objects::isNull);
</code>```

This remains quite easy to maintain while avoiding the reflection hammer.
This will return true for null attributes.

ContentLicense: CC BY-SA 3.0

Body:
Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:

return Stream.of(id, name).allMatch(Objects::isNull);

This remains quite easy to maintain while avoiding the reflection hammer.
This will return true for null attributes.


问:
Javascript replace every 6th colon in array
I have some problems with replacing every 6th colon in my array. Have tried something with Regex, but that doesn't seem to work. I have red other questions were people are using nth and then set this variabele to the index you want to replace, but can't figure out why that isn't working. I used the join function to replace the ',' in my array with ':'.

```<code>arrayProducts[i] = arrayProducts[i].join(':');
</code>```

When i use console.log(arrayProducts); this is my result:

F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3

This is what I want:

```<code>F200:0:0.0000:1:100:0:1,KPO2:0:0.0000:1:200:0:2,HGB1:0:0.0000:1:300:0:3
</code>```

Thanks for reading!

Edit: F200, KP02 and HGB1, could also be numbers / digits like: 210, 89, 102 so the :[A-Z] method from regex doesn't work.

答:
maybe you can try this approach,
loop your array and join it manually, something like :</p>

```<code>     var strarr = "F200:0:00000:1:100:0:1:KPO2:0:00000:1:200:0:2:HGB1:0:00000:1:300:0:3";
     var arr = strarr.split(":")

      var resStr = "";

       for(var i = 0; i < arr.length; i++)
       {
           if(i > 0 && i%7 == 0)
               resStr = resStr + ","  + arr[i]
           else
               resStr =  resStr + ( resStr == "" ? "" : ":") + arr[i];
        }

        console.log(resStr);
</code>```

Body:
I have some problems with replacing every 6th colon in my array. Have tried something with Regex, but that doesn't seem to work. I have red other questions were people are using nth and then set this variabele to the index you want to replace, but can't figure out why that isn't working. I used the join function to replace the ',' in my array with ':'.

arrayProducts[i] = arrayProducts[i].join(':');

When i use console.log(arrayProducts); this is my result:

F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3

This is what I want:

F200:0:0.0000:1:100:0:1,KPO2:0:0.0000:1:200:0:2,HGB1:0:0.0000:1:300:0:3

Thanks for reading!

Edit: F200, KP02 and HGB1, could also be numbers / digits like: 210, 89, 102 so the :[A-Z] method from regex doesn't work.

Body:
maybe you can try this approach,
loop your array and join it manually, something like :

     var strarr = "F200:0:00000:1:100:0:1:KPO2:0:00000:1:200:0:2:HGB1:0:00000:1:300:0:3";
     var arr = strarr.split(":")

      var resStr = "";

       for(var i = 0; i < arr.length; i++)
       {
           if(i > 0 && i%7 == 0)
               resStr = resStr + ","  + arr[i]
           else
               resStr =  resStr + ( resStr == "" ? "" : ":") + arr[i];
        }

        console.log(resStr);


问:
How to view form from source code in IntelliJ IDEA
I have just started working on Java Swing project. As an IDE I am using IntelliJ IDEA from JetBrains.

In the project I can see the .java files related to GUI.

Do you know how I can view these files in GUI Designer? Or Generate output of  these files in GUI Designer in IntelliJ IDEA or any other IDE.

I googled it but couldn't find anything.

答:
In two ways, you can see the file in GUI Designer:

Double click to .form file in Project view.

In .java file you can see which code part bounds in which GUI component at the left side of the editor as an icon. So just click the related icon to view related component.


问:
Adding a form field that is not in the schema to Doctrine form Symfony 1.4
I have an image upload form and at the bottom, I'd like to have a checkbox that the user must check before submitting the form, certifying that they have the right to distribute the photo. I've tried adding it as a Widget in the Form class, but it is not displaying. What is the best way to accomplish this?</p>

答:
For validation, you can add this to your form class to allow fields outside the model:

```<code>$this->validatorSchema->setOption('allow_extra_fields', true);
$this->validatorSchema->setOption('filter_extra_fields', false); // true or false
</code>```

Other than that, just adding the widget in the standard way should work fine.

ContentLicense: CC BY-SA 2.5

Body:
For validation, you can add this to your form class to allow fields outside the model:

$this->validatorSchema->setOption('allow_extra_fields', true);
$this->validatorSchema->setOption('filter_extra_fields', false); // true or false

Other than that, just adding the widget in the standard way should work fine.


问:
fail to open link in webview
Fail to open link in webview in android. I tried it in webview but it only shows blank page. It seems that some of urls are loaded but some not how is it.</p>

```<code>String strUrl =  "https://app.mygtechguy.com/5862bd814bf7f";
webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            Toast.makeText(getActivity(), "Oh no! ", Toast.LENGTH_SHORT).show();
            alertDialog.setTitle("Error");
            alertDialog.setMessage("Make sure internet is working well");
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    return;
                }
            });
            alertDialog.show();
        }
    });
    webView.getSettings().setLoadsImagesAutomatically(true);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().getAllowContentAccess();
    webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    webView.loadUrl(strUrl);
</code>```

答:
I would suggest try to remove the url loading from shouldOverrideUrlLoading like this:

```<code>@Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //view.loadUrl(url);
            return false;
        }
</code>```

And also in the AndroidManifest.xml set Internet permission:

```<code>   <uses-permission android:name="android.permission.INTERNET" />
</code>```

Title: fail to open link in webview

Body:
Fail to open link in webview in android. I tried it in webview but it only shows blank page. It seems that some of urls are loaded but some not how is it.

String strUrl =  "https://app.mygtechguy.com/5862bd814bf7f";
webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            Toast.makeText(getActivity(), "Oh no! ", Toast.LENGTH_SHORT).show();
            alertDialog.setTitle("Error");
            alertDialog.setMessage("Make sure internet is working well");
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    return;
                }
            });
            alertDialog.show();
        }
    });
    webView.getSettings().setLoadsImagesAutomatically(true);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().getAllowContentAccess();
    webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    webView.loadUrl(strUrl);

Body:
I would suggest try to remove the url loading from shouldOverrideUrlLoading like this:

@Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //view.loadUrl(url);
            return false;
        }

And also in the AndroidManifest.xml set Internet permission:

   <uses-permission android:name="android.permission.INTERNET" />


问:
Dropping mssql data records for records older than xx days
I'm trying to drop all the records from my DB where the records are OLDER than 3 days.

I've written something like this:

```<code>delete from Results WHERE [Date] > DATEADD(d, -3, getdate())
</code>```

I wanted to check whether this sql query is correct since I'm worried that I might make a mistake and delete more than I should...

this this query correct?

答:
Your code is deleting everything newer than 3 days old, and should be:

```<code>DELETE FROM Results WHERE [Date] < DATEADD(DAY, -3, GETDATE())
</code>```

Otherwise, this is fine for deleting everything that is older than exactly 72 hours, although as others have said you should definitely be testing either on a copy of the data or at least by using SELECT statement

```<code>SELECT * FROM Results WHERE [date] < DATEADD(DAY, -3, GETDATE())
</code>```

However, if you want to delete everything that happened before three days ago (e.g. It is now Monday, and I want to delete everything that happened before Friday) you would need to eliminate the time aspect.

```<code>DELETE FROM Results WHERE CONVERT(DATE, [date]) < DATEADD(DAY, -3, GETDATE())
</code>```

Body:
I'm trying to drop all the records from my DB where the records are OLDER than 3 days.

I've written something like this:

delete from Results WHERE [Date] > DATEADD(d, -3, getdate())

I wanted to check whether this sql query is correct since I'm worried that I might make a mistake and delete more than I should...

this this query correct?

Body:
Your code is deleting everything newer than 3 days old, and should be:

DELETE FROM Results WHERE [Date] < DATEADD(DAY, -3, GETDATE())

Otherwise, this is fine for deleting everything that is older than exactly 72 hours, although as others have said you should definitely be testing either on a copy of the data or at least by using SELECT statement

SELECT * FROM Results WHERE [date] < DATEADD(DAY, -3, GETDATE())

However, if you want to delete everything that happened before three days ago (e.g. It is now Monday, and I want to delete everything that happened before Friday) you would need to eliminate the time aspect.

DELETE FROM Results WHERE CONVERT(DATE, [date]) < DATEADD(DAY, -3, GETDATE())


答:
You could use replace with a look for six parts with colon and replace the seventh.

var string = 'F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3',
    result = string.replace(/(([^:]*:){6}[^:]*):/g, '$1,');

console.log(result);```

Title: Javascript replace every 6th colon in array


问:
Can not ping docker container from another host which is in the same LAN
I have two hosts, in the same LAN, both running docker:

Host A: 172.16.0.113

Host B: 172.16.0.114

I can ping host A from host B. But, I can not ping a docker container on host A from host B.

I created a docker container running ubuntu, in the docker default network (bridge). The default docker0's IP address is 172.17.0.1. And the IP address of the container (ubuntu) in the host (172.16.0.113) is 172.17.0.2. The command I used is here:

```<code>sudo docker run --name container01 -it -p 8080:80 ubuntu /bin/bash
</code>```

I can ping container01 from its host, host A; but I can not ping container01 from the other host, host B. Note that I have exposed the port of container01.

I think when I ping container01 from the host B, packets are sent to a container in that host. But I want to know how to connect to host A's container01 from host B.

答:
Docker containers run on private addresses that aren't normally accessible from other hosts. If you have multiple docker hosts, then you should setup overlay networking to place containers on the same private network where they can access each other; this can be done automatically with swarm mode.

For reaching containers from outside of docker, you need to publish a port. With docker run that's the -p 8080:80 option that would map the host port 8080 to the container port 80 (you can adjust these port numbers). With a docker-compose.yml, there's a similar ports section.

Body:
I have two hosts, in the same LAN, both running docker:

Host A: 172.16.0.113

Host B: 172.16.0.114

I can ping host A from host B. But, I can not ping a docker container on host A from host B.

I created a docker container running ubuntu, in the docker default network (bridge). The default docker0's IP address is 172.17.0.1. And the IP address of the container (ubuntu) in the host (172.16.0.113) is 172.17.0.2. The command I used is here:

sudo docker run --name container01 -it -p 8080:80 ubuntu /bin/bash

I can ping container01 from its host, host A; but I can not ping container01 from the other host, host B. Note that I have exposed the port of container01.

I think when I ping container01 from the host B, packets are sent to a container in that host. But I want to know how to connect to host A's container01 from host B.


问:
Will my attribute get assigned its default value if I use an initializer list?
I've got a class like,

```<code>public class Revex
{
    public IEnumerable<char> AllCharacters = Enumerable.Range(0, 256).Select(Convert.ToChar).Where(c => !char.IsControl(c)).ToArray();
    // ...
</code>```

If I initialize it with

```<code>var r = new Revex { AllCharacters = "abcd" };
</code>```

Will that line above get executed or not (Enumerable.Range...)? If I want it to not get called when I construct my class this way, how would I do that?

I've got about 10 optional character classes like that, so I don't want to write a constructor for every possible combination of them.

答:
Initialised member variables like this are always initialized prior to execution of the code in your constructor.

In this situation, you have the following sequence

Initialize the AllCharacters member variable

Run the Revex constructor (which might be the compiler supplied default "do nothing" constructor)

Assign a new value to AllCharacters

If you want to avoid this sequence, you'll need to move initialization of AllCharacters into your constructor.

If you also want to allow possible override, you might need something like this:

```<code>public class Revex
{
    public IEnumerable<char> AllCharacters;

    public Revex()
        : this( Enumerable.Range(0, 256)
                .Select(Convert.ToChar)
                .Where(c => !char.IsControl(c))
    {
        // Nothing
    }

    public Revex(IEnumerable<char> allCharacters)
    {
        AllCharacters = allCharacters.ToArray();
    }
}
</code>```

Update 3 Dec

Another alternative would be to use lazy initialization to provide the default values only if explicit values were not provided by the class consumer. You'd need to switch to public properties instead of public fields, and provide logic in the property getters.

```<code>public class Revex
{
    public IEnumerable<char> AllCharacters
    {
        get
        {
            if (mAllCharacters == null)
            {
                // Default initialization
                mAllCharacters
                    = Enumerable.Range(0, 256)
                      .Select(Convert.ToChar)
                      .Where(c => !char.IsControl(c)
            }

            return mAllCharacters;
        }
    }

    public Revex()
    {
        // Nothing
    }

    private IEnumerable<char> mAllCharacters;
}
</code>```

Body:
I've got a class like,

public class Revex
{
    public IEnumerable<char> AllCharacters = Enumerable.Range(0, 256).Select(Convert.ToChar).Where(c => !char.IsControl(c)).ToArray();
    // ...

If I initialize it with

var r = new Revex { AllCharacters = "abcd" };

Will that line above get executed or not (Enumerable.Range...)? If I want it to not get called when I construct my class this way, how would I do that?

I've got about 10 optional character classes like that, so I don't want to write a constructor for every possible combination of them.

Body:
Initialised member variables like this are always initialized prior to execution of the code in your constructor.

In this situation, you have the following sequence

Initialize the AllCharacters member variable

Run the Revex constructor (which might be the compiler supplied default "do nothing" constructor)

Assign a new value to AllCharacters

If you want to avoid this sequence, you'll need to move initialization of AllCharacters into your constructor.

If you also want to allow possible override, you might need something like this:

public class Revex
{
    public IEnumerable<char> AllCharacters;

    public Revex()
        : this( Enumerable.Range(0, 256)
                .Select(Convert.ToChar)
                .Where(c => !char.IsControl(c))
    {
        // Nothing
    }

    public Revex(IEnumerable<char> allCharacters)
    {
        AllCharacters = allCharacters.ToArray();
    }
}

Update 3 Dec

Another alternative would be to use lazy initialization to provide the default values only if explicit values were not provided by the class consumer. You'd need to switch to public properties instead of public fields, and provide logic in the property getters.

public class Revex
{
    public IEnumerable<char> AllCharacters
    {
        get
        {
            if (mAllCharacters == null)
            {
                // Default initialization
                mAllCharacters
                    = Enumerable.Range(0, 256)
                      .Select(Convert.ToChar)
                      .Where(c => !char.IsControl(c)
            }

            return mAllCharacters;
        }
    }

    public Revex()
    {
        // Nothing
    }

    private IEnumerable<char> mAllCharacters;
}


问:
Password security in Java - Converting char[] to String
I am trying to build an unofficial api for a website. It will require the user to log in, and the password will be read from the console using the standard Console.readPassword() method. Now, this gives me a char array, but I have to send the password through a POST request using the HttpPost class in Apache's HttpClient library. For this, a String is required, but conversion of the password to String will create a security risk.
What can I do?

Edit : I know how to convert a char array to string. The problem is that Strings are immutable and since you cannot delete objects explicitly in Java, the password will be left in the memory.

答:
Use String.valueOf();:

```<code>String str = String.valueOf(Console.readPassword());
</code>```

Body:
Use String.valueOf();:

String str = String.valueOf(Console.readPassword());


问:
Compile error after a modification
I'm trying to modify a spreadhseet as it seems to eventually have some errors.
The code below is the current one:

```<code>Range("DP2").Value = "=IF(RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)<0,60+RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2),RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)) + RC[-1]"
</code>```

The problem is that the values the logical is looking at are time (HHMM) and it takes the right 2 (MM) and subtract from another time (MM), and where the value is below zero, it just adds 60 assuming the first time just one hour ahead (which is true) but the problem is I have observations where the difference is more than an hour (2 hrs, 3 hrs, etc.) e.g. 1110 and 0830, hence adding only 60 will not do the right calculation.
I've written this code:

```<code>  IF(RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)<=0, IF(LEFT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-LEFT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)=1,60+RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2), IF(LEFT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-LEFT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)=2,120+RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2), IF(LEFT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-LEFT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)=3,180+RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2),RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2))))) + RC[-1]"
</code>```

This one is supposed to look at the hour section of the time value (Left 2,, HH), and accordingly decide whether to add 60, 120 or 180.
But VBA just won't accept the code saying it's a compile error!

Title: Compile error after a modification

Body:
I'm trying to modify a spreadhseet as it seems to eventually have some errors.
The code below is the current one:

Range("DP2").Value = "=IF(RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)<0,60+RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2),RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)) + RC[-1]"

The problem is that the values the logical is looking at are time (HHMM) and it takes the right 2 (MM) and subtract from another time (MM), and where the value is below zero, it just adds 60 assuming the first time just one hour ahead (which is true) but the problem is I have observations where the difference is more than an hour (2 hrs, 3 hrs, etc.) e.g. 1110 and 0830, hence adding only 60 will not do the right calculation.
I've written this code:

  IF(RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)<=0, IF(LEFT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-LEFT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)=1,60+RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2), IF(LEFT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-LEFT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)=2,120+RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2), IF(LEFT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-LEFT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)=3,180+RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2),RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2))))) + RC[-1]"

This one is supposed to look at the hour section of the time value (Left 2,, HH), and accordingly decide whether to add 60, 120 or 180.
But VBA just won't accept the code saying it's a compile error!

Body:
You've exceeded the number of characters per line in the VBE, break up your string on separate lines like so:

Range("D2").Value = "IF(RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]" & _
"=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)<=0, IF(LEFT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-LEFT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)=1,60+RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2), IF(LEFT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-LEFT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)=2,120+RIGHT(IF" & _
"(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP" & _
"(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2), IF(LEFT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-LEFT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2)=3,180+RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2),RIGHT(IF(R1C[-110]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-110],0)),2)-RIGHT(IF(R1C[-111]=RC7,VLOOKUP(RC4,Services!C1:C254,32,0),VLOOKUP(RC4,Services!C1:C254,146+R1C[-111],0)),2))" & _
"))) + RC[-1]"


答:
You can just count the number of colon occurences and replace every nth of them.

var str = 'F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3', counter = 0;
    res = str.replace(/:/g, function(v) {
      counter++;
      return !(counter % 7) ? ',' : v;
    });

    console.log(res);```


问:
Staggering items in CSS with flexbox
I'm trying to create a staggered layout in CSS, where each row only has one item, but it will be offset from the items on the other rows.

I've made two working examples so far, but I'm wondering if there is a better way to achieve this.

Here's an example I made using spacer divs :
http://cdpn.io/e/EWrMgL

HTML :

```<code><div class="container">
    <div class="row">
        <div class="spacer">(spacer)</div>
        <div class="content col-2">content 2</div>
        <div class="spacer">(spacer)</div>
    </div>
    <div class="row">
        <div class="content col-1">content 1</div>
        <div class="spacer">(spacer)</div>
        <div class="spacer">(spacer)</div>
    </div>
    <div class="row">
        <div class="spacer">(spacer)</div>
        <div class="spacer">(spacer)</div>
        <div class="content col-3">content 3</div>
    </div>
    <div class="row">
        <div class="spacer">(spacer)</div>
        <div class="spacer">(spacer)</div>
        <div class="content col-3">content 3</div>
    </div>
</div>
</code>```

CSS :

```<code>.container, .spacer, .content, .row {
    display: flex;
}

.container {
    flex-flow: row wrap;
    font-family: sans-serif;
}

.row {
    width: 100%
}

.spacer {
    color: #2c3e50;
    flex: 1 1 0%;
}

.content {
    color: #ecf0f1;
    flex : 3 1 0%;
    flex-basis: 60%
}

.content, .spacer {
    justify-content: center;
    align-items: center;
    min-height: 5em;
    margin: 0.5em;
}

.col-1 {
    background-color: #96858F;
}

.col-2 {
     background-color:#9099A2;
}

.col-3 {
    background-color: #6d7993;
}
</code>```

I made another attempt at a cleaner version using margins instead of wrapping
each item in a row : http://cdpn.io/e/xqMBmB

HTML:

```<code><div class="container">
        <div class="content col-2">content 2</div>
        <div class="content col-1">content 1</div>
        <div class="content col-3">content 3</div>
        <div class="content col-3">content 3</div>
</div>
</code>```

CSS:

```<code>.container, .content{
    display: flex;
}

.container {
    flex-flow: row wrap;
    font-family: sans-serif;
}

.content {
    color: #ecf0f1;
    flex: 0 1 70%;

    justify-content: center;
    align-items: center;
    min-height: 5em;
    margin-bottom: 0.5em;
}

.col-1 {
    background-color: #96858F;
}

.col-2 {
    background-color:#9099A2;
    margin-left: 7.5%;
}

.col-3 {
    background-color: #6d7993;
    margin-left: 15%;
}
</code>```

Is there a cleaner way to do this than enclosing each row in a div or changing the margins? I'll want to add @media rules to make the rows 100% width below a certain screen size.

答:
If you change to flex-direction: column and remove wrap, the 2:nd will behave as the 1:st

I also added a media query to drop the left margin at a small width.

With this markup it's also easier to change order and layout, and is most likely the best way to do it.

.container, .content{
  display: flex;
}
.container {
  flex-direction: column;
  font-family: sans-serif;
}
.content {
  color: #ecf0f1;
  justify-content: center;
  align-items: center;
  min-height: 5em;
  margin-bottom: 0.5em;
}
.col-1 {
  background-color: #96858F;
}
.col-2 {
  background-color:#9099A2;
  margin-left: 7.5%;
}
.col-3 {
  background-color: #6d7993;
  margin-left: 15%;
}

@media screen and (max-width: 500px) {
  .content {
    margin-left: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="content col-2">content 2</div>
    <div class="content col-1">content 1</div>
    <div class="content col-3">content 3</div>
    <div class="content col-3">content 3</div>
</div></code>```

You can also size them, like this

.container, .content{
  display: flex;
}
.container {
  flex-direction: column;
  font-family: sans-serif;
}
.content {
  width: 70%;
  color: #ecf0f1;
  justify-content: center;
  align-items: center;
  min-height: 5em;
  margin-bottom: 0.5em;
}
.col-1 {
  background-color: #96858F;
}
.col-2 {
  background-color:#9099A2;
  margin-left: 7.5%;
}
.col-3 {
  background-color: #6d7993;
  margin-left: 15%;
}

@media screen and (max-width: 500px) {
  .content {
    margin-left: 0;
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="content col-2">content 2</div>
    <div class="content col-1">content 1</div>
    <div class="content col-3">content 3</div>
    <div class="content col-3">content 3</div>
</div></code>```

Title: Staggering items in CSS with flexbox

Body:
I'm trying to create a staggered layout in CSS, where each row only has one item, but it will be offset from the items on the other rows.

I've made two working examples so far, but I'm wondering if there is a better way to achieve this.

Here's an example I made using spacer divs :
http://cdpn.io/e/EWrMgL

HTML :

(spacer)

content 2

(spacer)

content 1

(spacer)

(spacer)

(spacer)

(spacer)

content 3

(spacer)

(spacer)

content 3

CSS :

.container, .spacer, .content, .row {
    display: flex;
}

.container {
    flex-flow: row wrap;
    font-family: sans-serif;
}

.row {
    width: 100%
}

.spacer {
    color: #2c3e50;
    flex: 1 1 0%;
}

.content {
    color: #ecf0f1;
    flex : 3 1 0%;
    flex-basis: 60%
}

.content, .spacer {
    justify-content: center;
    align-items: center;
    min-height: 5em;
    margin: 0.5em;
}

.col-1 {
    background-color: #96858F;
}

.col-2 {
     background-color:#9099A2;
}

.col-3 {
    background-color: #6d7993;
}

I made another attempt at a cleaner version using margins instead of wrapping
each item in a row : http://cdpn.io/e/xqMBmB

HTML:

content 2

content 1

content 3

content 3

CSS:

.container, .content{
    display: flex;
}

.container {
    flex-flow: row wrap;
    font-family: sans-serif;
}

.content {
    color: #ecf0f1;
    flex: 0 1 70%;

    justify-content: center;
    align-items: center;
    min-height: 5em;
    margin-bottom: 0.5em;
}

.col-1 {
    background-color: #96858F;
}

.col-2 {
    background-color:#9099A2;
    margin-left: 7.5%;
}

.col-3 {
    background-color: #6d7993;
    margin-left: 15%;
}

Is there a cleaner way to do this than enclosing each row in a div or changing the margins? I'll want to add @media rules to make the rows 100% width below a certain screen size.

Body:
If you change to flex-direction: column and remove wrap, the 2:nd will behave as the 1:st

I also added a media query to drop the left margin at a small width.

With this markup it's also easier to change order and layout, and is most likely the best way to do it.

.container, .content{
  display: flex;
}
.container {
  flex-direction: column;
  font-family: sans-serif;
}
.content {
  color: #ecf0f1;
  justify-content: center;
  align-items: center;
  min-height: 5em;
  margin-bottom: 0.5em;
}
.col-1 {
  background-color: #96858F;
}
.col-2 {
  background-color:#9099A2;
  margin-left: 7.5%;
}
.col-3 {
  background-color: #6d7993;
  margin-left: 15%;
}

@media screen and (max-width: 500px) {
  .content {
    margin-left: 0;
  }
}

<div class="container">
    <div class="content col-2">content 2</div>
    <div class="content col-1">content 1</div>
    <div class="content col-3">content 3</div>
    <div class="content col-3">content 3</div>
</div>

You can also size them, like this

.container, .content{
  display: flex;
}
.container {
  flex-direction: column;
  font-family: sans-serif;
}
.content {
  width: 70%;
  color: #ecf0f1;
  justify-content: center;
  align-items: center;
  min-height: 5em;
  margin-bottom: 0.5em;
}
.col-1 {
  background-color: #96858F;
}
.col-2 {
  background-color:#9099A2;
  margin-left: 7.5%;
}
.col-3 {
  background-color: #6d7993;
  margin-left: 15%;
}

@media screen and (max-width: 500px) {
  .content {
    margin-left: 0;
    width: 100%;
  }
}

<div class="container">
    <div class="content col-2">content 2</div>
    <div class="content col-1">content 1</div>
    <div class="content col-3">content 3</div>
    <div class="content col-3">content 3</div>
</div>


问:
How to get array format in javascript?
I am getting an array in AngularJs with factory function. This is the console

```<code>Array[0]
  0: "value1"
  1: "value2"
  length:2
</code>```

But when i want to get the length of the array

```<code>console.log(array.length)
</code>```

getting data from mysql in loopback

```<code> app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    }
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    return array;
        });

        return array;
      }
  }
});
</code>```

The controller look like:

```<code>app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
var emails = getFoo.getCommi(3,1);

setTimeout(function(){
    $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
}, 0)
}])
</code>```

I get that the length is 0. Why is that?

答: The length property of an Array in JavaScript is immutable. You can either set an Array's size by defining how many properties will be in there: var a = new Array(2), or by just passing in your values: var a = ['value1', 'value2'].</p>

Title: How to get array format in javascript?

Body:
I am getting an array in AngularJs with factory function. This is the console

Array[0]
  0: "value1"
  1: "value2"
  length:2

But when i want to get the length of the array

console.log(array.length)

getting data from mysql in loopback

 app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    }
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    return array;
        });

        return array;
      }
  }
});

The controller look like:

app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
var emails = getFoo.getCommi(3,1);

setTimeout(function(){
    $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
}, 0)
}])

I get that the length is 0. Why is that?


问:
Calling IronRuby from C# with a delegate
Is it possible to call an IronRuby method from C# with a delegate as parameter in such a way that yield would work?

The following gives me a wrong number of arguments (1 for 0) exception.

```<code>Action<string> action = Console.WriteLine;
var runtime = Ruby.CreateRuntime();
var engine = runtime.GetEngine("rb");
engine.Execute(@"
                 class YieldTest
                   def test
                     yield 'From IronRuby'
                   end
                 end
                ");
object test = engine.Runtime.Globals.GetVariable("YieldTest");
dynamic t = engine.Operations.CreateInstance(test);
t.test(action);
</code>```

答: Got an answer by IronRuby core team member Tomáš Matoušek on the IronRuby-core list that it's not possible. Yet.</p>

Body:
Is it possible to call an IronRuby method from C# with a delegate as parameter in such a way that yield would work?

The following gives me a wrong number of arguments (1 for 0) exception.

Action<string> action = Console.WriteLine;
var runtime = Ruby.CreateRuntime();
var engine = runtime.GetEngine("rb");
engine.Execute(@"
                 class YieldTest
                   def test
                     yield 'From IronRuby'
                   end
                 end
                ");
object test = engine.Runtime.Globals.GetVariable("YieldTest");
dynamic t = engine.Operations.CreateInstance(test);
t.test(action);


问:
Jmeter- how to include external .p12 SSL certificate
```<code>exception Jmeter throws-
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
    at com.ibm.jsse2.qc.a(qc.java:422)
    at com.ibm.jsse2.qc.h(qc.java:714)
    at com.ibm.jsse2.qc.a(qc.java:831)
    at com.ibm.jsse2.qc.startHandshake(qc.java:828)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:553)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:412)
    at org.apache.jmeter.protocol.http.sampler.LazySchemeSocketFactory.connectSocket(LazySchemeSocketFactory.java:97)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:179)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:328)
    at org.apache.jmeter.protocol.http.sampler.MeasuringConnectionManager$MeasuredConnection.open(MeasuringConnectionManager.java:114)
</code>```

Is there any specific Java version need to be used?
Jmeter version is - 3.1

答:
Just add the next lines to system.properties file (located in the "bin" folder of your JMeter installation)

```<code>javax.net.ssl.keyStoreType=pkcs12
javax.net.ssl.keyStore=/path/to/your/certificate.p12
javax.net.ssl.keyStorePassword=your_certificate_password_here
</code>```

Another option is providing the aforementioned properties via -D command-line argument like:

```<code>jmeter -Djavax.net.ssl.keyStoreType=pkcs12 -Djavax.net.ssl.keyStore=/path/to/your/certificate.p12 -Djavax.net.ssl.keyStorePassword=your_certificate_password_here
</code>```

This is more convenient for unattended executions, i.e. using Continuous Integration servers

Restart JMeter to pick the properties up

Now JMeter will be using your client certificate for requests encryption

See How to Set Your JMeter Load Test to Use Client Side Certificates for more details.

Alternatively you can use SSL Manager, however personally I consider using system properties more convenient.

Body:
exception Jmeter throws-
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
    at com.ibm.jsse2.qc.a(qc.java:422)
    at com.ibm.jsse2.qc.h(qc.java:714)
    at com.ibm.jsse2.qc.a(qc.java:831)
    at com.ibm.jsse2.qc.startHandshake(qc.java:828)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:553)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:412)
    at org.apache.jmeter.protocol.http.sampler.LazySchemeSocketFactory.connectSocket(LazySchemeSocketFactory.java:97)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:179)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:328)
    at org.apache.jmeter.protocol.http.sampler.MeasuringConnectionManager$MeasuredConnection.open(MeasuringConnectionManager.java:114)

Is there any specific Java version need to be used?
Jmeter version is - 3.1

Body:
Just add the next lines to system.properties file (located in the "bin" folder of your JMeter installation)

javax.net.ssl.keyStoreType=pkcs12
javax.net.ssl.keyStore=/path/to/your/certificate.p12
javax.net.ssl.keyStorePassword=your_certificate_password_here

Another option is providing the aforementioned properties via -D command-line argument like:

jmeter -Djavax.net.ssl.keyStoreType=pkcs12 -Djavax.net.ssl.keyStore=/path/to/your/certificate.p12 -Djavax.net.ssl.keyStorePassword=your_certificate_password_here

This is more convenient for unattended executions, i.e. using Continuous Integration servers

Restart JMeter to pick the properties up

Now JMeter will be using your client certificate for requests encryption

See How to Set Your JMeter Load Test to Use Client Side Certificates for more details.

Alternatively you can use SSL Manager, however personally I consider using system properties more convenient.


问:
Rollup lines by delimiter count via Python
I have a huge '|' separated file. There are certain lines which have broken into two and shifted to the next line. Given , I know the number of delimiters in each line (say 100) how do I append this to the first half to get the whole correct record.

I have tried the below but it does not work as expected :

```<code>with open(file_name) as f:
    for line in f:
        lis.append(line)

file_object=open(out_file,'w+')
for x in range(len(lis)):
    line=lis[x]
    delim_count=line.count('|')
    if(delim_count==100):
        file_object.write(line)
    elif(delim_count<100):
        `file_object.write(lis[x]+lis[x+1])
    x=x+1
file_object.close()
</code>```

答:
Your code was almost doing it.

You can have an accumulator that accumulates lines until the number of separators is 100. Note that you have to remove the \n character at the end of the lines.

Here's an improved version of your code:

```<code>with open(file_name, 'r') as fin:
    with open(out_file, 'w+') as fout:
        accum_line = ''
        for line in fin:
            accum_line += line.rstrip('\n')    # remove '\n' here
            if accum_line.count('|') == 100:
                fout.write(accum_line + '\n')  # add '\n' here
                accum_line = ''
</code>```

Body:
I have a huge '|' separated file. There are certain lines which have broken into two and shifted to the next line. Given , I know the number of delimiters in each line (say 100) how do I append this to the first half to get the whole correct record.

I have tried the below but it does not work as expected :

with open(file_name) as f:
    for line in f:
        lis.append(line)

file_object=open(out_file,'w+')
for x in range(len(lis)):
    line=lis[x]
    delim_count=line.count('|')
    if(delim_count==100):
        file_object.write(line)
    elif(delim_count<100):
        `file_object.write(lis[x]+lis[x+1])
    x=x+1
file_object.close()

Body:
Your code was almost doing it.

You can have an accumulator that accumulates lines until the number of separators is 100. Note that you have to remove the \n character at the end of the lines.

Here's an improved version of your code:

with open(file_name, 'r') as fin:
    with open(out_file, 'w+') as fout:
        accum_line = ''
        for line in fin:
            accum_line += line.rstrip('\n')    # remove '\n' here
            if accum_line.count('|') == 100:
                fout.write(accum_line + '\n')  # add '\n' here
                accum_line = ''


问:
How to resolve ambiguous column names when retrieving results?
I have two tables in my database:

NEWS table with columns:

id - the news id

user - the user id of the author)

USERS table with columns:

id - the user id

I want to execute this SQL:

```<code>SELECT * FROM news JOIN users ON news.user = user.id
</code>```

When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?

答:
If you don't feel like aliassing you can also just prefix the tablenames.

This way you can better automate generation of your queries. Also, it's a best-practice to not use select * (it is obviously slower than just selecting the fields you need
Furthermore, only explicitly name the fields you want to have.

```<code>SELECT
    news.id, news.title, news.author, news.posted,
    users.id, users.name, users.registered
FROM
    news
LEFT JOIN
    users
ON
    news.user = user.id
</code>```

OwnerDisplayName: Dan

ContentLicense: CC BY-SA 4.0

Body:
I have two tables in my database:

NEWS table with columns:

id - the news id

user - the user id of the author)

USERS table with columns:

id - the user id

I want to execute this SQL:

SELECT * FROM news JOIN users ON news.user = user.id

When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?

LastEditorDisplayName: Dan

Body:
If you don't feel like aliassing you can also just prefix the tablenames.

This way you can better automate generation of your queries. Also, it's a best-practice to not use select * (it is obviously slower than just selecting the fields you need
Furthermore, only explicitly name the fields you want to have.

SELECT
    news.id, news.title, news.author, news.posted,
    users.id, users.name, users.registered
FROM
    news
LEFT JOIN
    users
ON
    news.user = user.id

OwnerDisplayName: SchizoDuckie


答:
This

```<code>var r = new Revex { AllCharacters = "abcd" };
</code>```

Is syntactic sugar for

```<code>var r = new Revex();
r.AllCharacters = "abcd";
</code>```

It should be obvious that the AllCharacters field will be initialized to the default value.

If you don't want the default value you can do this

```<code>public class Revex{

  public IEnumerable<char> AllCharacters;

  public Revex(){
     AllCharacters = Enumerable.Range(0, 256).Select(Convert.ToChar).Where(c => !char.IsControl(c)).ToArray()
  }

  public Revex(IEnumerable<char> allCharacters){
    AllCharacters = allCharacters;
  }

}
</code>```

There's one more option which is this:

```<code>public class Regex{

    private static IEnumerable<char> DefaultAllCharacters(){ return Enumerable.Range.. }

    private IEnumerable<char> allCharacters;

    public IEnumerable<char> AllCharacters{
        get { return allCharacters ?? (allCharacters = DefaultAllCharacters()); }
        set { allCharacters = value; }
    }

}
</code>```

Here you lazily initialize the property value if it hasn't already been set.  So you don't pay  the upfront cost of setting the value if it hasn't been set, but you pay it later once the object is created.

Title: Will my attribute get assigned its default value if I use an initializer list?

Body:
This

var r = new Revex { AllCharacters = "abcd" };

Is syntactic sugar for

var r = new Revex();
r.AllCharacters = "abcd";

It should be obvious that the AllCharacters field will be initialized to the default value.

If you don't want the default value you can do this

public class Revex{

  public IEnumerable<char> AllCharacters;

  public Revex(){
     AllCharacters = Enumerable.Range(0, 256).Select(Convert.ToChar).Where(c => !char.IsControl(c)).ToArray()
  }

  public Revex(IEnumerable<char> allCharacters){
    AllCharacters = allCharacters;
  }

}

There's one more option which is this:

public class Regex{

    private static IEnumerable<char> DefaultAllCharacters(){ return Enumerable.Range.. }

    private IEnumerable<char> allCharacters;

    public IEnumerable<char> AllCharacters{
        get { return allCharacters ?? (allCharacters = DefaultAllCharacters()); }
        set { allCharacters = value; }
    }

}

Here you lazily initialize the property value if it hasn't already been set.  So you don't pay  the upfront cost of setting the value if it hasn't been set, but you pay it later once the object is created.


问:
return observable to the caller function like returning promises
I am currently migrating to angular 2 from angular 1.x. The application currently follows John Papa's style guide Return a Promise from Data Calls.

activate();

function activate() {
    /**
     * Step 1
     * Ask the getAvengers function for the
     * avenger data and wait for the promise
     */
    return getAvengers().then(function() {
        /**
         * Step 4
         * Perform an action on resolve of final promise
         */
        logger.info('Activated Avengers View');
    });
}

function getAvengers() {
      /**
       * Step 2
       * Ask the data service for the data and wait
       * for the promise
       */
      return dataservice.getAvengers()
          .then(function(data) {
              /**
               * Step 3
               * set the data and resolve the promise
               */
              vm.avengers = data;
              return vm.avengers;
      });
}
```

How can I do the same thing with Observables? with promise, i can write .then() in multiple functions and return it so that the caller functions also will wait for the promise. But with observable, What is the correct thing to do?
Where exactly i should subscribe and where i should just map the values and return the observable?

答:
While using promises you use .then(), using Observables, you have plenty of operators that lets you combine multiple observables, create side effect, modify values emitted by the initial observable, etc. map as explained by @Supamiu is an example of all those operators.

Observables do not do anything as-is, they define a data-flow, it's only the subscription that triggers the data-broadcasting process.

Async Pipe

You don't really need to use subscribe most of the time, you can make angular handle that for you, with the async pipe. eg:

component :

```<code>this.avengers$=this.dataservice.getAvengers().do(()=>console.log("Avengers fetched");
</code>```

template :

```<code><span *ngFor="avenger of avengers$|async">{{avenger.name}}</span>
</code>```

the fact it defines a data-flow allows you to react to events creating very-complex streams without much side effect or efforts.

creating new avengers on click for example:

component :

```<code>avengerClick$ = new Subject<mouseEvent>();

constructor(){
    let initialAvengers = this.dataservice.getAvengers().do(()=>console.log("Avengers fetched").switchMap(avangers);
    this.avengers$ = Observable.merge(
        initialAvengers,
        this.avengerClick.switchMap(()=>this.dataservice.createAvenger()) // let's say this.dataservice.createAvenger() returns the new list of avengers
    )
}
</code>```

template :

```<code><span *ngFor="avenger of avengers$|async">{{avenger.name}}</span>
<span (click)="avengerClick$.next($event)">Create an avenger</span>
</code>```

Body:
I am currently migrating to angular 2 from angular 1.x. The application currently follows John Papa's style guide Return a Promise from Data Calls.

activate();

function activate() {
    /**
     * Step 1
     * Ask the getAvengers function for the
     * avenger data and wait for the promise
     */
    return getAvengers().then(function() {
        /**
         * Step 4
         * Perform an action on resolve of final promise
         */
        logger.info('Activated Avengers View');
    });
}

function getAvengers() {
      /**
       * Step 2
       * Ask the data service for the data and wait
       * for the promise
       */
      return dataservice.getAvengers()
          .then(function(data) {
              /**
               * Step 3
               * set the data and resolve the promise
               */
              vm.avengers = data;
              return vm.avengers;
      });
}

How can I do the same thing with Observables? with promise, i can write .then() in multiple functions and return it so that the caller functions also will wait for the promise. But with observable, What is the correct thing to do?
Where exactly i should subscribe and where i should just map the values and return the observable?

Body:
While using promises you use .then(), using Observables, you have plenty of operators that lets you combine multiple observables, create side effect, modify values emitted by the initial observable, etc. map as explained by @Supamiu is an example of all those operators.

Observables do not do anything as-is, they define a data-flow, it's only the subscription that triggers the data-broadcasting process.

Async Pipe

You don't really need to use subscribe most of the time, you can make angular handle that for you, with the async pipe. eg:

component :

this.avengers$=this.dataservice.getAvengers().do(()=>console.log("Avengers fetched");

template :

<span *ngFor="avenger of avengers$|async">{{avenger.name}}</span>

the fact it defines a data-flow allows you to react to events creating very-complex streams without much side effect or efforts.

creating new avengers on click for example:

component :

avengerClick$ = new Subject<mouseEvent>();

constructor(){
    let initialAvengers = this.dataservice.getAvengers().do(()=>console.log("Avengers fetched").switchMap(avangers);
    this.avengers$ = Observable.merge(
        initialAvengers,
        this.avengerClick.switchMap(()=>this.dataservice.createAvenger()) // let's say this.dataservice.createAvenger() returns the new list of avengers
    )
}

template :

<span *ngFor="avenger of avengers$|async">{{avenger.name}}</span>
<span (click)="avengerClick$.next($event)">Create an avenger</span>


问:
What is the difference between getText() and getSelection() of SWT Spinner?
For a Spinner control in SWT, what is the difference between getText() and getSelection()? The only thing I can make out is the return type. However, I cannot enter any text, only numbers are allowed.

getText():
  Returns a string containing a copy of the contents of the receiver's text field, or an empty string if there are no contents.

getSelection():
  Returns the selection, which is the receiver's position.

So why do we have two different getters and which one should I use?

答:
getText specifically says it can be empty (I'd guess it depends on platform whether this ever happens). It then allows to distinguish this case from value 0.

You could use getText when using Spinner with decimal digits (see http://help.eclipse.org/luna/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/widgets/Spinner.html#setDigits(int)), since getSelection in this case is farther from the meaning of the value. But note that the decimal separator depends on the current locale.


问:
I need to modify a VBA code to delete all the other rows but not the one that I input
I have this VBA code

```<code>Sub DeleteRows()
Dim rng As Range
Dim InputRng As Range
Dim DeleteRng As Range
Dim DeleteStr As String
xTitleId = "Delete"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
DeleteStr = Application.InputBox("Delete Text", xTitleId, Type:=2)
For Each rng In InputRng
    If rng.Value = DeleteStr Then
        If DeleteRng Is Nothing Then
            Set DeleteRng = rng
        Else
            Set DeleteRng = Application.Union(DeleteRng, rng)
        End If
    End If
Next
DeleteRng.EntireRow.Delete
End Sub
</code>```

This one deletes all the rows for the word I input. I need it to delete all the others except the word I input.
Thanks in advance!

答:
This should do the job. You had the EntireRow in the wrong place.

```<code>Sub DeleteRows()
    ' 03 Apr 2017

    Dim Cell As Range
    Dim InputRng As Range
    Dim DeleteRng As Range
    Dim DeleteStr As String
    Dim xTitleId As String

    xTitleId = "Delete"
    Set InputRng = Application.InputBox("Range :", xTitleId, Selection.Address, Type:=8)
    DeleteStr = InputBox("Delete Text", xTitleId)
    For Each Cell In InputRng
        If StrComp(Cell.Value, DeleteStr, vbTextCompare) Then
            If DeleteRng Is Nothing Then
                Set DeleteRng = Cell.EntireRow
            Else
                Set DeleteRng = Application.Union(DeleteRng, Cell.EntireRow)
            End If
        End If
    Next
    DeleteRng.Delete
End Sub
</code>```

Body:
I have this VBA code

Sub DeleteRows()
Dim rng As Range
Dim InputRng As Range
Dim DeleteRng As Range
Dim DeleteStr As String
xTitleId = "Delete"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
DeleteStr = Application.InputBox("Delete Text", xTitleId, Type:=2)
For Each rng In InputRng
    If rng.Value = DeleteStr Then
        If DeleteRng Is Nothing Then
            Set DeleteRng = rng
        Else
            Set DeleteRng = Application.Union(DeleteRng, rng)
        End If
    End If
Next
DeleteRng.EntireRow.Delete
End Sub

This one deletes all the rows for the word I input. I need it to delete all the others except the word I input.
Thanks in advance!

Body:
This should do the job. You had the EntireRow in the wrong place.

Sub DeleteRows()
    ' 03 Apr 2017

    Dim Cell As Range
    Dim InputRng As Range
    Dim DeleteRng As Range
    Dim DeleteStr As String
    Dim xTitleId As String

    xTitleId = "Delete"
    Set InputRng = Application.InputBox("Range :", xTitleId, Selection.Address, Type:=8)
    DeleteStr = InputBox("Delete Text", xTitleId)
    For Each Cell In InputRng
        If StrComp(Cell.Value, DeleteStr, vbTextCompare) Then
            If DeleteRng Is Nothing Then
                Set DeleteRng = Cell.EntireRow
            Else
                Set DeleteRng = Application.Union(DeleteRng, Cell.EntireRow)
            End If
        End If
    Next
    DeleteRng.Delete
End Sub


问:
Image path uploading and retrieving it in view in Codeigniter
I am new in codeigniter. And i was trying to upload images for a product. Right now i am trying with uploading only one image for each product. And i have done this in my controller:

```<code>    <?php defined('BASEPATH') OR exit('No direct script access allowed');
    class Users extends CI_Controller
    {
    function  __construct() {
    parent::__construct();
    $this->load->model('user');
    }

     function add(){
      if($this->input->post('userSubmit')){

        //Check whether user upload picture
        if(!empty($_FILES['picture']['name'])){
            $config['upload_path'] = 'uploads/images/';
            $config['allowed_types'] = 'jpg|jpeg|png|gif';
            $config['file_name'] = $_FILES['picture']['name'];

            //Load upload library and initialize configuration
            $this->load->library('upload',$config);
            $this->upload->initialize($config);

            if($this->upload->do_upload('picture')){
                $uploadData = $this->upload->data();
                $picture = $uploadData['file_name'];
            }else{
                $picture = '';
            }
        }else{
            $picture = '';
        }

        //Prepare array of user data
        $userData = array(
            'name' => $this->input->post('name'),
            'email' => $this->input->post('email'),
            'picture' => $picture
        );

        //Pass user data to model
        $insertUserData = $this->user->insert($userData);

        //Storing insertion status message.
        if($insertUserData){
            $this->session->set_flashdata('success_msg', 'User data have been added successfully.');
        }else{
            $this->session->set_flashdata('error_msg', 'Some problems occured, please try again.');
        }
    }
    //Form for adding user data
    $data['data']=$this->user->getdata();
    $this->load->view('show',$data);
}

public function show()
{
    #code
    $data['data']=$this->user->getdata();
    $this->load->view('show',$data);

}
</code>```

}

I have this in my model:

```<code>    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class User extends CI_Model{
   function __construct() {
    $this->load->database();
    $this->tableName = 'users';
    $this->primaryKey = 'id';
}

   public function insert($data = array()){
    if(!array_key_exists("created",$data)){
        $data['created'] = date("Y-m-d H:i:s");
    }
    if(!array_key_exists("modified",$data)){
        $data['modified'] = date("Y-m-d H:i:s");
    }
    $insert = $this->db->insert($this->tableName,$data);
    if($insert){
        return $this->db->insert_id();
    }else{
        return false;
    }
}

    public function getdata()
{
  $query=$this->db->get('users');
  return $query->result_array();
}
</code>```

}

Issue is i am being able to store data along with image name in the database, and the selected image is uploaded in the specified folder in project folder which currently is:

```<code>    root folder->image:
               -application
               -system
               -uploads
                  .images(images are saved here)
</code>```

Now in the problem is with view. I am trying to access the stored images dynamically like this:

```<code>      <!DOCTYPE html>
       <html>
     <head>
   <meta charset="utf-8">
   <title>show</title>
    </head>
       <body>

    <table border='1' cellpadding='4'>
        <tr>
            <td><strong>User_Id</strong></td>
            <td><strong>Name</strong></td>
            <td><strong>Image</strong></td>
            <td><strong>Option</strong></td>
        </tr>
    <?php foreach ($data as $p): ?>
            <tr>
                <td><?php echo $p['id']; ?></td>
                <td><?php echo $p['name']; ?></td>
                <td><img src="../uploads/images/<?php echo $p['picture']; ?>" /> </td>
                <td>
                    <a href="#">View</a> |

                </td>
            </tr>
    <?php endforeach; ?>
    </table>
</code>```

With this image source the image is not coming. only imge crack thumbnails is seen. I also tried giving root folder of image manually like this:

```<code>    <img src="../uploads/images/image-0-02-03-15420e726f6e9c97408cbb86b222586f7efe3b002e588ae6bdcfc3bc1ea1561e-V.jpg" />
     or like this
     <img src="../../uploadsimages/image-0-02-03-15420e726f6e9c97408cbb86b222586f7efe3b002e588ae6bdcfc3bc1ea1561e-V.jpg" />
</code>```

but it ain't helping. Can anyone help me? Any suggestions and advice are highly welcome.Thank you.

答:
try this

```<code>     <img src="<?php echo base_url('uploads/images/'.$p['picture']); ?>"/>

insted of this line
<img src="../uploads/images/<?php echo $p['picture']; ?>" />
</code>```

also set your folder location corectly

Body:
I am new in codeigniter. And i was trying to upload images for a product. Right now i am trying with uploading only one image for each product. And i have done this in my controller:

    <?php defined('BASEPATH') OR exit('No direct script access allowed');
    class Users extends CI_Controller
    {
    function  __construct() {
    parent::__construct();
    $this->load->model('user');
    }

     function add(){
      if($this->input->post('userSubmit')){

        //Check whether user upload picture
        if(!empty($_FILES['picture']['name'])){
            $config['upload_path'] = 'uploads/images/';
            $config['allowed_types'] = 'jpg|jpeg|png|gif';
            $config['file_name'] = $_FILES['picture']['name'];

            //Load upload library and initialize configuration
            $this->load->library('upload',$config);
            $this->upload->initialize($config);

            if($this->upload->do_upload('picture')){
                $uploadData = $this->upload->data();
                $picture = $uploadData['file_name'];
            }else{
                $picture = '';
            }
        }else{
            $picture = '';
        }

        //Prepare array of user data
        $userData = array(
            'name' => $this->input->post('name'),
            'email' => $this->input->post('email'),
            'picture' => $picture
        );

        //Pass user data to model
        $insertUserData = $this->user->insert($userData);

        //Storing insertion status message.
        if($insertUserData){
            $this->session->set_flashdata('success_msg', 'User data have been added successfully.');
        }else{
            $this->session->set_flashdata('error_msg', 'Some problems occured, please try again.');
        }
    }
    //Form for adding user data
    $data['data']=$this->user->getdata();
    $this->load->view('show',$data);
}

public function show()
{
    #code
    $data['data']=$this->user->getdata();
    $this->load->view('show',$data);

}

}

I have this in my model:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class User extends CI_Model{
   function __construct() {
    $this->load->database();
    $this->tableName = 'users';
    $this->primaryKey = 'id';
}

   public function insert($data = array()){
    if(!array_key_exists("created",$data)){
        $data['created'] = date("Y-m-d H:i:s");
    }
    if(!array_key_exists("modified",$data)){
        $data['modified'] = date("Y-m-d H:i:s");
    }
    $insert = $this->db->insert($this->tableName,$data);
    if($insert){
        return $this->db->insert_id();
    }else{
        return false;
    }
}

    public function getdata()
{
  $query=$this->db->get('users');
  return $query->result_array();
}

}

Issue is i am being able to store data along with image name in the database, and the selected image is uploaded in the specified folder in project folder which currently is:

    root folder->image:
               -application
               -system
               -uploads
                  .images(images are saved here)

Now in the problem is with view. I am trying to access the stored images dynamically like this:

      <!DOCTYPE html>

   <meta charset="utf-8">
   <title>show</title>

            User_Id
            Name
            Image
            Option

    <?php foreach ($data as $p): ?>

                <?php echo $p['id']; ?>
                <?php echo $p['name']; ?>
                <img src="../uploads/images/<?php echo $p['picture']; ?>" />

                    View |

    <?php endforeach; ?>

With this image source the image is not coming. only imge crack thumbnails is seen. I also tried giving root folder of image manually like this:

     or like this

but it ain't helping. Can anyone help me? Any suggestions and advice are highly welcome.Thank you.

Body:
try this

     <img src="<?php echo base_url('uploads/images/'.$p['picture']); ?>"/>

insted of this line
<img src="../uploads/images/<?php echo $p['picture']; ?>" />

also set your folder location corectly


问:
regex join line infos
I have to parse this package:

```<code>WGS AUFFUELLUNGEN
ADMIN1          23.03.
17:09   -20-   1500.00
17:10   JD20    560.00
17:11  -2.0-    112.00
ADMIN1          24.03.
14:51   JD50    500.00
ADMIN2          27.03.
08:58   JD50    500.00
----------------------
               3172.00
</code>```

Parsing the user and date is easy:

```<code>\r?\n(.*)\s+(\d\d\.\d\d\.)
</code>```

Parsing the time, denomination and amount is easy too:

```<code>\r?\n(\d\d:\d\d)\s+(.*)\s+(\d+\.\d\d)
</code>```

But I need a parsing that detects user, date, time, denomination and amount for every booking at once.

Any ideas?

答:
Your second regex is too eager, have a look at this.

I suggest to change it into \r?\n(\d\d:\d\d)\s+(.*?)\s+(\d+.\d\d)

This regex would match user, date, time, denomination and amount for every booking at once, but I have added the multiline regex flag.:

```<code>(^(.*)\s+(\d\d\.\d\d\.)$|^(\d\d:\d\d)\s+(.*)\s+(\d+\.\d\d)$)+
</code>```

Title: regex join line infos

Body:
I have to parse this package:

WGS AUFFUELLUNGEN
ADMIN1          23.03.
17:09   -20-   1500.00
17:10   JD20    560.00
17:11  -2.0-    112.00
ADMIN1          24.03.
14:51   JD50    500.00
ADMIN2          27.03.
08:58   JD50    500.00
----------------------
               3172.00

Parsing the user and date is easy:

\r?\n(.*)\s+(\d\d\.\d\d\.)

Parsing the time, denomination and amount is easy too:

\r?\n(\d\d:\d\d)\s+(.*)\s+(\d+\.\d\d)

But I need a parsing that detects user, date, time, denomination and amount for every booking at once.

Any ideas?

Body:
Your second regex is too eager, have a look at this.

I suggest to change it into \r?\n(\d\d:\d\d)\s+(.*?)\s+(\d+.\d\d)

This regex would match user, date, time, denomination and amount for every booking at once, but I have added the multiline regex flag.:

(^(.*)\s+(\d\d\.\d\d\.)$|^(\d\d:\d\d)\s+(.*)\s+(\d+\.\d\d)$)+


问:
Manually rendering django template with date filter
I've got the template to render manually, but not the dates with a filter.  Is there a way of doing this without formatting the dates before I put them in the context?

Here is the code:

```<code>t= This is to notify you that you are booked on the course {{title}} that starts on {{start_date|date:"F j, Y"}} at {{start|time}} and is being held at {{venue}}.

c = {'startdate': datetime.datetime(2010, 12, 1, 9, 0), 'enddate': datetime.datetime(2010, 12, 1, 12, 0), 'has_cpd': False, 'title': 'Course 1', 'closes': None, 'creator': 1L, 'venue': 'Venue for Course 1', 'summary': 'Course 1 Summary', 'tags': '', 'attachment': <FieldFile: None>, 'organiser': 3L, 'id': 1L, 'opens': datetime.datetime(2010, 11, 30, 20, 1, 50, 951490), 'venue_map': None}

t.render(c)
</code>```

This gives the output:

```<code>This is to notify you that you are booked on the course Course 1 that starts on  at  and is being held at Venue for Course 1.
</code>```

Why don't the dates show up?

答:
Looks like a simple typo between start_date vs. startdate.</p>

```<code>In [18]: t= Template("""This is to notify you that you are booked on the course {{title}} that starts on {{startdate|date:"F j, Y"}} at {{start|time}} and is being held at {{venue}}.""")
In [19]: t.render(c)Out[19]: u'This is to notify you that you are booked on the course Course 1 that starts on December 1, 2010 at  and is being held at Venue for Course 1.'
</code>```

Body:
I've got the template to render manually, but not the dates with a filter.  Is there a way of doing this without formatting the dates before I put them in the context?

Here is the code:

t= This is to notify you that you are booked on the course {{title}} that starts on {{start_date|date:"F j, Y"}} at {{start|time}} and is being held at {{venue}}.

c = {'startdate': datetime.datetime(2010, 12, 1, 9, 0), 'enddate': datetime.datetime(2010, 12, 1, 12, 0), 'has_cpd': False, 'title': 'Course 1', 'closes': None, 'creator': 1L, 'venue': 'Venue for Course 1', 'summary': 'Course 1 Summary', 'tags': '', 'attachment': <FieldFile: None>, 'organiser': 3L, 'id': 1L, 'opens': datetime.datetime(2010, 11, 30, 20, 1, 50, 951490), 'venue_map': None}

t.render(c)

This gives the output:

This is to notify you that you are booked on the course Course 1 that starts on  at  and is being held at Venue for Course 1.

Why don't the dates show up?

Body:
Looks like a simple typo between start_date vs. startdate.

In [18]: t= Template("""This is to notify you that you are booked on the course {{title}} that starts on {{startdate|date:"F j, Y"}} at {{start|time}} and is being held at {{venue}}.""")
In [19]: t.render(c)Out[19]: u'This is to notify you that you are booked on the course Course 1 that starts on December 1, 2010 at  and is being held at Venue for Course 1.'


问:
Symfony JWT token: exception when token is expired
I am using JWT Token Bundle for user authentication. When the token is expired I get 500 server error. Instead of this how can I return JsonResponse with error code and message?

Here is my authenticator class:

```<code> class JwtTokenAuthentication extends AbstractGuardAuthenticator
{
/**
 * @var JWTEncoderInterface
 */
private $jwtEncoder;

/**
 * @var EntityManager
 */
private $em;

public function __construct(JWTEncoderInterface $jwtEncoder, EntityManager $em)
{
    $this->jwtEncoder = $jwtEncoder;
    $this->em = $em;
}

public function getCredentials(Request $request)
{
    $extractor = new AuthorizationHeaderTokenExtractor(
        'Bearer',
        'Authorization'
    );
    $token = $extractor->extract($request);
    if (!$token) {
        return null;
    }

    return $token;
}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    $data = $this->jwtEncoder->decode($credentials);
    if(!$data){
      return null;
    }
    $user = $this->em->getRepository("AlumnetCoreBundle:User")->find($data["email"]);
    return $user;
}

public function checkCredentials($credentials, UserInterface $user)
{
    return true;
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    //todo
}

public function start(Request $request, AuthenticationException $authException = null)
{
    return new JsonResponse([
        'errorMessage' => 'auth required'
    ], Response::HTTP_UNAUTHORIZED);
}
}
</code>```

答:
I surround my entire code in a try catch block, when the JWT Token Expired error message is generated, it is caught in the catch block.

{
  "error": 1,
  "status": 400,
  "msg": "Expired JWT Token",
  "data": []
}

```<code>/**
 * @Route("/api/tokens")
 * @Method("POST")
 */
public function newTokenAction(Request $request)
{
    try {
    $data['_username'] = $request->get('_username');
    $data['_password'] = $request->get('_password');
    if (empty($data['_username']) || empty($data['_password'])) {
        throw new \Exception('Username or password fields empty');
    }

    $user = $this->getDoctrine()->getRepository('AppBundle:User')->findOneBy(array('username' => $data['_username']));
    if (!$user) {
        throw new \Exception('Username or password does not exist');
    } else if ($user->hasRole('ROLE_SUPER_ADMIN')) {
        throw new \Exception('Admin is not allowed to login through app');
    } else if (!$user->getEnabled()) {
        throw new \Exception('User is not enabled');
    } else if ($user->getIsDeleted()) {
        throw new \Exception('User does not exist any more');
    }

    $isValid = $this->get('security.password_encoder')->isPasswordValid($user, $data['_password']);
    if (!$isValid) {
        throw new \Exception('Bad Credentials');
    }

    $token = $this->get('lexik_jwt_authentication.encoder')->encode(array(
        'username' => $data['_username'],
        'exp' => time() + 3600,
        'secret_key' => ____________,
    ));

    $user->setAuthToken($token);
    $em = $this->getEntityManager();
    $em->persist($user);
    $em->flush();

    $json = $this->getJsonResponse(0, 200, 'User Logged In');

    $response = new Response($json);
    $response->headers->set('Content-Type', 'application/json');
    return $response;
} catch (\Exception $e) {
    // Using custom Execption class
    $customApiProblem = new CustomApiProblem(self::API_ERROR_TRUE, $httpStatusCode, $e->getMessage());
    $customApiProblem->set('data', $data);
    $serializer = $this->container->get('jms_serializer');
    $response_json = $serializer->serialize($customApiProblem->toArray(), 'json');
    return new Response($response_json, $statusCode);
}
}
</code>```

Body:
I am using JWT Token Bundle for user authentication. When the token is expired I get 500 server error. Instead of this how can I return JsonResponse with error code and message?

Here is my authenticator class:

 class JwtTokenAuthentication extends AbstractGuardAuthenticator
{
/**
 * @var JWTEncoderInterface
 */
private $jwtEncoder;

/**
 * @var EntityManager
 */
private $em;

public function __construct(JWTEncoderInterface $jwtEncoder, EntityManager $em)
{
    $this->jwtEncoder = $jwtEncoder;
    $this->em = $em;
}

public function getCredentials(Request $request)
{
    $extractor = new AuthorizationHeaderTokenExtractor(
        'Bearer',
        'Authorization'
    );
    $token = $extractor->extract($request);
    if (!$token) {
        return null;
    }

    return $token;
}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    $data = $this->jwtEncoder->decode($credentials);
    if(!$data){
      return null;
    }
    $user = $this->em->getRepository("AlumnetCoreBundle:User")->find($data["email"]);
    return $user;
}

public function checkCredentials($credentials, UserInterface $user)
{
    return true;
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    //todo
}

public function start(Request $request, AuthenticationException $authException = null)
{
    return new JsonResponse([
        'errorMessage' => 'auth required'
    ], Response::HTTP_UNAUTHORIZED);
}
}

Body:
I surround my entire code in a try catch block, when the JWT Token Expired error message is generated, it is caught in the catch block.

{
  "error": 1,
  "status": 400,
  "msg": "Expired JWT Token",
  "data": []
}

/**
 * @Route("/api/tokens")
 * @Method("POST")
 */
public function newTokenAction(Request $request)
{
    try {
    $data['_username'] = $request->get('_username');
    $data['_password'] = $request->get('_password');
    if (empty($data['_username']) || empty($data['_password'])) {
        throw new \Exception('Username or password fields empty');
    }

    $user = $this->getDoctrine()->getRepository('AppBundle:User')->findOneBy(array('username' => $data['_username']));
    if (!$user) {
        throw new \Exception('Username or password does not exist');
    } else if ($user->hasRole('ROLE_SUPER_ADMIN')) {
        throw new \Exception('Admin is not allowed to login through app');
    } else if (!$user->getEnabled()) {
        throw new \Exception('User is not enabled');
    } else if ($user->getIsDeleted()) {
        throw new \Exception('User does not exist any more');
    }

    $isValid = $this->get('security.password_encoder')->isPasswordValid($user, $data['_password']);
    if (!$isValid) {
        throw new \Exception('Bad Credentials');
    }

    $token = $this->get('lexik_jwt_authentication.encoder')->encode(array(
        'username' => $data['_username'],
        'exp' => time() + 3600,
        'secret_key' => ____________,
    ));

    $user->setAuthToken($token);
    $em = $this->getEntityManager();
    $em->persist($user);
    $em->flush();

    $json = $this->getJsonResponse(0, 200, 'User Logged In');

    $response = new Response($json);
    $response->headers->set('Content-Type', 'application/json');
    return $response;
} catch (\Exception $e) {
    // Using custom Execption class
    $customApiProblem = new CustomApiProblem(self::API_ERROR_TRUE, $httpStatusCode, $e->getMessage());
    $customApiProblem->set('data', $data);
    $serializer = $this->container->get('jms_serializer');
    $response_json = $serializer->serialize($customApiProblem->toArray(), 'json');
    return new Response($response_json, $statusCode);
}
}


问:
Render loop vs. explicitely calling update method
I am working on a 3D simulation program using openGL which uses a render loop with a fixed framerate to keep the screen updated as the world changes. Standard procedure really, and for a typical video game this is certainly the best approach (I originally took this code from an openGL game tutorial). But for me, the 3D scene will not be changing as rapidly and unpredictably as in a computer game. It will be possible for the 3D scene itself to change from time to time but in general it won't change between render calls (it's more of a visualisation tool for geometric problems). The user will be able to control the position/orientation of the camera but in general there will be times when the camera won't move for several seconds/minutes (potentially hundreds of render calls) and since the 3D scene is likely be static for the majority of the time, I wonder if I really need a continuous render loop...?

My thinking is that I will remove the automatic render loop and instead I will explicitly call my update method when either,

The 3D scene changes (very rare)

The camera moves (somewhat rare)

As I will be using this largely for research purposes, the scene/camera is likely to stay in one state for several minutes at a time and it seems silly to be continuously updating the frame buffer when it's not changing.

My question then is, is this a good approach? All the online tutorials for 3D graphics rendering seem to deal with game design but that's not really my requirement. In other words, what are the pros and cons of using a render loop vs. manually calling "update()" whenever something changes?

Thanks

答:
There's no problem with this approach, in fact many 3D apps, like 3DS MAX use explicit rendering. You just pick what is better for your needs, in most games scene changes each frame so it's better to have update loop, but if you were doing some chess game, without animated UI you could also use explicit rendering only when the scene changes.

For apps with rare changes, like 3DS or Blender it would be better to call rendering only on change. This way you save the CPU/GPU but also power and your PC don't heat up so much.

With explicit rendering you can also have some performance tricks, like drawing simplified scene when camera moves, for better performance. Then when camera stops you render the full scene in background once again, and replace the low-quality rendering with the new one.


问:
How to get both like and dislike count of the post in single query using cake php or php
I have researched a day but I not get the solution.if it is possible to get he likes and dislike count of all post using single CakePHP query
table structure

```<code>id user_id  posts_id  like_and_dislike
1    1         1          1
2    2         1          1
3    4         1          0
4    5         2          1
</code>```

Here we need to get the like and dislike count of all posts that is for
post 1 like -> 2 and dislike -> 1 And for post - 2 like -> 1 and dislike -> 0
need to list the count.please any one help on this query if it not possible please help in php query

答:
I'm guess you need this</p>

```<code>SELECT post_id,
COUNT( CASE WHEN like_and_dislike = 1 THEN 1 END ) AS like_cnt,
COUNT( CASE WHEN like_and_dislike = 0 THEN 1 END ) AS dislike_cnt
FROM your_table
GROUP BY post_id
-- ORDER BY something
-- LIMIT x, y
</code>```

Body:
I have researched a day but I not get the solution.if it is possible to get he likes and dislike count of all post using single CakePHP query
table structure

id user_id  posts_id  like_and_dislike
1    1         1          1
2    2         1          1
3    4         1          0
4    5         2          1

Here we need to get the like and dislike count of all posts that is for
post 1 like -> 2 and dislike -> 1 And for post - 2 like -> 1 and dislike -> 0
need to list the count.please any one help on this query if it not possible please help in php query

Body:
I'm guess you need this

SELECT post_id,
COUNT( CASE WHEN like_and_dislike = 1 THEN 1 END ) AS like_cnt,
COUNT( CASE WHEN like_and_dislike = 0 THEN 1 END ) AS dislike_cnt
FROM your_table
GROUP BY post_id
-- ORDER BY something
-- LIMIT x, y


问:
Jquery gallery/lightbox onClick always return "-1"
I have a gallery of 12 links(images), that when clicked open lightbox and show the clicked image. But when I click the image it always open the last one. When i try to console log index I always get "-1";</p>

```<code>var image= $('.Gallery div a');
console.log(image.index($(e.target)));
</code>```

答:
You can do the following:

```<code>$('.Gallery div a').click(function(e){
    var index = $(this).index(); //this is the index of your currently clicked element
    //do your rest of logic here
});
</code>```

The above will bind click event to all of a tags who has a parent div and which has a parent having Gallery class.

Body:
I have a gallery of 12 links(images), that when clicked open lightbox and show the clicked image. But when I click the image it always open the last one. When i try to console log index I always get "-1";

var image= $('.Gallery div a');
console.log(image.index($(e.target)));

Body:
You can do the following:

$('.Gallery div a').click(function(e){
    var index = $(this).index(); //this is the index of your currently clicked element
    //do your rest of logic here
});

The above will bind click event to all of a tags who has a parent div and which has a parent having Gallery class.


问:
How to add existent database into my app in iphone sdk
I have to add an existent DB into my iphone app
I' ve tried to put it into the project's folder and used this init function

```<code>-(id) initDatabase{
    databaseName = @"mydatabase.sqlite";
    // Get the path to the documents directory and append the databaseName
 NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDir = [documentPaths objectAtIndex:0];
 databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
 [databasePath retain];

    return self;
}
</code>```

and then i used this function

```<code>if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK){ //inserting methods
</code>```

but I have an error: the table 'nametable' does not exists, I am sure that this table exists and I think that these methods create a new db file into the device path.

答: In the sidebar, check "Targets" => (Your Target) => "Copy Bundle Resources". I think your database file might not have been copied because Xcode has no idea what file type that is.

Body:
I have to add an existent DB into my iphone app
I' ve tried to put it into the project's folder and used this init function

-(id) initDatabase{
    databaseName = @"mydatabase.sqlite";
    // Get the path to the documents directory and append the databaseName
 NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDir = [documentPaths objectAtIndex:0];
 databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
 [databasePath retain];

    return self;
}

and then i used this function

if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK){ //inserting methods

but I have an error: the table 'nametable' does not exists, I am sure that this table exists and I think that these methods create a new db file into the device path.


问:
how to get the last value of the array variable in loops
Here is my code:

```<code>class test {
  public static void main(String args[]) {
    int a[]={5,8,9,7,3};
    int j;

    for(j=0;j<a.length-1;j++)
    {
        if(a[j]>a[j+1])
        {
            int temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp;
        }
        System.out.print(a[j]+"   "); // last value of array a[4] is not printed
    }
  }
}
</code>```

This is one part of my program, here last value of the array is not printed?!

Can you help me anyone how to get the last value of array?

答:
...here last value of the array is not printed...

is not printed because you are doing this:

```<code>for(j=0;j<a.length-1;j++)
</code>```

to only print the last element is enough to do:

```<code>System.out.println(a[a.length - 1]);
</code>```

Body:
Here is my code:

class test {
  public static void main(String args[]) {
    int a[]={5,8,9,7,3};
    int j;

    for(j=0;ja[j+1])
        {
            int temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp;
        }
        System.out.print(a[j]+"   "); // last value of array a[4] is not printed
    }
  }
}

This is one part of my program, here last value of the array is not printed?!

Can you help me anyone how to get the last value of array?

Body:
...here last value of the array is not printed...

is not printed because you are doing this:

for(j=0;j<a.length-1;j++)

to only print the last element is enough to do:

System.out.println(a[a.length - 1]);