问:
I followed a tutorial to make a temperature conversion android app
I followed everything step by step and after running the app, when I use the slider, my numbers don't change and stay stuck at "0.1". Did I miss a step?

```<code>    package com.example.tempconv;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.SeekBar;
    import android.widget.TextView;

    import java.util.Locale;

    public class MainActivity extends AppCompatActivity {

    TextView cel, fah;

    SeekBar seekBar;

    double c, f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    cel =  (TextView) findViewById(R.id.cel);
    fah =  (TextView) findViewById(R.id.fah);

    seekBar = (SeekBar) findViewById(R.id.seekBar);
    seekBar.setMax(400);
    seekBar.setProgress(200);

    c = seekBar.getProgress() - 200;
    f = c * 1.8 +32;
    cel.setText(String.format(Locale.getDefault(), "0.1 C", c));
    fah.setText(String.format(Locale.getDefault(), "0.1 F", f));

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            c = i - 200;
            f = c * 1.8 +32;
            cel.setText(String.format(Locale.getDefault(), "0.1 C", c));
            fah.setText(String.format(Locale.getDefault(), "0.1 F", f));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

}
}
</code>```

This is exactly what I've seen in the YouTube Video I watched. I really don't know what I'm doing wrong as it worked completely fine for the guy I watched.

答:
It looks like you're not letting the String.format() method do it's job - String.format(locale, string, variable)

You're hard-coding your string result with no where for your variable to be included.

For your double c and f, put %s in the string so the String.format can replace and format the string for you.

```<code>cel.setText(String.format(Locale.getDefault(), "%s C", c));
fah.setText(String.format(Locale.getDefault(), "%s F", f));
</code>```

Note that this setText() is called twice in your provided code, and as such, will need to be changed for both parts (most importantly the onProgressChanged part())

Body:
I followed everything step by step and after running the app, when I use the slider, my numbers don't change and stay stuck at "0.1". Did I miss a step?

    package com.example.tempconv;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.SeekBar;
    import android.widget.TextView;

    import java.util.Locale;

    public class MainActivity extends AppCompatActivity {

    TextView cel, fah;

    SeekBar seekBar;

    double c, f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    cel =  (TextView) findViewById(R.id.cel);
    fah =  (TextView) findViewById(R.id.fah);

    seekBar = (SeekBar) findViewById(R.id.seekBar);
    seekBar.setMax(400);
    seekBar.setProgress(200);

    c = seekBar.getProgress() - 200;
    f = c * 1.8 +32;
    cel.setText(String.format(Locale.getDefault(), "0.1 C", c));
    fah.setText(String.format(Locale.getDefault(), "0.1 F", f));

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            c = i - 200;
            f = c * 1.8 +32;
            cel.setText(String.format(Locale.getDefault(), "0.1 C", c));
            fah.setText(String.format(Locale.getDefault(), "0.1 F", f));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

}
}

This is exactly what I've seen in the YouTube Video I watched. I really don't know what I'm doing wrong as it worked completely fine for the guy I watched.

Body:
It looks like you're not letting the String.format() method do it's job - String.format(locale, string, variable)

You're hard-coding your string result with no where for your variable to be included.

For your double c and f, put %s in the string so the String.format can replace and format the string for you.

cel.setText(String.format(Locale.getDefault(), "%s C", c));
fah.setText(String.format(Locale.getDefault(), "%s F", f));

Note that this setText() is called twice in your provided code, and as such, will need to be changed for both parts (most importantly the onProgressChanged part())


来源: stackexchange

问:
How to save text file as variable in IOS
I am sending some images via socket and I would like to create text file with information about the images to send over the network as well.  I right now I can send the images no problem by creating a variable for the image data like so

```<code>let imageData = UIImageJPEGRepresentation(someUIImage, 1.0)
</code>```

How do create a variable with the data of the text file?

```<code>let textData = someTextFileAsData.....
</code>```

答:
Is this what you want?</p>

```<code>let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
// Get the URL to the file. Below is an example
let fileURL = documentsDirectory.appendingPathComponent("test").appendingPathExtension("txt") // Replace "test" with your fileName and "txt" with your fileExtension
var text = ""

do {
    text = try String(contentsOf: fileURL)
} catch {
    fatalError("error: \(error.localizedDescription)")
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am sending some images via socket and I would like to create text file with information about the images to send over the network as well.  I right now I can send the images no problem by creating a variable for the image data like so

let imageData = UIImageJPEGRepresentation(someUIImage, 1.0)

How do create a variable with the data of the text file?

let textData = someTextFileAsData.....

Body:
Is this what you want?

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
// Get the URL to the file. Below is an example
let fileURL = documentsDirectory.appendingPathComponent("test").appendingPathExtension("txt") // Replace "test" with your fileName and "txt" with your fileExtension
var text = ""

do {
    text = try String(contentsOf: fileURL)
} catch {
    fatalError("error: \(error.localizedDescription)")
}


问:
Is returning a forward-declared structure undefined behavior?
I have the following code (include-guards omitted for simplicity's sake):

= foo.hpp =

```<code>struct FOO
{
  int not_used_in_this_sample;
  int not_used_in_this_sample2;
};
</code>```

= main.cpp =

```<code>#include "foo_generator.hpp"
#include "foo.hpp"

int main()
{
  FOO foo = FooGenerator::createFoo(0xDEADBEEF, 0x12345678);

  return 0;
}
</code>```

= foo_generator.hpp =

```<code>struct FOO; // FOO is only forward-declared

class FooGenerator
{
  public:

    // Note: we return a FOO, not a FOO&
    static FOO createFoo(size_t a, size_t b);
};
</code>```

= foo_generator.cpp =

```<code>#include "foo_generator.hpp"
#include "foo.hpp"

FOO FooGenerator::createFoo(size_t a, size_t b)
{
  std::cout << std::hex << a << ", " << b << std::endl;

  return FOO();
}
</code>```

This code, as it stands, compiles perfectly fine without any warning. If my understanding is correct, it should output:

```<code>deadbeef, 12345678
</code>```

But instead, it randomly displays:

```<code>12345678, 32fb23a1
</code>```

Or just crashes.

If I replace the forward-declaration of FOO in foo_generator.hpp with #include "foo.hpp", then it works.

So here is my question: Does returning a forward-declared structure lead to undefined behavior ? Or what can possibly go wrong ?

Compiler used: MSVC 9.0 and 10.0 (both show the issue)

答: That should be fine according to 8.3.5.6: "The type of a parameter or the return type for a function declaration that is not a definition may be an incomplete class type."</p>

ContentLicense: CC BY-SA 2.5

Body:
I have the following code (include-guards omitted for simplicity's sake):

= foo.hpp =

struct FOO
{
  int not_used_in_this_sample;
  int not_used_in_this_sample2;
};

= main.cpp =

#include "foo_generator.hpp"
#include "foo.hpp"

int main()
{
  FOO foo = FooGenerator::createFoo(0xDEADBEEF, 0x12345678);

  return 0;
}

= foo_generator.hpp =

struct FOO; // FOO is only forward-declared

class FooGenerator
{
  public:

    // Note: we return a FOO, not a FOO&
    static FOO createFoo(size_t a, size_t b);
};

= foo_generator.cpp =

#include "foo_generator.hpp"
#include "foo.hpp"

FOO FooGenerator::createFoo(size_t a, size_t b)
{
  std::cout << std::hex << a << ", " << b << std::endl;

  return FOO();
}

This code, as it stands, compiles perfectly fine without any warning. If my understanding is correct, it should output:

deadbeef, 12345678

But instead, it randomly displays:

12345678, 32fb23a1

Or just crashes.

If I replace the forward-declaration of FOO in foo_generator.hpp with #include "foo.hpp", then it works.

So here is my question: Does returning a forward-declared structure lead to undefined behavior ? Or what can possibly go wrong ?

Compiler used: MSVC 9.0 and 10.0 (both show the issue)


问:
Color points with the color as a column in ggplot2
I have a dataframe where a color is given for each point in a column:

```<code>d<-data.frame(x=1:10,y=1:10,col=c(rep("red",n=5),rep("green",n=5)))
d$col<-as.character(d$col)
ggplot(data=d,aes(x=x,y=y,colour=col))+geom_point()
</code>```

As you can see, the colour is not interpreted as a colour, but a group,

can ggplot handle such cases?

答:
Just found out how:

color should be given as a separate vector, and not related to the data

```<code>ggplot(data=d,aes(x=x,y=y))+geom_point(colour=d$col)
</code>```

Body:
I have a dataframe where a color is given for each point in a column:

d<-data.frame(x=1:10,y=1:10,col=c(rep("red",n=5),rep("green",n=5)))
d$col<-as.character(d$col)
ggplot(data=d,aes(x=x,y=y,colour=col))+geom_point()

As you can see, the colour is not interpreted as a colour, but a group,

can ggplot handle such cases?

Body:
Just found out how:

color should be given as a separate vector, and not related to the data

ggplot(data=d,aes(x=x,y=y))+geom_point(colour=d$col)


问:
Why is this c code not changing the value of arr[3]?
I am creating an int array and then tricking c into believing that it's an array of short values. I know it's not good practice but I am just trying to understand why this isn't working. Shouldn't this change the value of arr[3] ?

```<code>#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    int arr[5];
    arr[0] = 0; arr[1] = 0; arr[2] = 0; arr[4] = 0;
    arr[3] = 128;
    ((short*)arr)[6] = 128; // Shouldn't this change arr[3] ? as 6,7 indices in the arr of short would compromise of arr[3] in arr of ints?
    int i = 0;
    for (i = 0; i < 5; i++){
        printf("%d\n", arr[i]);
    }
    return 0;
}
</code>```

PS: Here's a deeper clarification:
When I cast int array to a short array, it seemingly becomes an array of 10 short elements (not 5). So when I change arr[6], I am changing only the first 16 bits of the int arr[3]. So arr[3] should still change and it is NOT that I am changing it to 128 again and not seeing the change.

FOR CLARIFICATION: THIS CODE IS ONLY FOR EXPERIMENTAL REASONS! I AM JUST LEARNING HOW POINTERS WORK AND I GET THAT ITS NOT GOOD PRACTICE.

答:
Have you considered endianness?

EDIT: Now to add more clarity ...

As others have mentioned in the comments, this is most definitely undefined behavior!  This is not just "not good practice", it's just don't do it!

Pointers on C is an excellent book that goes over everything you wanted to know about pointers and more.  It's dated but still very relevant.  You can probably find most of the information online, but I haven't seen many books that deal with pointers as completely as this one.

Though it sounds like you are experimenting, possibly as part of a class.  So, here are a number of things wrong with this code:

endianness

memory access model

assumption of type size

assumption of hardware architecture

cross type casting

Remember, even though C is considered a pretty low level language today, it is still a high level programming language that affords many key abstractions.

Now, look at your declaration again.

```<code>int arr[5];
</code>```

You've allocated 5 ints grouped together and accessed via a common variable named arr.   By the standard, the array is 5 elements of at least 2 bytes per element with base address of &arr[0].  So, you aren't guaranteed that an int is 2 bytes, or 4 bytes or whatever.  Likewise, as short is defined by the standard as at least 2 bytes.  However, a short is not an int even if they have the same byte width!  Remember, C is strongly typed.

Now, it looks like you are running on a machine where shorts are 2 bytes and ints are 4 bytes. That is where the endianness issue come into play: where is your most significant bit? And where is your most significant byte?

By casting the address of arr to a short pointer first of all breaks both the type and the memory access model.  Then, you want to access the 6th element from the offset of arr.  However, you aren't accessing relative to the int you declared arr to be, you are accessing through a short pointer that is pointing at the same address as arr!

These following operations ARE NOT the same!  And it also falls into the category of undefined - don't do this ever!

```<code>int foo;
int pfooInt;
short bar;
short * pfooShort;

bar = (short) foo;
pfooShort = (short*)&foo;
pfooInt = &foo;
bar = *pfooShort;
pfooShort = (short*)pfooInt[0];
</code>```

Another thing to clarify for you:

```<code>int arr[5];

((short *)arr)[6] ...
</code>```

This does not transform your int array of 5 elements into a short array with 10 elements.  arr is still an int array of 5 elements.  You just broke the access method and are trying to modify memory in an undefined manner.  What you did is tell the compiler "ignore what I told you about arr previously, treat arr as a short pointer for the life of this statement and access/modify 6th short relative to this pointer."

Body:
I am creating an int array and then tricking c into believing that it's an array of short values. I know it's not good practice but I am just trying to understand why this isn't working. Shouldn't this change the value of arr[3] ?

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    int arr[5];
    arr[0] = 0; arr[1] = 0; arr[2] = 0; arr[4] = 0;
    arr[3] = 128;
    ((short*)arr)[6] = 128; // Shouldn't this change arr[3] ? as 6,7 indices in the arr of short would compromise of arr[3] in arr of ints?
    int i = 0;
    for (i = 0; i < 5; i++){
        printf("%d\n", arr[i]);
    }
    return 0;
}

PS: Here's a deeper clarification:
When I cast int array to a short array, it seemingly becomes an array of 10 short elements (not 5). So when I change arr[6], I am changing only the first 16 bits of the int arr[3]. So arr[3] should still change and it is NOT that I am changing it to 128 again and not seeing the change.

FOR CLARIFICATION: THIS CODE IS ONLY FOR EXPERIMENTAL REASONS! I AM JUST LEARNING HOW POINTERS WORK AND I GET THAT ITS NOT GOOD PRACTICE.

Body:
Have you considered endianness?

EDIT: Now to add more clarity ...

As others have mentioned in the comments, this is most definitely undefined behavior!  This is not just "not good practice", it's just don't do it!

Pointers on C is an excellent book that goes over everything you wanted to know about pointers and more.  It's dated but still very relevant.  You can probably find most of the information online, but I haven't seen many books that deal with pointers as completely as this one.

Though it sounds like you are experimenting, possibly as part of a class.  So, here are a number of things wrong with this code:

endianness

memory access model

assumption of type size

assumption of hardware architecture

cross type casting

Remember, even though C is considered a pretty low level language today, it is still a high level programming language that affords many key abstractions.

Now, look at your declaration again.

int arr[5];

You've allocated 5 ints grouped together and accessed via a common variable named arr.   By the standard, the array is 5 elements of at least 2 bytes per element with base address of &arr[0].  So, you aren't guaranteed that an int is 2 bytes, or 4 bytes or whatever.  Likewise, as short is defined by the standard as at least 2 bytes.  However, a short is not an int even if they have the same byte width!  Remember, C is strongly typed.

Now, it looks like you are running on a machine where shorts are 2 bytes and ints are 4 bytes. That is where the endianness issue come into play: where is your most significant bit? And where is your most significant byte?

By casting the address of arr to a short pointer first of all breaks both the type and the memory access model.  Then, you want to access the 6th element from the offset of arr.  However, you aren't accessing relative to the int you declared arr to be, you are accessing through a short pointer that is pointing at the same address as arr!

These following operations ARE NOT the same!  And it also falls into the category of undefined - don't do this ever!

int foo;
int pfooInt;
short bar;
short * pfooShort;

bar = (short) foo;
pfooShort = (short*)&foo;
pfooInt = &foo;
bar = *pfooShort;
pfooShort = (short*)pfooInt[0];

Another thing to clarify for you:

int arr[5];

((short *)arr)[6] ...

This does not transform your int array of 5 elements into a short array with 10 elements.  arr is still an int array of 5 elements.  You just broke the access method and are trying to modify memory in an undefined manner.  What you did is tell the compiler "ignore what I told you about arr previously, treat arr as a short pointer for the life of this statement and access/modify 6th short relative to this pointer."


问:
Selenium ChromeDriver - is it possible to load multiple extensions?
(I'm new so don't kill me, please)

I'm trying to start ChromeDriver for a Chromium-based browser with multiple unpacked extensions, thus (simplified for your convenience, but basically the same as in the code):

```<code>   foreach (var path in ExtensionsPaths)
   {
    CommonWebDriver._ChromeOptionsForTorch.AddArguments(new string[1] { "--load-extension=" + path });
   }
</code>```

After the foreach finishes running, I see all the extensions I want to load listed in the options.

When I create the ChromeDriver, though, it only loads one extension from this list - the last one of them.

What am I doing wrong? Is it possible to load multiple extensions?

答:
You provide one argument string containing multiple paths to extensions separated by comma:</p>

```<code>ChromeOptions options = new ChromeOptions();
options.AddArgument(@"load-extension=c:\PathToFirstExtensionHere,c:\PathToSecondExtensionHere");
Driver = new ChromeDriver(options);
</code>```

Body:
(I'm new so don't kill me, please)

I'm trying to start ChromeDriver for a Chromium-based browser with multiple unpacked extensions, thus (simplified for your convenience, but basically the same as in the code):

   foreach (var path in ExtensionsPaths)
   {
    CommonWebDriver._ChromeOptionsForTorch.AddArguments(new string[1] { "--load-extension=" + path });
   }

After the foreach finishes running, I see all the extensions I want to load listed in the options.

When I create the ChromeDriver, though, it only loads one extension from this list - the last one of them.

What am I doing wrong? Is it possible to load multiple extensions?

Body:
You provide one argument string containing multiple paths to extensions separated by comma:

ChromeOptions options = new ChromeOptions();
options.AddArgument(@"load-extension=c:\PathToFirstExtensionHere,c:\PathToSecondExtensionHere");
Driver = new ChromeDriver(options);


问:
javax.servlet.jsp.JspException cannot be resolved to a type
I have a Spring 4 MVC Maven project in Eclipse Mars
I have this error javax.servlet.jsp.JspException cannot be resolved to a type in the JSP, even in my Project Facets -> Runtimes I have checked Apache Tomcat v7.0065
The error is in Edit time and I can find that type on the project's Java Build Path as M2_REPO/../javax.servlet-api-3.0.1.jar

答:
You may be looking at the wrong JAR file for JspException.

I am developing a Spring 4 app in Eclipse with a Maven project, but using an external Tomcat 8 server.  I was receiving the same error message in a JSP in the editor until I created and added a User Library in Eclipse that contained 'jsp-api.jar', which is actually a link in my Ubuntu file system to a file named 'tomcat8-jsp-api.jar'.

Once I added this new user library to my build path and then did a 'Build Project' in Eclipse, the red markers went away.  You may need to refresh the project after building.  Hopefully this at least points you in the right direction.


问:
Devexpress Winforms - Forms are fractured while transition one form to another
I am using Devexpress winform for my project. There are three forms simply. The first is MainForm that used MdiParent, the second is FormArticles that used listing articles about law into GridControl. And the last is FormArticleView that used viewing selected article into pdfViewer control. I managed to use documentManager and SplashScreenManager while loading Mdi Child forms and articles into one of Mdi Child form FormArticles. Here is my code:

```<code>   public prjLibrary()
    {
        InitializeComponent();
        var frm = new FormArticles{ MdiParent = this, Dock = DockStyle.Fill };
        frm.Show();
    }
</code>```

While transition one form to another, the forms is fractured and after load it is fixed. Here is my screenshot:

And here is fixed view:

How can I fix fractured view while transition of forms?

答:
This is because when the form from the first screenshot is getting focused, the controls have to be rendered in their Paint-event. This seems to take some time but you can see the fractured text is shown in rectangles where I think the underlying controls (radio buttons, text boxes, labels) are placed. So they are not rendered yet and not ready to go while any other call is blocking the thread. I think the problem is that you create a new form in your mainForm's constructor.

Anyway, it is a good practice to perform heavy tasks (which seem to block the painting of your controls) in a background thread having the UI waiting for the response. If this is too hard to do, try to do it after the UI is shown to the user. This could be the OnLoad- or even OnShown-event.

Note that I don't want to encourage you to write any business code into the UI layer but that seems not to be the question here.

Body:
I am using Devexpress winform for my project. There are three forms simply. The first is MainForm that used MdiParent, the second is FormArticles that used listing articles about law into GridControl. And the last is FormArticleView that used viewing selected article into pdfViewer control. I managed to use documentManager and SplashScreenManager while loading Mdi Child forms and articles into one of Mdi Child form FormArticles. Here is my code:

   public prjLibrary()
    {
        InitializeComponent();
        var frm = new FormArticles{ MdiParent = this, Dock = DockStyle.Fill };
        frm.Show();
    }

While transition one form to another, the forms is fractured and after load it is fixed. Here is my screenshot:

And here is fixed view:

How can I fix fractured view while transition of forms?


问:
Can You Use Arithmetic Operators to Flip Between 0 and 1
Is there a way without using logic and bitwise operators, just arithmetic operators, to flip between integers with the value 0 and 1?

ie.
variable ?= variable will make the variable 1 if it 0 or 0 if it is 1.

答:
Another way to flip a bit.  </p>

```<code>x = ABS(x - 1) // the absolute of (x - 1)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Another way to flip a bit.

x = ABS(x - 1) // the absolute of (x - 1)


问:
SQL Server 2008 Backup Transaction Logs
I understand that the transaction logs keep a record of historical transactions in order to facilitate a restore if needed. However do I need to keep creating transaction log backups for inactive databases that are hanging around on the server? No DDL statements are run against them and they are just used for reference. </p>

<p>I am just a bit worried that I might run out of log space if I get this wrong. </p>

答:
Transaction logs are actually truncated when they're backed up. So, if these databases are actually inactive, you shouldn't be backing up any transaction logs for them since the logs would be empty.

Also, common practice for "inactive" databases would be to make them READ ONLY with a SIMPLE recovery model.

Title: SQL Server 2008 Backup Transaction Logs

Body:
I understand that the transaction logs keep a record of historical transactions in order to facilitate a restore if needed. However do I need to keep creating transaction log backups for inactive databases that are hanging around on the server? No DDL statements are run against them and they are just used for reference.

I am just a bit worried that I might run out of log space if I get this wrong.


问:
NPM + Zurb Foundation + WebPack: Cannot resolve module 'foundation'
I am working on using Zurb Foundation with WebPack and NPM, without Bower.

The problem I am encountering is the same as this below:

https://github.com/zurb/foundation-sites/issues/7386

Essentially, when installing foundation-sites via NPM, there are references to a module "foundation" that is not found.  The error:

```<code>Module not found: Error: Cannot resolve module 'foundation' in c:\Users\Matt\Documents\Projects\test\node_modules\foundation-sites\dist
 @ ./~/foundation-sites/dist/foundation.js
</code>```

Here's the package.json:

```<code>{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "foundation-sites": "6.0.5",
    "webpack": "~1.12.6",
    "webpack-dev-server": "~1.2",
    "jquery": "2.1.1"
  }
}
</code>```

And here is webpack.config.js:

```<code>var path = require("path");
var webpack = require("webpack");
module.exports = {
    entry: {
      main: "./app/js/main.js"
    },
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: "style!css" },
            {
                test: /\.scss$/,
                loaders: ["style", "css", "sass"]
              },
              { test: /\.vue$/, loader: 'vue' }
        ],
        resolve: {
            modulesDirectories: ['node_modules']
        }
    },
     sassLoader: {
            includePaths: [path.resolve(__dirname, "./node_modules/foundation-sites/scss/")]
          },
    devServer: {
        proxy: {
            '/api/*': {
                target: 'http://localhost:4567',
                secure: false
            }
        }
    }
};
</code>```

I can work around this by including foundation via bower instead, but I want to eliminate bower and use only NPM.

答:
If you carefully see the foundation-sites 6.2.0 modules, you will find the changes in path as following

foundation-sites/dist/css/foundation.min.css

foundation-sites/dist/js/foundation.min.js

So basically you have to changes in webpack confing files entry as following

```<code>module.exports =  {
         entry: ['script!jquery/dist/jquery.min.js',
        'script!foundation-sites/dist/js/foundation.min.js',
         './app/app.jsx'
       ]
}
</code>```

and the entry for style should be like this

require('style!css!foundation-sites/dist/css/foundation.min.css');

Body:
I am working on using Zurb Foundation with WebPack and NPM, without Bower.

The problem I am encountering is the same as this below:

https://github.com/zurb/foundation-sites/issues/7386

Essentially, when installing foundation-sites via NPM, there are references to a module "foundation" that is not found.  The error:

Module not found: Error: Cannot resolve module 'foundation' in c:\Users\Matt\Documents\Projects\test\node_modules\foundation-sites\dist
 @ ./~/foundation-sites/dist/foundation.js

Here's the package.json:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "foundation-sites": "6.0.5",
    "webpack": "~1.12.6",
    "webpack-dev-server": "~1.2",
    "jquery": "2.1.1"
  }
}

And here is webpack.config.js:

var path = require("path");
var webpack = require("webpack");
module.exports = {
    entry: {
      main: "./app/js/main.js"
    },
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: "style!css" },
            {
                test: /\.scss$/,
                loaders: ["style", "css", "sass"]
              },
              { test: /\.vue$/, loader: 'vue' }
        ],
        resolve: {
            modulesDirectories: ['node_modules']
        }
    },
     sassLoader: {
            includePaths: [path.resolve(__dirname, "./node_modules/foundation-sites/scss/")]
          },
    devServer: {
        proxy: {
            '/api/*': {
                target: 'http://localhost:4567',
                secure: false
            }
        }
    }
};

I can work around this by including foundation via bower instead, but I want to eliminate bower and use only NPM.

Body:
If you carefully see the foundation-sites 6.2.0 modules, you will find the changes in path as following

foundation-sites/dist/css/foundation.min.css

foundation-sites/dist/js/foundation.min.js

So basically you have to changes in webpack confing files entry as following

module.exports =  {
         entry: ['script!jquery/dist/jquery.min.js',
        'script!foundation-sites/dist/js/foundation.min.js',
         './app/app.jsx'
       ]
}

and the entry for style should be like this

require('style!css!foundation-sites/dist/css/foundation.min.css');


问:
Why does the compiler invoke a templated copy constructor when assigning?
Consider the code below:

```<code>#include <iostream>

template<class T>
struct X
{
    X() = default;

    template<class U>
    X(const X<U>&)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }

/*
    template<class U>
    X& operator=(const X<U>&)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
        return *this;
    }
*/

};

int main()
{
    X<int> a;
    X<double> b;

    b = a;
}
</code>```

Live on Coliru

As you can see, the assignment operator is commented out. However, the line

```<code>b = a;
</code>```

compiles fine. I thought it should not compile, as a and b have different types, and the operator=(const X&) that is generated by default by the compiler will be instantiated by the underlying type, so it won't assign an X<int> to an X<double>.

To my surprise, the code compiles, and it seems that the templated copy constructor is being invoked. Why is this? Is it because the compiler tries first to cast the a to a b then invoke the default-generated B::operator=?

答:
template<class U> X(const X&) is a generalized user-defined conversion -- see Anton Savin's answer.

The rules for implicit type conversions are quite complex, so you should be wary of user-defined conversion functions (More Effective C++ Item 5). This is even more the case with template functions.

The code

```<code>#include <iostream>

template<class T>
struct X
{
    X() = default;

    template<class U>
    X(const X<U>&)
    {
        std::cout << "generalized ctor: " << __PRETTY_FUNCTION__ << std::endl;
    }

/*
    template<class U>
    X& operator=(const X<U>&)
    {
        std::cout << "generalized assignment: " << __PRETTY_FUNCTION__ << std::endl;
        return *this;
    }
*/
};

int main()
{
    X<int> a;
    X<double> b;

    b = a;
}
</code>```

returns

generalized ctor: X::X(const X&) [with U = int; T = double]

But for operator= not commented out, it returns

generalized assignment: X& X::operator=(const X&) [with U = int; T = double].

So you are correct that the implicitly generated operator=(const X&) will be instantiated by the underlying type and won't assign an X<int> to an X<double>. As Scott Meyers (see reference above) explains, your compiler is faced with a call to b.operator= of a X<double>, which takes a
const X<double>, and finds that no such function exists. Therefore, your compiler then tries to find an acceptable sequence of implicit type conversions it can apply to make the call succeed, see rules in the cpp reference. Your compiler finds your generalized user-defined conversion and converts your X<int> to X<double> to have the right argument type for b.operator=.

Body:
Consider the code below:

#include <iostream>

template<class T>
struct X
{
    X() = default;

    template<class U>
    X(const X&)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
    }

/*
    template<class U>
    X& operator=(const X&)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
        return *this;
    }
*/

};

int main()
{
    X<int> a;
    X<double> b;

    b = a;
}

Live on Coliru

As you can see, the assignment operator is commented out. However, the line

b = a;

compiles fine. I thought it should not compile, as a and b have different types, and the operator=(const X&) that is generated by default by the compiler will be instantiated by the underlying type, so it won't assign an X<int> to an X<double>.

To my surprise, the code compiles, and it seems that the templated copy constructor is being invoked. Why is this? Is it because the compiler tries first to cast the a to a b then invoke the default-generated B::operator=?

Body:
template<class U> X(const X<U>&) is a generalized user-defined conversion -- see Anton Savin's answer.

The rules for implicit type conversions are quite complex, so you should be wary of user-defined conversion functions (More Effective C++ Item 5). This is even more the case with template functions.

The code

#include <iostream>

template<class T>
struct X
{
    X() = default;

    template<class U>
    X(const X<U>&)
    {
        std::cout << "generalized ctor: " << __PRETTY_FUNCTION__ << std::endl;
    }

/*
    template<class U>
    X& operator=(const X<U>&)
    {
        std::cout << "generalized assignment: " << __PRETTY_FUNCTION__ << std::endl;
        return *this;
    }
*/
};

int main()
{
    X<int> a;
    X<double> b;

    b = a;
}

returns

generalized ctor: X::X(const X&) [with U = int; T = double]

But for operator= not commented out, it returns

generalized assignment: X& X::operator=(const X&) [with U = int; T = double].

So you are correct that the implicitly generated operator=(const X&) will be instantiated by the underlying type and won't assign an X<int> to an X<double>. As Scott Meyers (see reference above) explains, your compiler is faced with a call to b.operator= of a X<double>, which takes a
const X<double>, and finds that no such function exists. Therefore, your compiler then tries to find an acceptable sequence of implicit type conversions it can apply to make the call succeed, see rules in the cpp reference. Your compiler finds your generalized user-defined conversion and converts your X<int> to X<double> to have the right argument type for b.operator=.


问:
How to add consecutive elements of a list?
If I have the following list:

```<code>x = [0, 1, 2, 1, 3, 4, 0, 1, 0, 1, 0, 1, 1]
</code>```

And I have a number m = 4. From each element I have to consecutively add the next element to it until I reach a sum that is greater than or equal to 4. Then, I have to output the list containing how many numbers I had to add, including the starting one.So the output for this example would be:

```<code>y = [4, 3, 3, 2, 2, 1, 7, 6, 0, 0, 0, 0, 0]
</code>```

The first element 4 means that starting from x[0], it took 3 more elements for the sum to be 4, thus y[0] = 4.The end zeros signify that there is no possible way to get the sum 4.

答:
To add consecutive elements of a list, I recommend two steps:

Grab the slice of the list that you want.

Use the sum function to add all the elements.

You get a slice of a list with the start and end elements -- remembering that the end element is not included in the slice, so you need to add 1 to the position of the last item you want.

In general, if you want elements start through last, you grab that slice with

```<code>y_slice = y[start:(last+1) ]   # The parentheses aren't needed
</code>```

To get the sum of that slice you simply feed it to the function:

```<code>slice_sum = sum(y_slice)
</code>```

or

```<code>slice_sum = sum( y[start:(last+1) ] )
</code>```

Now, you need to figure out how to run through useful values of start and last.  Have fun.

Body:
If I have the following list:

x = [0, 1, 2, 1, 3, 4, 0, 1, 0, 1, 0, 1, 1]

And I have a number m = 4. From each element I have to consecutively add the next element to it until I reach a sum that is greater than or equal to 4. Then, I have to output the list containing how many numbers I had to add, including the starting one.So the output for this example would be:

y = [4, 3, 3, 2, 2, 1, 7, 6, 0, 0, 0, 0, 0]

The first element 4 means that starting from x[0], it took 3 more elements for the sum to be 4, thus y[0] = 4.The end zeros signify that there is no possible way to get the sum 4.

Body:
To add consecutive elements of a list, I recommend two steps:

Grab the slice of the list that you want.

Use the sum function to add all the elements.

You get a slice of a list with the start and end elements -- remembering that the end element is not included in the slice, so you need to add 1 to the position of the last item you want.

In general, if you want elements start through last, you grab that slice with

y_slice = y[start:(last+1) ]   # The parentheses aren't needed

To get the sum of that slice you simply feed it to the function:

slice_sum = sum(y_slice)

or

slice_sum = sum( y[start:(last+1) ] )

Now, you need to figure out how to run through useful values of start and last.  Have fun.


问:
Hibernate, Spring & HSQL: Table not Found Exception
we're using spring, hibernate and hsql to persist a simple user entity. We always get the error "table not found". Do you have any idea what this could be? It seems like the table is not generated or the hsql database is not running at all.

Regards,
G.

```<code>@Entity
@Table (name="USER")
public class User {

 @Id
 @GeneratedValue(strategy= GenerationType.AUTO)
 @Column(name="ID")
 private Long id;

 @Column(name="NAME", length = 100, nullable = false)
 private String name;

 public User(){}

        //getters and setters ...
</code>```

by this dao class:

```<code>package de.hsrm.mediathek;

import java.util.List;

public class UserDao implements IUserDao{

    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(final HibernateTemplate hibernateTemplate){
        this.hibernateTemplate = hibernateTemplate;
    }

    @Transactional
    public void store(final User user){
        hibernateTemplate.saveOrUpdate(user);
    }

    @Transactional
    public void delete(final Long userId){
        final User user = (User) hibernateTemplate.get(User.class, userId);
        hibernateTemplate.delete(user);
    }

    @Transactional(readOnly = true)
    public User findById(final Long userId){
        return (User) hibernateTemplate.get(User.class, userId);
    }

    @Transactional(readOnly = true)
    public List<User> findAll(){
        return hibernateTemplate.find("from User");
    }

}
</code>```

Configuration XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

 <tx:annotation-driven/>

 <bean id="dataSource"
   class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
  <property name="url" value="jdbc:hsqldb:mem:mediathekdb" />
  <property name="username" value="sa" />
  <property name="password" value="" />
 </bean>

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>de.hsrm.mediathek.User</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
    <prop key="hibernate.hbm2dll.auto">create-drop</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.format_sql">true</prop>
    <prop key="hibernate.connection.pool_size">10</prop>
    <prop
     key="hibernate.cache.provider_class">
     org.hibernate.cache.HashtableCacheProvider</prop>
   </props>
  </property>

 </bean>

 <bean id="hibernateTemplate"
  class="org.springframework.orm.hibernate3.HibernateTemplate">
  <property name="sessionFactory" ref="sessionFactory"/>
 </bean>

 <bean id="userDao" class="de.hsrm.mediathek.UserDao">
  <property name="hibernateTemplate" ref="hibernateTemplate" />
 </bean>

 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

 <!-- Interceptor for hibernate calls to be able to create and close sessions
 <bean id="hibernateInterceptor"
  class="org.springframework.orm.hibernate3.HibernateInterceptor">
  <property name="sessionFactory"><ref local="sessionFactory"/></property>
 </bean>
-->
</beans>
</code>```

Error LOG:

```<code>Caused by: java.sql.SQLException: Table not found in statement [insert into User (ID, NAME) values (null, ?)]
 at org.hsqldb.jdbc.Util.throwError(Unknown Source)
 at org.hsqldb.jdbc.jdbcPreparedStatement.<init>(Unknown Source)
 at org.hsqldb.jdbc.jdbcConnection.prepareStatement(Unknown Source)
 at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:528)
 at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:95)
 at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:30)
 ... 63 more
</code>```

答:
I'd suggest trying to run HSQLDB in server mode using:

```<code>java -classpath hsqldb.jar org.hsqldb.server.Server
</code>```

Check that it's running using Database manager:

```<code>java -classpath hsqldb.jar org.hsqldb.util.DatabaseManagerSwing
</code>```

Next, change your Hibernate URL, so it uses server mode HSQLDB:

```<code><property name="url" value="jdbc:hsqldb:mediathekdb" />
</code>```

I've had success using this method. It's possible that create-drop doesn't work properly when using a memory only instance.

Body:
we're using spring, hibernate and hsql to persist a simple user entity. We always get the error "table not found". Do you have any idea what this could be? It seems like the table is not generated or the hsql database is not running at all.

Regards,
G.

@Entity
@Table (name="USER")
public class User {

 @Id
 @GeneratedValue(strategy= GenerationType.AUTO)
 @Column(name="ID")
 private Long id;

 @Column(name="NAME", length = 100, nullable = false)
 private String name;

 public User(){}

        //getters and setters ...

by this dao class:

package de.hsrm.mediathek;

import java.util.List;

public class UserDao implements IUserDao{

    private HibernateTemplate hibernateTemplate;

    public void setHibernateTemplate(final HibernateTemplate hibernateTemplate){
        this.hibernateTemplate = hibernateTemplate;
    }

    @Transactional
    public void store(final User user){
        hibernateTemplate.saveOrUpdate(user);
    }

    @Transactional
    public void delete(final Long userId){
        final User user = (User) hibernateTemplate.get(User.class, userId);
        hibernateTemplate.delete(user);
    }

    @Transactional(readOnly = true)
    public User findById(final Long userId){
        return (User) hibernateTemplate.get(User.class, userId);
    }

    @Transactional(readOnly = true)
    public List<User> findAll(){
        return hibernateTemplate.find("from User");
    }

}

Configuration XML:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

 <tx:annotation-driven/>

 <bean id="dataSource"
   class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
  <property name="url" value="jdbc:hsqldb:mem:mediathekdb" />
  <property name="username" value="sa" />
  <property name="password" value="" />
 </bean>

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>de.hsrm.mediathek.User</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
    <prop key="hibernate.hbm2dll.auto">create-drop</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.format_sql">true</prop>
    <prop key="hibernate.connection.pool_size">10</prop>
    <prop
     key="hibernate.cache.provider_class">
     org.hibernate.cache.HashtableCacheProvider</prop>
   </props>
  </property>

 </bean>

 <bean id="hibernateTemplate"
  class="org.springframework.orm.hibernate3.HibernateTemplate">
  <property name="sessionFactory" ref="sessionFactory"/>
 </bean>

 <bean id="userDao" class="de.hsrm.mediathek.UserDao">
  <property name="hibernateTemplate" ref="hibernateTemplate" />
 </bean>

 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

</beans>

Error LOG:

Caused by: java.sql.SQLException: Table not found in statement [insert into User (ID, NAME) values (null, ?)]
 at org.hsqldb.jdbc.Util.throwError(Unknown Source)
 at org.hsqldb.jdbc.jdbcPreparedStatement.<init>(Unknown Source)
 at org.hsqldb.jdbc.jdbcConnection.prepareStatement(Unknown Source)
 at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:528)
 at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:95)
 at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:30)
 ... 63 more

Body:
I'd suggest trying to run HSQLDB in server mode using:

java -classpath hsqldb.jar org.hsqldb.server.Server

Check that it's running using Database manager:

java -classpath hsqldb.jar org.hsqldb.util.DatabaseManagerSwing

Next, change your Hibernate URL, so it uses server mode HSQLDB:

<property name="url" value="jdbc:hsqldb:mediathekdb" />

I've had success using this method. It's possible that create-drop doesn't work properly when using a memory only instance.


问:
save to localStorage
i'm curious if its possible to save the text input a user types in the field to localStorage , so in this html example , i'd want to save the innner html from the div#match_player_id , that is created when you click the button</p>

```<code><input type="text" id="contract_year" placeholder="Contract" autocomplete="off">

<input value="Submit" onclick="document.querySelector('#match_player_id').innerHTML = document.querySelector('#contract_year').value" type="button">

<div id="match_player_id"></div>
</code>```

答:
Firstly, you should really be using unobtrusive event handlers to hook to events instead of the outdated on* event attributes. As you've tagged jQuery in the question this can be done incredibly simply.

From there you can just use localStorage.setItem() to save the value you require, like this:

$('button').click(function(e) {
  e.preventDefault();

  var contractYear = $('#contract_year').val();
  $('#match_player_id').html(contractYear);

  localStorage.setItem(contractYear);
});
```

<pre class="lang-html prettyprint-override"><code><input type="text" id="contract_year" placeholder="Contract" autocomplete="off">
<button type="button">Submit</button>
<div id="match_player_id"></div>
</code>```

Working example

Title: save to localStorage

Body:
i'm curious if its possible to save the text input a user types in the field to localStorage , so in this html example , i'd want to save the innner html from the div#match_player_id , that is created when you click the button

<input type="text" id="contract_year" placeholder="Contract" autocomplete="off">

<input value="Submit" onclick="document.querySelector('#match_player_id').innerHTML = document.querySelector('#contract_year').value" type="button">

Body:
Firstly, you should really be using unobtrusive event handlers to hook to events instead of the outdated on* event attributes. As you've tagged jQuery in the question this can be done incredibly simply.

From there you can just use localStorage.setItem() to save the value you require, like this:

$('button').click(function(e) {
  e.preventDefault();

  var contractYear = $('#contract_year').val();
  $('#match_player_id').html(contractYear);

  localStorage.setItem(contractYear);
});

<input type="text" id="contract_year" placeholder="Contract" autocomplete="off">
<button type="button">Submit</button>
<div id="match_player_id"></div>

Working example


问:
Angular2 view not updating after changes. Possible 'this' context issue?
I'm trying to update the totalRequests, payloadSize, payloadSizeType properties every time I receive a message from the WebSocket. This works successfully, and I can confirm by the console.log's as they update correctly every log according to what's being sent from the server.

The problem is that my template is not updating to reflect these changes for some reason.

I can confirm that there is no other underlying error because when I make a test function and update those values on click, they update and the changes are indeed reflected in the template, so I've concluded that the error must be coming from the way I am passing the WS callbacks in...unless there's something else I'm unaware of.

```<code>import { Component, OnInit } from '@angular/core';

import { AttackService } from './attack.service';
import { WebSocketService } from '../../../lib/service/websocket/websocket.service';
import { WebSocketConfig } from '../../../lib/service/websocket/websocket.config';

@Component({
  selector: 'attack',
  templateUrl: './attack.component.html',
  styleUrls: ['./attack.component.css'],
  providers: [AttackService, WebSocketService]
})
export class AttackComponent implements OnInit {
  private model: Object = {
    url: "http://localhost",
    kb_per_request: 5,
    duration: 5
  };

  private hasReceivedMessage: boolean = false;
  private totalRequests: number = 0;
  private payloadSize: number = 0;
  private payloadSizeType: string = 'KB';

  constructor(private attackService: AttackService, private socket: WebSocketService) {}

  ngOnInit(): void {
    this.socket.create(new WebSocketConfig(this.sOnOpen, this.sOnClose, this.sOnMessage, this.sOnError));
  }

  sOnOpen(): void {
    console.log('WebSocket connection successfully established.');
  }

  sOnClose(code: number): void {
    console.log(`WebSocket connection closed (${code}).`);
  }

  sOnMessage(data: any): void {
    this.hasReceivedMessage = true;

    this.totalRequests = data.total_requests;
    this.payloadSize = data.payload_size;
    this.payloadSizeType = data.payload_size_type;

    console.log('====================================');
    console.log('Total requests: ', this.totalRequests);
    console.log('Payload size: ', this.payloadSize);
    console.log('Payload type: ', this.payloadSizeType);
  }

  sOnError(data: any): void {
    console.log('WebSocket error occurred: ', data);
  }

  submit(): void {
    this.attackService.attack(this.model).subscribe(
        res => {
          let data = res.json();

          if (data.success) {
            console.log(data.message);
          }
        },
        err => {
          console.log('Error:', err);
        }
      );
  }
}
</code>```

I thought I was passing in the methods with the wrong this context, but even when binding the correct context, the template still does not update to reflect the changes.

```<code>constructor(private attackService: AttackService, private socket: WebSocketService) {
    this.sOnOpen = this.sOnOpen.bind(this);
    this.sOnClose = this.sOnClose.bind(this);
    this.sOnMessage = this.sOnMessage.bind(this);
    this.sOnError = this.sOnError.bind(this);
  }
</code>```

Anyone know a solution to this problem?

UPDATE:

WebSocketService:

```<code>import { Injectable } from '@angular/core';
import { WebSocketConfig } from './websocket.config';

@Injectable()
export class WebSocketService {
  private socket = null;
  private uri = "ws://localhost:80/ws";

  create(config: WebSocketConfig): void {
    window.onload = () => {
      this.socket = new WebSocket(this.uri);
      this.socket.onopen = config.onOpen;
      this.socket.onclose = config.onClose;
      this.socket.onmessage = res => config.onMessage(JSON.parse(res.data));
      this.socket.onerror = config.onError;
    };
  }

  send(data: any): void {
    this.socket.send(data);
  }
}
</code>```

答:
My solution to this was not quite what the two answers provided, but they pointed me in the right direction.

First of all, I was creating my websocket connection in the AttackComponent, and I would rather create it in my AppComponent so that the connection can be accessed globally (not related to my question).

I created an interval function that checks to see is the socket has connected, and if so then it invokes a function call, which would be a callback function that I pass in from my AttackComponent.

That callback is passed in via an arrow function in the AttackComponent, which gives me the right this context. I then call another method to set the sockets onmessage property to my AttackComponent's method, and I bind it to the proper this context which is allowed by the arrow function. I could also just do the binding outside of that all together.

Here is en example of what I did, that now works and updates my template properly:

WebSocketService:

```<code>  setSocketOnMessage(fn: Function): void {
    this.socket.onmessage = function (message) {
      fn(JSON.parse(message.data), message);
    };
  }

  onReady(cb: Function): void {
    let socketInterval = setInterval(() => {
      if (this.isConnected()) {
        cb();

        clearInterval(socketInterval);
      }
    }, 50);
  }
</code>```

AttackComponent:

```<code>  constructor(private webSocketService: WebSocketService) {
    this.webSocketService.onReady(() => {
      this.webSocketService.setSocketOnMessage(this.sOnMessage.bind(this));
    });
  }

  sOnMessage(data: any): void {
    this.hasReceivedMessage = true;
    this.totalRequests = data.total_requests;
    this.payloadSize = data.payload_size;
    this.payloadSizeType = data.payload_size_type;
  }
</code>```

Body:
I'm trying to update the totalRequests, payloadSize, payloadSizeType properties every time I receive a message from the WebSocket. This works successfully, and I can confirm by the console.log's as they update correctly every log according to what's being sent from the server.

The problem is that my template is not updating to reflect these changes for some reason.

I can confirm that there is no other underlying error because when I make a test function and update those values on click, they update and the changes are indeed reflected in the template, so I've concluded that the error must be coming from the way I am passing the WS callbacks in...unless there's something else I'm unaware of.

import { Component, OnInit } from '@angular/core';

import { AttackService } from './attack.service';
import { WebSocketService } from '../../../lib/service/websocket/websocket.service';
import { WebSocketConfig } from '../../../lib/service/websocket/websocket.config';

@Component({
  selector: 'attack',
  templateUrl: './attack.component.html',
  styleUrls: ['./attack.component.css'],
  providers: [AttackService, WebSocketService]
})
export class AttackComponent implements OnInit {
  private model: Object = {
    url: "http://localhost",
    kb_per_request: 5,
    duration: 5
  };

  private hasReceivedMessage: boolean = false;
  private totalRequests: number = 0;
  private payloadSize: number = 0;
  private payloadSizeType: string = 'KB';

  constructor(private attackService: AttackService, private socket: WebSocketService) {}

  ngOnInit(): void {
    this.socket.create(new WebSocketConfig(this.sOnOpen, this.sOnClose, this.sOnMessage, this.sOnError));
  }

  sOnOpen(): void {
    console.log('WebSocket connection successfully established.');
  }

  sOnClose(code: number): void {
    console.log(`WebSocket connection closed (${code}).`);
  }

  sOnMessage(data: any): void {
    this.hasReceivedMessage = true;

    this.totalRequests = data.total_requests;
    this.payloadSize = data.payload_size;
    this.payloadSizeType = data.payload_size_type;

    console.log('====================================');
    console.log('Total requests: ', this.totalRequests);
    console.log('Payload size: ', this.payloadSize);
    console.log('Payload type: ', this.payloadSizeType);
  }

  sOnError(data: any): void {
    console.log('WebSocket error occurred: ', data);
  }

  submit(): void {
    this.attackService.attack(this.model).subscribe(
        res => {
          let data = res.json();

          if (data.success) {
            console.log(data.message);
          }
        },
        err => {
          console.log('Error:', err);
        }
      );
  }
}

I thought I was passing in the methods with the wrong this context, but even when binding the correct context, the template still does not update to reflect the changes.

constructor(private attackService: AttackService, private socket: WebSocketService) {
    this.sOnOpen = this.sOnOpen.bind(this);
    this.sOnClose = this.sOnClose.bind(this);
    this.sOnMessage = this.sOnMessage.bind(this);
    this.sOnError = this.sOnError.bind(this);
  }

Anyone know a solution to this problem?

UPDATE:

WebSocketService:

import { Injectable } from '@angular/core';
import { WebSocketConfig } from './websocket.config';

@Injectable()
export class WebSocketService {
  private socket = null;
  private uri = "ws://localhost:80/ws";

  create(config: WebSocketConfig): void {
    window.onload = () => {
      this.socket = new WebSocket(this.uri);
      this.socket.onopen = config.onOpen;
      this.socket.onclose = config.onClose;
      this.socket.onmessage = res => config.onMessage(JSON.parse(res.data));
      this.socket.onerror = config.onError;
    };
  }

  send(data: any): void {
    this.socket.send(data);
  }
}

Body:
My solution to this was not quite what the two answers provided, but they pointed me in the right direction.

First of all, I was creating my websocket connection in the AttackComponent, and I would rather create it in my AppComponent so that the connection can be accessed globally (not related to my question).

I created an interval function that checks to see is the socket has connected, and if so then it invokes a function call, which would be a callback function that I pass in from my AttackComponent.

That callback is passed in via an arrow function in the AttackComponent, which gives me the right this context. I then call another method to set the sockets onmessage property to my AttackComponent's method, and I bind it to the proper this context which is allowed by the arrow function. I could also just do the binding outside of that all together.

Here is en example of what I did, that now works and updates my template properly:

WebSocketService:

  setSocketOnMessage(fn: Function): void {
    this.socket.onmessage = function (message) {
      fn(JSON.parse(message.data), message);
    };
  }

  onReady(cb: Function): void {
    let socketInterval = setInterval(() => {
      if (this.isConnected()) {
        cb();

        clearInterval(socketInterval);
      }
    }, 50);
  }

AttackComponent:

  constructor(private webSocketService: WebSocketService) {
    this.webSocketService.onReady(() => {
      this.webSocketService.setSocketOnMessage(this.sOnMessage.bind(this));
    });
  }

  sOnMessage(data: any): void {
    this.hasReceivedMessage = true;
    this.totalRequests = data.total_requests;
    this.payloadSize = data.payload_size;
    this.payloadSizeType = data.payload_size_type;
  }


问:
Check checkbox from antoher activity
I was wondering if anyone could tell me how I could check a checkBox in an  activity from another activity.

I'm making a homework app and I want to put a check next to the questions that have been completed.

So the first activity has a list of questions and next to them are unchecked boxes. When you click a question, the app takes you to the second activity. In the second activity, I want to check the box of the question that was completed.

答:
You should use SharedPreferences for that. call this in the first activity:

```<code>SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.putBoolean("KEY", <your value>).apply();
</code>```

and something similar in another activity:

```<code>    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean isTicked = prefs.getBoolean("KEY", <default boolean value>);
</code>```

where KEY can be anything, for example, your question's number

Title: Check checkbox from antoher activity

Body:
You should use SharedPreferences for that. call this in the first activity:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.putBoolean("KEY", <your value>).apply();

and something similar in another activity:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean isTicked = prefs.getBoolean("KEY", <default boolean value>);

where KEY can be anything, for example, your question's number


问:
Grey Box in Google Play Developer Console
I just submitted an update to Google Play, and now I am seeing an empty grey box next to my app name in the Google Play Developer console. I have submitted countless updates to Google Play, and I have never seen this. In the play store, the icon shows up fine. Does anyone know what this could possibly be? Is this a new feature of Google Play while the app is being distributed, or did I possibly mess something up in my latest release. Thank you in advance.

答: For those wondering, this was a bug with Google. They have since fixed it and the icon has gone back to normal.</p>


问:
PHP and AlertDialog not in sync on Android
I'm currently building a simple login Android app using a tutorial on YouTube that fetches data from a database and lets the user login. However, when I click the login button, regardless of what the input is, it tells me that the login has been successful. Below is the Java code where the data is entered and the PHP code to connect to the database, every time login is clicked the AlertDialog will pop up saying 'Login successful'. I want it to display 'Login not successful' if the data the user enters is incorrect, can somebody show me how? Thanks

```<code>public class BackgroundWorker extends AsyncTask<String, Void, String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx){
        context = ctx;
    }

    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_url = "";
        if (type.equals("Login")) {
            try {
                String userName = params[1];
                String password = params[2];
                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("userName", "UTF-8")+"="+URLEncoder.encode(userName, "utf-8")+"&"
                +URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "utf-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result ="";
                String line ="";
                while ((line = bufferedReader.readLine()) != null){
                    result += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login status: ");
    }

    @Override
    protected void onPostExecute(String result) {
        alertDialog.setMessage(result);
        alertDialog.show();
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}
</code>```

====

```<code><?php
require "conn.php";

$userName = $_POST["userName"];
$password = $_POST["password"];

$mysql_qry = "select * from database where userName like '$userName' and password like '$password';";

$result = mysqli_query($conn, $mysql_qry);

if(mysqli_num_rows($result) > 0) {
    echo "Successful login";
}
else{
    echo "Login not successful";
}
</code>```

答:
In your conn.php file

```<code>$dbname = "";
$username = "";
$password = "";
$server = "";
</code>```

This should not be empty.

Fill it with appropriate data

Body:
I'm currently building a simple login Android app using a tutorial on YouTube that fetches data from a database and lets the user login. However, when I click the login button, regardless of what the input is, it tells me that the login has been successful. Below is the Java code where the data is entered and the PHP code to connect to the database, every time login is clicked the AlertDialog will pop up saying 'Login successful'. I want it to display 'Login not successful' if the data the user enters is incorrect, can somebody show me how? Thanks

public class BackgroundWorker extends AsyncTask<String, Void, String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx){
        context = ctx;
    }

    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_url = "";
        if (type.equals("Login")) {
            try {
                String userName = params[1];
                String password = params[2];
                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("userName", "UTF-8")+"="+URLEncoder.encode(userName, "utf-8")+"&"
                +URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "utf-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result ="";
                String line ="";
                while ((line = bufferedReader.readLine()) != null){
                    result += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login status: ");
    }

    @Override
    protected void onPostExecute(String result) {
        alertDialog.setMessage(result);
        alertDialog.show();
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

====

<?php
require "conn.php";

$userName = $_POST["userName"];
$password = $_POST["password"];

$mysql_qry = "select * from database where userName like '$userName' and password like '$password';";

$result = mysqli_query($conn, $mysql_qry);

if(mysqli_num_rows($result) > 0) {
    echo "Successful login";
}
else{
    echo "Login not successful";
}

Body:
In your conn.php file

$dbname = "";
$username = "";
$password = "";
$server = "";

This should not be empty.

Fill it with appropriate data


问:
ubuntu server pipeline stop process termination when the first exit
The situation is: I have an external application so I don't have the source code and i can't change it. While running, the application writes logs to the stderr. The task is to write a program that check the output of it and separate some part of the output to other file. My solution is to start the app like

```<code>./externalApp 2>&1 | myApp
</code>```

the myApp is a c++ app with the following source:

```<code>using namespace std;

int main ()
{
string str;
ofstream A;
A.open("A.log");

ofstream B;
B.open("B.log");

A << "test start" << endl;

int i = 0;

while (getline(cin,str))
{
    if(str.find("asdasd") != string::npos)
    {
        A << str << endl;
    }
    else
    {
        B << str << endl;
    }
    ++i;
}

A << "test end: " << i << " lines" << endl;
A.close();
B.close();

return 0;
}
</code>```

The externalApp can crash or be terminated. A that moment the myApp gets terminated too and it is don't write the last lines and don't close the files. The file can be 60Gb or larger so saving it and processing it after not a variant.

Correction: My problem is that when the externalApp crash it terminate myApp. That mean any code after while block will never run. So the question is: Is there a way to run myApp even after the externalApp closed?

How can I do this task correctly? I interesed in any other idea to do this task.

答:
There's nothing wrong with the shown code, and nothing in your question offers any evidence of anything being wrong with the shown code. No evidence was shown that your logging application actually received "the last lines" to be written from that external application. Most likely that external application simply failed to write them to standard output or error, before crashing.

The most likely explanation is that your external application checks if its standard output or error is connected to an interactive terminal; if so each line of its log message is followed by an explicit buffer flush. When the external application's standard output is a pipe, no such flushing takes place, so the log messages get buffered up, and are flushed only when the application's internal output buffer is full. This is a fairly common behavior. But because of that, when the external application crashes its last logged lines are lost forever. Because your logger never received them. Your logger can't do anything about log lines it never read.

In your situation, the only available option is to set up and connect a pseudo-tty device to the external application's standard output and error, making it think that's connected to an interactive terminal, while its output is actually captured by your application.

You can't do this from the shell. You need to write some code to set this up. You can start by reading the pty(7) manual page which explains the procedure to follow, at which point you will end up with file descriptors that you can take, and attach to your external application.

Body:
The situation is: I have an external application so I don't have the source code and i can't change it. While running, the application writes logs to the stderr. The task is to write a program that check the output of it and separate some part of the output to other file. My solution is to start the app like

./externalApp 2>&1 | myApp

the myApp is a c++ app with the following source:

using namespace std;

int main ()
{
string str;
ofstream A;
A.open("A.log");

ofstream B;
B.open("B.log");

A << "test start" << endl;

int i = 0;

while (getline(cin,str))
{
    if(str.find("asdasd") != string::npos)
    {
        A << str << endl;
    }
    else
    {
        B << str << endl;
    }
    ++i;
}

A << "test end: " << i << " lines" << endl;
A.close();
B.close();

return 0;
}

The externalApp can crash or be terminated. A that moment the myApp gets terminated too and it is don't write the last lines and don't close the files. The file can be 60Gb or larger so saving it and processing it after not a variant.

Correction: My problem is that when the externalApp crash it terminate myApp. That mean any code after while block will never run. So the question is: Is there a way to run myApp even after the externalApp closed?

How can I do this task correctly? I interesed in any other idea to do this task.


问:
LocalDate in form
I have a question about Spring + Thymeleaf date format.
I have a simple entity with LocalDate date field. I want to get this date from a user in form and save it to MySQL database.
I'm getting such an error:

Failed to convert property value of type java.lang.String to required type java.time.LocalDate for property date; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.time.LocalDate for value 2019-04-30; nested exception is java.time.format.DateTimeParseException: Text 2019-04-30 could not be parsed at index 2

My entity:

```<code>@Entity
@Table(name="game")
public class Game{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Transient
    private User gameOwner;
    private LocalDate date;
    private LocalTime time;

    //other fields
</code>```

Thymeleaf view / form:

```<code><form action="#" th:action="@{/games/addForm}" th:object="${gameForm}" method="post">
    <p>Date: <input type="date" th:field="*{date}" /></p>
</form>
</code>```

What's the reason for this problem? Maybe there is the other, better way to storage date?

答:
Thymeleaf provides an extra module for that: https://github.com/thymeleaf/thymeleaf-extras-java8time

Adding the following dependency (maven) should be enough:

```<code><dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
</code>```

Title: LocalDate in form

Body:
I have a question about Spring + Thymeleaf date format.
I have a simple entity with LocalDate date field. I want to get this date from a user in form and save it to MySQL database.
I'm getting such an error:

Failed to convert property value of type java.lang.String to required type java.time.LocalDate for property date; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.time.LocalDate for value 2019-04-30; nested exception is java.time.format.DateTimeParseException: Text 2019-04-30 could not be parsed at index 2

My entity:

@Entity
@Table(name="game")
public class Game{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Transient
    private User gameOwner;
    private LocalDate date;
    private LocalTime time;

    //other fields

Thymeleaf view / form:

<form action="#" th:action="@{/games/addForm}" th:object="${gameForm}" method="post">

Date: <input type="date" th:field="*{date}" />

</form>

What's the reason for this problem? Maybe there is the other, better way to storage date?

Body:
Thymeleaf provides an extra module for that: https://github.com/thymeleaf/thymeleaf-extras-java8time

Adding the following dependency (maven) should be enough:

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>


问:
SQL-Server - Access Linked Server (Cannot initialize the data source object)
I am currently configuring a linked server connection between Microsoft SQL-Server and a Microsoft Access database in our network. To make things easy, I saved the Access db locally and tried to configure the linked server.

First I created a system-DSN named "BADEN32" (32 bit)
This DSN refers to my Access database (located C:\Users\xxx\Desktop\Baden.accdb)
For this DSN, I used the Microsoft Access Driver (.mdb .accdb)

When I try to create a new linked server, I keep getting the following error: Cannot initialize the data source object of OLE DB provider "MSDASQL" for linked server "BADEN32"
I have already checked the MSDASQL provider if allow inprocess was true, but it was.

What am I doing wrong here?

答:
You're linking to the SQL server from the Access Database?  You would need to set up an ODBC connection to the SQL server and test it. Once it is working, go to the Access Database, External Data Tab, then ODBC Database to set up.

If this isn't what you mean, could I get more information?


问:
angular automatically removes parameters form url
In my application i am passing parameters for controller and read it using javascript as below.

localhost:8080/app/conroller#parameter=value

now problem is if i open my conroller in url and than append #parameter=value than only it works.

but i want to put whole link in anchor tag.

and when i click outside application than it automatically reroute localhost:8080/app/conroller and don't accept parameters.Although when opening that url if i apped #parameter=value* part than it works perfect.

i am using html5mode = true.
i search lots of document but didnt find right solution for this.

答:
Not exactly sure if I get what you are asking but I think this is what you are getting at:

```<code>href="/app/conroller#parameter=value" target="_self"
</code>```

Try adding the target self.

If that doesn't work you could try setting a base url <base href="/"></base>

You could try using ? for the query parameter instead of the #

Body:
Not exactly sure if I get what you are asking but I think this is what you are getting at:

href="/app/conroller#parameter=value" target="_self"

Try adding the target self.

If that doesn't work you could try setting a base url <base href="/"></base>

You could try using ? for the query parameter instead of the #


问:
Identifying encrypted Word docs with perl
I have a series of Word docs that require a password to decode and would like to be able to identify them as having a password among a series of non-encrypted Word docs.

I've followed much of the guidance provided by this stackoverflow link:

How to detect if a Word document is password protected before uploading the file to server?

Here is the code I am currently using:

```<code> sub _is_encrypted_doc {
   my ($data) = @_;

 if (_is_office_doc($data)) {
     if ($data =~ /(?:<encryption xmlns)/i) {
       return 1;
     }
     if (index($data, "\x13") == 523) {
       return 1;
     }
     if (index($data, "\x2f") == 532) {
       return 1;
     }
     if (index($data, "\xfe") == 520) {
       return 1;
     }
     my $tdata = substr $data, 2000;
     $tdata =~ s/\\0/ /g;
     if (index($tdata, "E n c r y p t e d P a c k a g e") > -1) {
       return 1;
     }
   }
 }
</code>```

However, my code doesn't appear to identify all variations we've received. I've uploaded one such file here:

https://www.dropbox.com/s/uk51fixkc12aove/g9kfak164.docx?dl=0

Use "NZlttUtz" to decode. I'm relatively new at this, so I hoped someone could guide me here. Is there more comprehensive code already available to do this?

答:
As far as I can see in the link you reference, generally files beginning with the ÐÏ prefix are protected, & I've not found any unprotected word documents that do begin with that prefix. So unless you need to distinguish between e.g. Excel and Word and which version the documents are (which might be better handled via file ext), you can simply test for files beginning with Ð.

```<code>use Fcntl qw(:seek);

my($fh, $FILE, $byte_position, $byte_value);

$FILE      = "path/to/file";
$byte_position = 0;

open($fh, "<", $FILE)
  || die "can't open $FILE: $!";

binmode($fh)
  || die "can't binmode $FILE";

sysseek($fh, $byte_position, SEEK_CUR)  # NB: 0-based
  || die "couldn't see to byte $byte_position in $FILE: $!";

sysread($fh, $byte_value, 1) == 1
  || die "couldn't read byte from $FILE: $!";

if (ord($byte_value) == 208){
  return 1;
}
else {
  return 0;
}
</code>```

i.e. Read first byte of file to see if it is D0hex (ASCII Ð), if it is return 1 for protected document, otherwise return 0.

Body:
I have a series of Word docs that require a password to decode and would like to be able to identify them as having a password among a series of non-encrypted Word docs.

I've followed much of the guidance provided by this stackoverflow link:

How to detect if a Word document is password protected before uploading the file to server?

Here is the code I am currently using:

 sub _is_encrypted_doc {
   my ($data) = @_;

 if (_is_office_doc($data)) {
     if ($data =~ /(?:<encryption xmlns)/i) {
       return 1;
     }
     if (index($data, "\x13") == 523) {
       return 1;
     }
     if (index($data, "\x2f") == 532) {
       return 1;
     }
     if (index($data, "\xfe") == 520) {
       return 1;
     }
     my $tdata = substr $data, 2000;
     $tdata =~ s/\\0/ /g;
     if (index($tdata, "E n c r y p t e d P a c k a g e") > -1) {
       return 1;
     }
   }
 }

However, my code doesn't appear to identify all variations we've received. I've uploaded one such file here:

https://www.dropbox.com/s/uk51fixkc12aove/g9kfak164.docx?dl=0

Use "NZlttUtz" to decode. I'm relatively new at this, so I hoped someone could guide me here. Is there more comprehensive code already available to do this?

Body:
As far as I can see in the link you reference, generally files beginning with the ÐÏ prefix are protected, & I've not found any unprotected word documents that do begin with that prefix. So unless you need to distinguish between e.g. Excel and Word and which version the documents are (which might be better handled via file ext), you can simply test for files beginning with Ð.

use Fcntl qw(:seek);

my($fh, $FILE, $byte_position, $byte_value);

$FILE      = "path/to/file";
$byte_position = 0;

open($fh, "<", $FILE)
  || die "can't open $FILE: $!";

binmode($fh)
  || die "can't binmode $FILE";

sysseek($fh, $byte_position, SEEK_CUR)  # NB: 0-based
  || die "couldn't see to byte $byte_position in $FILE: $!";

sysread($fh, $byte_value, 1) == 1
  || die "couldn't read byte from $FILE: $!";

if (ord($byte_value) == 208){
  return 1;
}
else {
  return 0;
}

i.e. Read first byte of file to see if it is D0hex (ASCII Ð), if it is return 1 for protected document, otherwise return 0.


问:
Apply UDF dynamically to 1 to N columns from N columns in dataframe
I have a schema and name of columns to apply UDF to. Name of columns are user input and they can differ in numbers for each input.
Is there a way to apply UDFs to N columns in dataframe  ?

Trying to achieve this.
for schema with say col1,col2,col3,col4,col5

```<code>  DataFrame newDF = df.withColumn("col2", callUDF("test", (df.col("col2"))));
  or
  DataFrame newDF = df.withColumn("col2", callUDF("test", (df.col("col2"))))
                 .withColumn("col3", callUDF("test", (df.col("col3"))));
  or
   DataFrame newDF = df.withColumn("col2", callUDF("test", (df.col("col1"))))
                 .withColumn("col3", callUDF("test", (df.col("col3"))))
                 .withColumn("col5", callUDF("test", (df.col("col5"))))
  or for N columns.
</code>```

Any ideas ?

答: I ended up writing code to dynamically generate SPARK SQL query for applying UDFs to 1 to N cols. Then register input dataframe as temp table and use genererated query.</p>

Body:
I have a schema and name of columns to apply UDF to. Name of columns are user input and they can differ in numbers for each input.
Is there a way to apply UDFs to N columns in dataframe  ?

Trying to achieve this.
for schema with say col1,col2,col3,col4,col5

  DataFrame newDF = df.withColumn("col2", callUDF("test", (df.col("col2"))));
  or
  DataFrame newDF = df.withColumn("col2", callUDF("test", (df.col("col2"))))
                 .withColumn("col3", callUDF("test", (df.col("col3"))));
  or
   DataFrame newDF = df.withColumn("col2", callUDF("test", (df.col("col1"))))
                 .withColumn("col3", callUDF("test", (df.col("col3"))))
                 .withColumn("col5", callUDF("test", (df.col("col5"))))
  or for N columns.

Any ideas ?