问:
Tracking fast forward/ rewind in tvos
Apple's tvos AVPlayerViewController allows user to fast forward/rewind by pressing down on the rightmost/leftmost end of the siri remote. Is there any delegate method to track this. I did come across the following method but its only good enough to track drag/drop seeks or seek forwards by 10 seconds. Is there any other way to track fast forwards, short of keeping track of avplayeritems currentTime property?

```<code>- (void)playerViewController:(AVPlayerViewController *)playerViewController
willResumePlaybackAfterUserNavigatedFromTime:(CMTime)oldTime
                      toTime:(CMTime)targetTime
</code>```

答:
As far as I know there is no way to get that information back from AVPlayerViewControllerDelegate.

But due to the fact that AVPlayerViewController, at then, is using an injected instance of AVPlayer internally... you could create your custom subclass of AVPlayer to keep track of that usage.

```<code>class ViewController: AVPlayerViewController {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        play(stream: URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!)
    }

    // MARK: - Private

    private func play(stream: URL) {
        let asset = AVAsset(url: stream)
        let playetItem = AVPlayerItem(asset: asset)
        player = MyPlayer(playerItem: playetItem)
        player?.play()
    }
}

class MyPlayer: AVPlayer {

    override func seek(to time: CMTime, toleranceBefore: CMTime, toleranceAfter: CMTime, completionHandler: @escaping (Bool) -> Void) {
        super.seek(to: time, toleranceBefore: toleranceBefore, toleranceAfter: toleranceAfter, completionHandler: completionHandler)

        print("The user did seek to: \(time)")
    }
}
</code>```

Title: Tracking fast forward/ rewind in tvos

Body:
Apple's tvos AVPlayerViewController allows user to fast forward/rewind by pressing down on the rightmost/leftmost end of the siri remote. Is there any delegate method to track this. I did come across the following method but its only good enough to track drag/drop seeks or seek forwards by 10 seconds. Is there any other way to track fast forwards, short of keeping track of avplayeritems currentTime property?

- (void)playerViewController:(AVPlayerViewController *)playerViewController
willResumePlaybackAfterUserNavigatedFromTime:(CMTime)oldTime
                      toTime:(CMTime)targetTime

Body:
As far as I know there is no way to get that information back from AVPlayerViewControllerDelegate.

But due to the fact that AVPlayerViewController, at then, is using an injected instance of AVPlayer internally... you could create your custom subclass of AVPlayer to keep track of that usage.

class ViewController: AVPlayerViewController {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        play(stream: URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!)
    }

    // MARK: - Private

    private func play(stream: URL) {
        let asset = AVAsset(url: stream)
        let playetItem = AVPlayerItem(asset: asset)
        player = MyPlayer(playerItem: playetItem)
        player?.play()
    }
}

class MyPlayer: AVPlayer {

    override func seek(to time: CMTime, toleranceBefore: CMTime, toleranceAfter: CMTime, completionHandler: @escaping (Bool) -> Void) {
        super.seek(to: time, toleranceBefore: toleranceBefore, toleranceAfter: toleranceAfter, completionHandler: completionHandler)

        print("The user did seek to: \(time)")
    }
}


来源: stackexchange

问:
Visual Studio 2017, JavaScript intellisense inconsistencies
TL;DR: How do you include a tsconfig.json file in Visual Studio 2017 and still have JavaScript intellisense work like it does by default, giving code hints both for your own code and 3rd-party libraries? Is it borked, or do I just need a better understanding of how it works?

Much like jQuery, I would like ubiquitous access to my own JavaScript namespaces across JavaScript and html files with intellisense. How does one achieve this?

EDIT 3:

I reported this issue on developercommunity.visualstudio.com. Please consider up-voting the issue to attract more attention from Microsoft.

EDIT 2:

Currently the "solution" is Resharper, which provides what one would expect straight out-of-the-box. But it's not really ideal at a price of $299/yr/user for something Visual Studio markets it provides itself.

EDIT 1:

In the event that my expectations for JavaScript intellisense in Visual Studio is inaccurate, below is a contrived example of how I expect it to function.

Say I create three TypeScript files in my ./Scripts folder, we'll call them A.ts, B.ts, and C.ts. Each will contain its own namespace:

A.ts

```<code>namespace A {
    export function f1(s: string) {
        return s;
    }
}
</code>```

B.ts

```<code>namespace B {
    export function f1(n: number) {
        return n;
    }
}
</code>```

C.ts

```<code>namespace C {
    export function f1(b: boolean) {
        return b;
    }
}
</code>```

At this point in time one may expect to be able to start seeing intellisense for their newly created namespaces, and indeed, within A.ts, B.ts, and C.ts you begin to see intellisense for those namespaces. Cool.

Unfortunately this doesn't carry over to other places, like /Home/Index.cshtml. Index.cshtml knows nothing about the A, B, or C namespaces. Additionally, .js files know nothing about these namespaces, hence the need for their respective TypeScript Declaration (.d.ts) files.

So we'll go ahead and add our tsconfig.json file to the root of our project and configure it like we do above. If we perform an edit on one of our .ts files and save it, this triggers the compilation of our corresponding .d.ts files into our ./Scripts/out folder. Do we now get intellisense in Index.cshtml and .js files? ...No.

Now you might be thinking these files need to be included in the project in order for Visual Studio to pick them up for intellisense (they're excluded on creation). So you include them in the project. Intellisense? No. jQuery intellisense? No. Perhaps they need to be in the same directory as the file you want to use them in? .....Kind of? I've ran into intellisense being inconsistent like this on a number of occassions:

Somehow we're getting intellisense for our 'A' namespace within our C3.js (note: a JavaScript file), but none of the other ones. What?

Perhaps you think you're on the right track and that you've scored a small victory against the intellisense engine. But then you restart your Visual Studio instance and...

Wait....I just had intellisense for the 'A' namespace. What happened!?

I have no idea. But after messing around for a bit I try placing an import statement at the top of the .js file, and all of a sudden intellisense starts kicking in for the imported files/modules. Huzzah!

And even in Index.cshtml I begin receiving intellisense for our imported namespaces.

The moment I close the .js file with the import statements, though, all of a sudden I lose the intellisense for them in Index.cshtml. Wait...what?? And unlike in JavaScript files, I'm unable to write an import statement to receive intellisense for them:

Or at least... not with my own namespaces:

It's this inconsistent back-and-forth that confuses the heck out of me as to how exactly Visual Studio's JavaScript intellisense actually works. I still don't know if it's just broken or if I need a better understanding of it.

ORIGINAL POST

System

Windows 10
VS2017 15.0.0+26228.10
New JavaScript language service is enabled

I've been fighting to get Visual Studio 2017's JavaScript intellisense to work for me for a couple of days now to no avail. I don't know if something's genuinely wonky with the IDE or if I just don't understand it properly.

My understanding of how VS2017's JS intellisense works is now by typescript definition files, or .d.ts files. Ultimately I would like to get intellisense to help us out with our own TypeScript/JavaScript but right now I'd settle for just having it work consistently within a fresh project.

If I create a new ASP.NET MVC 4.5.2 project, out-of-the-box JS intellisense seems to work fine, and by that I mean I can type a dollar sign ($) either in a .js file or between <script> tags and I properly receive intellisense for jQuery. Awesome. Now, with the ultimate goal in mind of creating TypeScript files (.ts) and having the TypeScript compiler generate our .d.ts files automagically so that we can get rich intellisense for our own code, I wish to introduce a tsconfig.json file to the root of the project in order to configure that.

After creating the tsconfig.json file JS intellisense ceases to function. I type a dollar sign ($) into either a .js file or between <script> tags and I get zero intellisense for jQuery. This was a frustrating experience for a while but then I read this little note found on the linked page above:

NOTE: This feature is disabled by default if using a tsconfig.json
configuration file, but may be set to enabled as outlined further
below).

"This feature" is in reference to "By default, the Salsa language service will try to detect which JavaScript libraries are in use...in order to provide richer IntelliSense." Ok, so the Salsa language service will not autodetect libraries in use and provide intellisense for them when a tsconfig.json file is present, unless you specifically configure it to do so as "outlined below." At least, that's how I understand it.

If we scroll down the page a little bit and come to the tsconfig file settings we come across a setting for enableAutoDiscovery which "enables the automatic detection and download of definition files as outlined above." It's not super explicit as to what "as outlined above" is in reference to, but I can only assume it's in reference to the previous note indicative of re-enabling Salsa's auto-detection feature to provide rich intellisense. So I include that option in my tsconfig.json file and...no benefit; still no JS intellisense.

As it turns out, typingOptions.enableAutoDiscovery has been renamed to typeAcquisition.enable. Grrrrr. Alright, so we make that change in our tsconfig.json aaaaaaand... still no JS intellisense.

At this point I am able to write my own .d.ts files and Visual Studio's intellisense will pick it up alright (most of the time...), but I still have no intellisense for 3rd-party libraries like jQuery, which is no good.

So far I've landed on the following tsconfig.json file:

```<code>{
  "compilerOptions": {
    "noEmitOnError": true,
    "noImplicitAny": false,
    "removeComments": false,
    "target": "es5",
    "declaration": true,
    "declarationDir": "./Scripts/out"
  },
  "compileOnSave": true,
  "typeAcquisition": {
    "enable": true,
    "include": ["jquery"]
  },
  "include": [
    "./Scripts/app/**/*"
  ],
  "exclude": [
    "./Scripts/vendors/**/*",
    "./Scripts/out/**/*"
  ]
}
</code>```

With the TypeScript virtual project in view I can see that my project's .ts files are included as well as jQuery in my %LOCALAPPDATA%\Microsoft\TypeScript\node_modules@types directory.

I was hopeful that with all this in place I would have both intellisense for my own project's .ts files and 3rd-party libraries (at least those specifically included; jQuery only at this point). Alas...no. Still no jQuery intellisense.

Incidentally, if I write an import line for jQuery, all of a sudden I get jQuery intellisense

...interesting. And maybe that makes perfect sense; I haven't messed a whole lot with module imports and how Visual Studio's intellisense handles those, but what I really want is to have intellisense application-wide for both our code and 3rd-party libraries.

答:
It looks like the latest update March 14, 2017 (build 26228.09) caused this issue, you can go to Control Panel—Programs and Features-View Installed updates and remove this update, then reopen VS to check the intellisense. If it works, which means this update lead to this issue, you can temporarily not install this updat

I've noticed the Microsoft Report Projects for Visual Studio Extension can cause problems such as this when being used in a project, A couple of mine have broken right after I add my SQL Server Report project to the solution and restarted visual studio..  So for now I remove my Report project from the solution but I hope Microsoft fixes this issue

ContentLicense: CC BY-SA 3.0

Body:
TL;DR: How do you include a tsconfig.json file in Visual Studio 2017 and still have JavaScript intellisense work like it does by default, giving code hints both for your own code and 3rd-party libraries? Is it borked, or do I just need a better understanding of how it works?

Much like jQuery, I would like ubiquitous access to my own JavaScript namespaces across JavaScript and html files with intellisense. How does one achieve this?

EDIT 3:

I reported this issue on developercommunity.visualstudio.com. Please consider up-voting the issue to attract more attention from Microsoft.

EDIT 2:

Currently the "solution" is Resharper, which provides what one would expect straight out-of-the-box. But it's not really ideal at a price of $299/yr/user for something Visual Studio markets it provides itself.

EDIT 1:

In the event that my expectations for JavaScript intellisense in Visual Studio is inaccurate, below is a contrived example of how I expect it to function.

Say I create three TypeScript files in my ./Scripts folder, we'll call them A.ts, B.ts, and C.ts. Each will contain its own namespace:

A.ts

namespace A {
    export function f1(s: string) {
        return s;
    }
}

B.ts

namespace B {
    export function f1(n: number) {
        return n;
    }
}

C.ts

namespace C {
    export function f1(b: boolean) {
        return b;
    }
}

At this point in time one may expect to be able to start seeing intellisense for their newly created namespaces, and indeed, within A.ts, B.ts, and C.ts you begin to see intellisense for those namespaces. Cool.

Unfortunately this doesn't carry over to other places, like /Home/Index.cshtml. Index.cshtml knows nothing about the A, B, or C namespaces. Additionally, .js files know nothing about these namespaces, hence the need for their respective TypeScript Declaration (.d.ts) files.

So we'll go ahead and add our tsconfig.json file to the root of our project and configure it like we do above. If we perform an edit on one of our .ts files and save it, this triggers the compilation of our corresponding .d.ts files into our ./Scripts/out folder. Do we now get intellisense in Index.cshtml and .js files? ...No.

Now you might be thinking these files need to be included in the project in order for Visual Studio to pick them up for intellisense (they're excluded on creation). So you include them in the project. Intellisense? No. jQuery intellisense? No. Perhaps they need to be in the same directory as the file you want to use them in? .....Kind of? I've ran into intellisense being inconsistent like this on a number of occassions:

Somehow we're getting intellisense for our 'A' namespace within our C3.js (note: a JavaScript file), but none of the other ones. What?

Perhaps you think you're on the right track and that you've scored a small victory against the intellisense engine. But then you restart your Visual Studio instance and...

Wait....I just had intellisense for the 'A' namespace. What happened!?

I have no idea. But after messing around for a bit I try placing an import statement at the top of the .js file, and all of a sudden intellisense starts kicking in for the imported files/modules. Huzzah!

And even in Index.cshtml I begin receiving intellisense for our imported namespaces.

The moment I close the .js file with the import statements, though, all of a sudden I lose the intellisense for them in Index.cshtml. Wait...what?? And unlike in JavaScript files, I'm unable to write an import statement to receive intellisense for them:

Or at least... not with my own namespaces:

It's this inconsistent back-and-forth that confuses the heck out of me as to how exactly Visual Studio's JavaScript intellisense actually works. I still don't know if it's just broken or if I need a better understanding of it.

ORIGINAL POST

System

Windows 10
VS2017 15.0.0+26228.10
New JavaScript language service is enabled

I've been fighting to get Visual Studio 2017's JavaScript intellisense to work for me for a couple of days now to no avail. I don't know if something's genuinely wonky with the IDE or if I just don't understand it properly.

My understanding of how VS2017's JS intellisense works is now by typescript definition files, or .d.ts files. Ultimately I would like to get intellisense to help us out with our own TypeScript/JavaScript but right now I'd settle for just having it work consistently within a fresh project.

If I create a new ASP.NET MVC 4.5.2 project, out-of-the-box JS intellisense seems to work fine, and by that I mean I can type a dollar sign ($) either in a .js file or between <script> tags and I properly receive intellisense for jQuery. Awesome. Now, with the ultimate goal in mind of creating TypeScript files (.ts) and having the TypeScript compiler generate our .d.ts files automagically so that we can get rich intellisense for our own code, I wish to introduce a tsconfig.json file to the root of the project in order to configure that.

After creating the tsconfig.json file JS intellisense ceases to function. I type a dollar sign ($) into either a .js file or between <script> tags and I get zero intellisense for jQuery. This was a frustrating experience for a while but then I read this little note found on the linked page above:

NOTE: This feature is disabled by default if using a tsconfig.json
configuration file, but may be set to enabled as outlined further
below).

"This feature" is in reference to "By default, the Salsa language service will try to detect which JavaScript libraries are in use...in order to provide richer IntelliSense." Ok, so the Salsa language service will not autodetect libraries in use and provide intellisense for them when a tsconfig.json file is present, unless you specifically configure it to do so as "outlined below." At least, that's how I understand it.

If we scroll down the page a little bit and come to the tsconfig file settings we come across a setting for enableAutoDiscovery which "enables the automatic detection and download of definition files as outlined above." It's not super explicit as to what "as outlined above" is in reference to, but I can only assume it's in reference to the previous note indicative of re-enabling Salsa's auto-detection feature to provide rich intellisense. So I include that option in my tsconfig.json file and...no benefit; still no JS intellisense.

As it turns out, typingOptions.enableAutoDiscovery has been renamed to typeAcquisition.enable. Grrrrr. Alright, so we make that change in our tsconfig.json aaaaaaand... still no JS intellisense.

At this point I am able to write my own .d.ts files and Visual Studio's intellisense will pick it up alright (most of the time...), but I still have no intellisense for 3rd-party libraries like jQuery, which is no good.

So far I've landed on the following tsconfig.json file:

{
  "compilerOptions": {
    "noEmitOnError": true,
    "noImplicitAny": false,
    "removeComments": false,
    "target": "es5",
    "declaration": true,
    "declarationDir": "./Scripts/out"
  },
  "compileOnSave": true,
  "typeAcquisition": {
    "enable": true,
    "include": ["jquery"]
  },
  "include": [
    "./Scripts/app/**/*"
  ],
  "exclude": [
    "./Scripts/vendors/**/*",
    "./Scripts/out/**/*"
  ]
}

With the TypeScript virtual project in view I can see that my project's .ts files are included as well as jQuery in my %LOCALAPPDATA%\Microsoft\TypeScript\node_modules@types directory.

I was hopeful that with all this in place I would have both intellisense for my own project's .ts files and 3rd-party libraries (at least those specifically included; jQuery only at this point). Alas...no. Still no jQuery intellisense.

Incidentally, if I write an import line for jQuery, all of a sudden I get jQuery intellisense

...interesting. And maybe that makes perfect sense; I haven't messed a whole lot with module imports and how Visual Studio's intellisense handles those, but what I really want is to have intellisense application-wide for both our code and 3rd-party libraries.


问:
How can I set max-length in an HTML5 "input type=number" element?
For <input type="number"> element, maxlength is not working. How can I restrict the maxlength for that number element?

答:
Another option is to just add a listener for anything with the maxlength attribute and add the slice value to that.  Assuming the user doesn't want to use a function inside every event related to the input.  Here's a code snippet. Ignore the CSS and HTML code, the JavaScript is what matters.

// Reusable Function to Enforce MaxLength
function enforce_maxlength(event) {
  var t = event.target;
  if (t.hasAttribute('maxlength')) {
    t.value = t.value.slice(0, t.getAttribute('maxlength'));
  }
}

// Global Listener for anything with an maxlength attribute.
// I put the listener on the body, put it on whatever.
document.body.addEventListener('input', enforce_maxlength);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label { margin: 10px; font-size: 16px; display: block }
input { margin: 0 10px 10px; padding: 5px; font-size: 24px; width: 100px }
span { margin: 0 10px 10px; display: block; font-size: 12px; color: #666 }</code>```

Text Input
<input id="test_input" type="text" maxlength="5"/>
set to 5 maxlength

Number Input
<input id="test_input" type="number" min="0" max="99" maxlength="2"/>
set to 2 maxlength, min 0 and max 99```

ContentLicense: CC BY-SA 4.0

Body:
Another option is to just add a listener for anything with the maxlength attribute and add the slice value to that.  Assuming the user doesn't want to use a function inside every event related to the input.  Here's a code snippet. Ignore the CSS and HTML code, the JavaScript is what matters.

// Reusable Function to Enforce MaxLength
function enforce_maxlength(event) {
  var t = event.target;
  if (t.hasAttribute('maxlength')) {
    t.value = t.value.slice(0, t.getAttribute('maxlength'));
  }
}

// Global Listener for anything with an maxlength attribute.
// I put the listener on the body, put it on whatever.
document.body.addEventListener('input', enforce_maxlength);

label { margin: 10px; font-size: 16px; display: block }
input { margin: 0 10px 10px; padding: 5px; font-size: 24px; width: 100px }
span { margin: 0 10px 10px; display: block; font-size: 12px; color: #666 }

<label for="test_input">Text Input</label>
<input id="test_input" type="text" maxlength="5"/>
<span>set to 5 maxlength</span>

<br>

<label for="test_input">Number Input</label>
<input id="test_input" type="number" min="0" max="99" maxlength="2"/>
<span>set to 2 maxlength, min 0 and max 99</span>


问:
Insert data from multiple files into multiple tables
I have data stored in CSV files in multiple folders that I want to load into multiple SQL tables using MySQL on an Ubuntu system. Each table and file follows this schema (the files don't have the id field):

```<code>+ ------ + -------- + -------- + --------- + ---------- +
| SPO_Id | SPO_Name | SPO_Date | SPO_Price | SPO_Amount |
+ ------ + -------- + -------- + --------- + ---------- +
</code>```

Each file contains pricing and sales data for a single day. Unfortunately, the files are not named after their date; they are stored in folders that are named after the date. Here's an example diagram of what the directory looks like

```<code>      ------> 20170102 ------> prices.csv
     /
    /
Exmpl ------> 20170213 ------> prices.csv
    \
     \
      ------> 20170308 ------> prices.csv
</code>```

Here is a query I've written that pulls data from a file and stores it into a table:

```<code>use pricing ; # the database I want the tables in
drop table if exists SP_2017_01_02 ;

create table SP_2017_01_02 (
    SPO_Id int not null primary key auto_increment,
    SPO_Name varchar(32),
    SPO_Date date,
    SPO_Price float,
    SPO_Amount int
);

load data local infile '/Exmpl/20170102/prices.csv'
    into table SP_2017_01_02
    fields terminated by ','
    lines terminated by '\n'
    ignore 1 lines # First line contains field name information
    (SPO_Name, SPO_Date, SPO_Price, SPO_Amount) ;

select * from SP_2017_01_02 ;

show tables ;
</code>```

This query works fine for loading one table in at a time; however, because I have hundreds of tables, I need to automate this process. I've looked around on SO and here are a few things I've found:

Here is a question similar to mine, only this question references SQL Server. The answer gives a suggestion of what to do without any real substance.

This question is also very similar to mine, only this is specifically using SSIS, to which I don't have access (and the question is left unanswered)

This post suggests using control file reference, but this is for sql-loader and oracle.

Using python may be the way to go, but I've never used it before and my question seems like too complicated a problem with which to start.

This one and this one also use python, but they're just updating one table with data from one file.

I've worked a lot in SQL Server, but I'm fairly new to MySQL. Any help is greatly appreciated!

Update

I have attempted to do this using Dynamic SQL in MySQL. Unfortunately, MySQL requires the use of stored procedures to do Dynamic SQL, but it doesn't allow the function load data in a stored procedure. As @RandomSeed pointed out, this cannot be done with only MySQL. I'm going to take his advice and attempt to write a shell/python script to handle this.

I'll leave this question open until I (or someone else) can come up with a solid answer.

答:
So once you have a sql query/function/script that reads a single table, which it looks like you do (or can build an equivalent one in python somewhat simply), using python to loop through the directory structure and get filenames is fairly simple. If you can somehow pass the infile '/Exmpl/20170102/prices.csv' a new csv parameter each time and call your sql script from within python, you should be good.

I don't have much time right now, but I wanted to show you how you could get those filename strings using python.

```<code>import os

prices_csvs = []
for root, dirs, files in os.walk(os.path.join('insert_path_here', 'Exmpl'):
    for f in files:
        if f == 'prices.csv':
            prices_csvs.append(os.path.join(root, f))
            break # optional, use if there only is one prices.csv in each subfolder

for csv_file in prices_csvs:
    # csv_file is a string of the path for each prices.csv
    # if you can insert it as the `infile` parameter and run the sql, you are done
    # admittedly, i don't know how to do this at the moment
</code>```

os.walk goes down through each subdirectory, giving the name root to the path to that folder, listing all the directories as dirs and files as files stored there. From there it's a simple check to see if the filename matches what you're looking for, and storing it in a list if it does. Looping over the list yields strings containing the path to each prices.csv in Exmpl.

Hope that shed a very little light on how python could help

Body:
I have data stored in CSV files in multiple folders that I want to load into multiple SQL tables using MySQL on an Ubuntu system. Each table and file follows this schema (the files don't have the id field):

+ ------ + -------- + -------- + --------- + ---------- +
| SPO_Id | SPO_Name | SPO_Date | SPO_Price | SPO_Amount |
+ ------ + -------- + -------- + --------- + ---------- +

Each file contains pricing and sales data for a single day. Unfortunately, the files are not named after their date; they are stored in folders that are named after the date. Here's an example diagram of what the directory looks like

      ------> 20170102 ------> prices.csv
     /
    /
Exmpl ------> 20170213 ------> prices.csv
    \
     \
      ------> 20170308 ------> prices.csv

Here is a query I've written that pulls data from a file and stores it into a table:

use pricing ; # the database I want the tables in
drop table if exists SP_2017_01_02 ;

create table SP_2017_01_02 (
    SPO_Id int not null primary key auto_increment,
    SPO_Name varchar(32),
    SPO_Date date,
    SPO_Price float,
    SPO_Amount int
);

load data local infile '/Exmpl/20170102/prices.csv'
    into table SP_2017_01_02
    fields terminated by ','
    lines terminated by '\n'
    ignore 1 lines # First line contains field name information
    (SPO_Name, SPO_Date, SPO_Price, SPO_Amount) ;

select * from SP_2017_01_02 ;

show tables ;

This query works fine for loading one table in at a time; however, because I have hundreds of tables, I need to automate this process. I've looked around on SO and here are a few things I've found:

Here is a question similar to mine, only this question references SQL Server. The answer gives a suggestion of what to do without any real substance.

This question is also very similar to mine, only this is specifically using SSIS, to which I don't have access (and the question is left unanswered)

This post suggests using control file reference, but this is for sql-loader and oracle.

Using python may be the way to go, but I've never used it before and my question seems like too complicated a problem with which to start.

This one and this one also use python, but they're just updating one table with data from one file.

I've worked a lot in SQL Server, but I'm fairly new to MySQL. Any help is greatly appreciated!

Update

I have attempted to do this using Dynamic SQL in MySQL. Unfortunately, MySQL requires the use of stored procedures to do Dynamic SQL, but it doesn't allow the function load data in a stored procedure. As @RandomSeed pointed out, this cannot be done with only MySQL. I'm going to take his advice and attempt to write a shell/python script to handle this.

I'll leave this question open until I (or someone else) can come up with a solid answer.

Body:
So once you have a sql query/function/script that reads a single table, which it looks like you do (or can build an equivalent one in python somewhat simply), using python to loop through the directory structure and get filenames is fairly simple. If you can somehow pass the infile '/Exmpl/20170102/prices.csv' a new csv parameter each time and call your sql script from within python, you should be good.

I don't have much time right now, but I wanted to show you how you could get those filename strings using python.

import os

prices_csvs = []
for root, dirs, files in os.walk(os.path.join('insert_path_here', 'Exmpl'):
    for f in files:
        if f == 'prices.csv':
            prices_csvs.append(os.path.join(root, f))
            break # optional, use if there only is one prices.csv in each subfolder

for csv_file in prices_csvs:
    # csv_file is a string of the path for each prices.csv
    # if you can insert it as the `infile` parameter and run the sql, you are done
    # admittedly, i don't know how to do this at the moment

os.walk goes down through each subdirectory, giving the name root to the path to that folder, listing all the directories as dirs and files as files stored there. From there it's a simple check to see if the filename matches what you're looking for, and storing it in a list if it does. Looping over the list yields strings containing the path to each prices.csv in Exmpl.

Hope that shed a very little light on how python could help


问:
JAXBException: class java.util.ArrayList nor any of its super class is known to this context
I am new with Spring integration and while working for my project requirement. I am facing the below issue to marshall Pojo(java object) to the SOAP response(Using Spring integration ws): Please find the below details for the same:

I have the sample xsd file as below:

```<code>  </xsd:element>
    <xsd:element name="MyUserResponses">
    <xsd:complexType>
      <xsd:sequence>
         <xsd:element minOccurs="0" maxOccurs="unbounded" name="MyUserResponse"
       type="tns:MyUserResponse" />
      </xsd:sequence>
    </xsd:complexType>
    </xsd:element>

  <xsd:complexType name="MyUserResponse">
   <xsd:sequence>
        <xsd:element minOccurs="0" maxOccurs="1" name="SomeNumber" type="xsd:string"/>
        <xsd:element minOccurs="0" maxOccurs="1" name="ReferenceID" type="xsd:string" />
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>
</code>```

I have created the below java object files using xjc compiler:

```<code>package com.myuser.echannel;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * <p>Java class for anonymous complex type.
 *
 * <p>The following schema fragment specifies the expected content contained within this class.
 *
 * ```
 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="SomeNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="ReferenceID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * ```
 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "someNumber",
    "referenceID"
})
@XmlRootElement(name = "MyUserRequest")
public class MyUserRequest {

    @XmlElement(name = "SomeNumber")
    protected String someNumber;
    @XmlElement(name = "ReferenceID")
    protected String referenceID;

    /**
     * Gets the value of the someNumber property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSomeNumber() {
        return someNumber;
    }

    /**
     * Sets the value of the someNumber property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSomeNumber(String value) {
        this.someNumber = value;
    }

    /**
     * Gets the value of the referenceID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getReferenceID() {
        return referenceID;
    }

    /**
     * Sets the value of the referenceID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setReferenceID(String value) {
        this.referenceID = value;
    }

}
</code>```

Another Java object:

```<code>package com.myuser.echannel;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 * <p>Java class for MyUserResponse complex type.
 *
 * <p>The following schema fragment specifies the expected content contained within this class.
 *
 * ```
 * <complexType name="MyUserResponse">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="SomeNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="ReferenceID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * ```
 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MyUserResponse", propOrder = {
    "someNumber",
    "referenceID"
})
public class MyUserResponse {

    @XmlElement(name = "SomeNumber")
    protected String someNumber;
    @XmlElement(name = "ReferenceID")
    protected String referenceID;

    /**
     * Gets the value of the someNumber property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSomeNumber() {
        return someNumber;
    }

    /**
     * Sets the value of the someNumber property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSomeNumber(String value) {
        this.someNumber = value;
    }

    /**
     * Gets the value of the referenceID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getReferenceID() {
        return referenceID;
    }

    /**
     * Sets the value of the referenceID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setReferenceID(String value) {
        this.referenceID = value;
    }

}
</code>```

MyUserResponses.java file as below:

```<code>package com.myuser.echannel;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * <p>Java class for anonymous complex type.
 *
 * <p>The following schema fragment specifies the expected content contained within this class.
 *
 * ```
 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="MyUserResponse" type="{http://tempuri.org/}MyUserResponse" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * ```
 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "myUserResponse"
})
@XmlRootElement(name = "MyUserResponses")
public class MyUserResponses {

    @XmlElement(name = "MyUserResponse")
    protected List<MyUserResponse> myUserResponse;

    /**
     * Gets the value of the myUserResponse property.
     *
     * <p>
     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a <CODE>set</CODE> method for the myUserResponse property.
     *
     * <p>
     * For example, to add a new item, do as follows:
     * ```
     *    getMyUserResponse().add(newItem);
     * ```
     *
     *
     * <p>
     * Objects of the following type(s) are allowed in the list
     * {@link MyUserResponse }
     *
     *
     */
    public List<MyUserResponse> getMyUserResponse() {
        if (myUserResponse == null) {
            myUserResponse = new ArrayList<MyUserResponse>();
        }
        return this.myUserResponse;
    }

}
</code>```

Object Factory:

```<code>package com.myuser.echannel;

import javax.xml.bind.annotation.XmlRegistry;

/**
 * This object contains factory methods for each
 * Java content interface and Java element interface
 * generated in the com.myuser.echannel package.
 * <p>An ObjectFactory allows you to programatically
 * construct new instances of the Java representation
 * for XML content. The Java representation of XML
 * content can consist of schema derived interfaces
 * and classes representing the binding of schema
 * type definitions, element declarations and model
 * groups.  Factory methods for each of these are
 * provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.myuser.echannel
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link MyUserResponses }
     *
     */
    public MyUserResponses createMyUserResponses() {
        return new MyUserResponses();
    }

    /**
     * Create an instance of {@link MyUserResponse }
     *
     */
    public MyUserResponse createMyUserResponse() {
        return new MyUserResponse();
    }

    /**
     * Create an instance of {@link MyUserRequest }
     *
     */
    public MyUserRequest createMyUserRequest() {
        return new MyUserRequest();
    }

}
</code>```

package-info.java file:

```<code>@javax.xml.bind.annotation.XmlSchema(namespace = "http://tempuri.org/", elementFormDefault =     javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.myuser.echannel;
</code>```

I am handling the SOAP request with the request body as below to my spring integration layer(which is the below web.xml and spring context files):

web.xml:

```<code><servlet>
        <servlet-name>spring-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/spring-ws-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-ws</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</code>```

spring-ws-config.xml file:

```<code><context:component-scan base-package="com.nbad.eChannel"/>

    <import resource="classpath:/WEB-INF/inbound-gateway-config.xml"/>

    <!-- Ensures that all incoming requests will be routed to the ws:inbound-gateway -->
    <!-- <bean class="org.springframework.ws.server.endpoint.mapping.UriEndpointMapping">
        <property name="defaultEndpoint" ref="ws-inbound-gateway"/>
    </bean> -->

    <bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
     <property name="mappings">
     <props>

     <prop key="{http://tempuri.org/}MyUserRequest">ws-myuser-gateway</prop>
     </props>
     </property>
    </bean>

</beans>

<context:component-scan base-package="com.mypackage"/>

<import resource="classpath:/com/mypackage/si/jdbc/config/spring-integration-context.xml"/>

    <int:channel id="FFUserRequestChannel"/>

    <int-ws:inbound-gateway id="ws-ffuser-gateway" request-channel="FFUserRequestChannel" marshaller="marshaller" unmarshaller="marshaller"/>

    <bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="contextPath" value="com.mypackage.model" />
    </bean>

    <int:service-activator input-channel="MyUserRequestChannel">
    <bean class="com.mypackage.serviceImpl.MyUserImpl">
    <constructor-arg ref = "MyUserRequest"></constructor-arg>
    </bean>
    </int:service-activator>

    <bean id="MyUserRequest" class="com.mypackage.model.MyUserRequest"></bean>
    <bean id="MyUserResponse" class="com.mypackage.model.MyUserResponse"></bean>

</beans>
</code>```

as above, I am using the Jaxb2Marshaller for marshalling and unmarshalling purpose. Now serviceImpl file is as below:

```<code>package com.mypackage.serviceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

import com.mypackage.model.*;
import com.mypackage.service.MyUser;
import com.mypackage.si.jdbc.service.MyUserJdbc;
/**
 * @author Vinay Agrawal
 */
public class MyUserImpl implements MyUser{

    @Autowired
    MyUserRequest request;
    @Autowired
    MyUserJdbc MyUserJdbc;
    public MyUserImpl() {
    }

    public MyUserImpl(MyUserRequest request) {
        super();
        this.request = request;
    }

    @Override
    @PayloadRoot(localPart = "issueResponseFor" , namespace = "http://tempuri.org/")
    @ResponsePayload
    public List<MyUserResponse>issueResponseFor(@RequestPayload MyUserRequest request) {
        List<MyUserResponse> MyUserResponse = new ArrayList<MyUserResponse>();

        MyUserResponse = (List<MyUserResponse>)MyUserJdbc.getMyUserResponse(request);

        return MyUserResponse;
        }
}
</code>```

Here I am calling DB layer and getting List of the MyUserResponse(multiple records) from DB and using spring integration marshaller Jaxb2Marshaller, I am expecting this will marshall the java object into soap response and should display this list in the SOAPUI for MyUserResponse list. but I am getting the below error on SOAP UI and from Junit:

```<code><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <SOAP-ENV:Body>
      <SOAP-ENV:Fault>
         <faultcode>SOAP-ENV:Server</faultcode>
         <faultstring xml:lang="en">Unknown JAXB exception; nested exception is javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.</faultstring>
      </SOAP-ENV:Fault>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

error generated from Junit:

org.springframework.ws.soap.client.SoapFaultClientException: Unknown JAXB exception; nested exception is javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.
    at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:37)
    at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:776)
    at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:602)
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:539)
    at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:494)
    at org.springframework.ws.client.core.WebServiceTemplate.sendSourceAndReceiveToResult(WebServiceTemplate.java:438)
    at org.springframework.ws.client.core.WebServiceTemplate.sendSourceAndReceiveToResult(WebServiceTemplate.java:423)
    at com.nbad.eChannel.Common.InContainerTests.testWebServiceRequestAndResponse(InContainerTests.java:44)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

My SOAP request is as below:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>

     <sch:MyUserRequest>
        <sch:SomeNumber>8009618916</sch:SomeNumber>
        <sch:ReferenceID>ReferenceIDReferenceID</sch:ReferenceID>
     </sch:MyUserRequest>

</soapenv:Body>
</soapenv:Envelope>
</code>```

Again I receive the proper response(one record) if I do changes in the xsd file for getting the single record and corresponding changes in java object file created but face issue when try to get multiple record response.

Please help me to find where I am doing mistake or missing something.

答:
I have got similar issue, I had generated the stubs using CXF. I got similar error and on analysis I have found that the list I'm creating had some null values which caused it. I have replaced null values with empty string. My code is as below using Java 8. If I enable the commented line of code I get  java.util.ArrayList nor any of its super class is known to this context  exception.

Hope this will help someone.

```<code>    model.keySet().forEach( val ->{
                TestRequest.Param param = new Param();
                param.setKey(val);
                param.setValue(model.get(val) != null ?model.get(val).toString():""); //works fine
                    //below line has caused the issue
                    //param.setValue(model.get(val));
                request.getParam().add(param);// this is the list on my request
            });
</code>```

Body:
I am new with Spring integration and while working for my project requirement. I am facing the below issue to marshall Pojo(java object) to the SOAP response(Using Spring integration ws): Please find the below details for the same:

I have the sample xsd file as below:

  </xsd:element>
    <xsd:element name="MyUserResponses">
    <xsd:complexType>
      <xsd:sequence>
         <xsd:element minOccurs="0" maxOccurs="unbounded" name="MyUserResponse"
       type="tns:MyUserResponse" />
      </xsd:sequence>
    </xsd:complexType>
    </xsd:element>

  <xsd:complexType name="MyUserResponse">
   <xsd:sequence>
        <xsd:element minOccurs="0" maxOccurs="1" name="SomeNumber" type="xsd:string"/>
        <xsd:element minOccurs="0" maxOccurs="1" name="ReferenceID" type="xsd:string" />
    </xsd:sequence>
  </xsd:complexType>
</xsd:schema>

I have created the below java object files using xjc compiler:

package com.myuser.echannel;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="SomeNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="ReferenceID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "someNumber",
    "referenceID"
})
@XmlRootElement(name = "MyUserRequest")
public class MyUserRequest {

    @XmlElement(name = "SomeNumber")
    protected String someNumber;
    @XmlElement(name = "ReferenceID")
    protected String referenceID;

    /**
     * Gets the value of the someNumber property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSomeNumber() {
        return someNumber;
    }

    /**
     * Sets the value of the someNumber property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSomeNumber(String value) {
        this.someNumber = value;
    }

    /**
     * Gets the value of the referenceID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getReferenceID() {
        return referenceID;
    }

    /**
     * Sets the value of the referenceID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setReferenceID(String value) {
        this.referenceID = value;
    }

}

Another Java object:

package com.myuser.echannel;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for MyUserResponse complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="MyUserResponse">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="SomeNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="ReferenceID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MyUserResponse", propOrder = {
    "someNumber",
    "referenceID"
})
public class MyUserResponse {

    @XmlElement(name = "SomeNumber")
    protected String someNumber;
    @XmlElement(name = "ReferenceID")
    protected String referenceID;

    /**
     * Gets the value of the someNumber property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSomeNumber() {
        return someNumber;
    }

    /**
     * Sets the value of the someNumber property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSomeNumber(String value) {
        this.someNumber = value;
    }

    /**
     * Gets the value of the referenceID property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getReferenceID() {
        return referenceID;
    }

    /**
     * Sets the value of the referenceID property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setReferenceID(String value) {
        this.referenceID = value;
    }

}

MyUserResponses.java file as below:

package com.myuser.echannel;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="MyUserResponse" type="{http://tempuri.org/}MyUserResponse" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "myUserResponse"
})
@XmlRootElement(name = "MyUserResponses")
public class MyUserResponses {

    @XmlElement(name = "MyUserResponse")
    protected List<MyUserResponse> myUserResponse;

    /**
     * Gets the value of the myUserResponse property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the myUserResponse property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getMyUserResponse().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link MyUserResponse }
     *
     *
     */
    public List<MyUserResponse> getMyUserResponse() {
        if (myUserResponse == null) {
            myUserResponse = new ArrayList<MyUserResponse>();
        }
        return this.myUserResponse;
    }

}

Object Factory:

package com.myuser.echannel;

import javax.xml.bind.annotation.XmlRegistry;

/**
 * This object contains factory methods for each
 * Java content interface and Java element interface
 * generated in the com.myuser.echannel package.
 *
An ObjectFactory allows you to programatically
 * construct new instances of the Java representation
 * for XML content. The Java representation of XML
 * content can consist of schema derived interfaces
 * and classes representing the binding of schema
 * type definitions, element declarations and model
 * groups.  Factory methods for each of these are
 * provided in this class.
 *
 */
@XmlRegistry
public class ObjectFactory {

    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.myuser.echannel
     *
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link MyUserResponses }
     *
     */
    public MyUserResponses createMyUserResponses() {
        return new MyUserResponses();
    }

    /**
     * Create an instance of {@link MyUserResponse }
     *
     */
    public MyUserResponse createMyUserResponse() {
        return new MyUserResponse();
    }

    /**
     * Create an instance of {@link MyUserRequest }
     *
     */
    public MyUserRequest createMyUserRequest() {
        return new MyUserRequest();
    }

}

package-info.java file:

@javax.xml.bind.annotation.XmlSchema(namespace = "http://tempuri.org/", elementFormDefault =     javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.myuser.echannel;

I am handling the SOAP request with the request body as below to my spring integration layer(which is the below web.xml and spring context files):

web.xml:

<servlet>
        <servlet-name>spring-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/spring-ws-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-ws</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

spring-ws-config.xml file:

<context:component-scan base-package="com.nbad.eChannel"/>

    <import resource="classpath:/WEB-INF/inbound-gateway-config.xml"/>

    <bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
     <property name="mappings">
     <props>

     <prop key="{http://tempuri.org/}MyUserRequest">ws-myuser-gateway</prop>
     </props>
     </property>
    </bean>

</beans>

<context:component-scan base-package="com.mypackage"/>

<import resource="classpath:/com/mypackage/si/jdbc/config/spring-integration-context.xml"/>

    <int:channel id="FFUserRequestChannel"/>

    <int-ws:inbound-gateway id="ws-ffuser-gateway" request-channel="FFUserRequestChannel" marshaller="marshaller" unmarshaller="marshaller"/>

    <bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="contextPath" value="com.mypackage.model" />
    </bean>

    <int:service-activator input-channel="MyUserRequestChannel">
    <bean class="com.mypackage.serviceImpl.MyUserImpl">
    <constructor-arg ref = "MyUserRequest"></constructor-arg>
    </bean>
    </int:service-activator>

    <bean id="MyUserRequest" class="com.mypackage.model.MyUserRequest"></bean>
    <bean id="MyUserResponse" class="com.mypackage.model.MyUserResponse"></bean>

</beans>

as above, I am using the Jaxb2Marshaller for marshalling and unmarshalling purpose. Now serviceImpl file is as below:

package com.mypackage.serviceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

import com.mypackage.model.*;
import com.mypackage.service.MyUser;
import com.mypackage.si.jdbc.service.MyUserJdbc;
/**
 * @author Vinay Agrawal
 */
public class MyUserImpl implements MyUser{

    @Autowired
    MyUserRequest request;
    @Autowired
    MyUserJdbc MyUserJdbc;
    public MyUserImpl() {
    }

    public MyUserImpl(MyUserRequest request) {
        super();
        this.request = request;
    }

    @Override
    @PayloadRoot(localPart = "issueResponseFor" , namespace = "http://tempuri.org/")
    @ResponsePayload
    public List<MyUserResponse>issueResponseFor(@RequestPayload MyUserRequest request) {
        List<MyUserResponse> MyUserResponse = new ArrayList<MyUserResponse>();

        MyUserResponse = (List<MyUserResponse>)MyUserJdbc.getMyUserResponse(request);

        return MyUserResponse;
        }
}

Here I am calling DB layer and getting List of the MyUserResponse(multiple records) from DB and using spring integration marshaller Jaxb2Marshaller, I am expecting this will marshall the java object into soap response and should display this list in the SOAPUI for MyUserResponse list. but I am getting the below error on SOAP UI and from Junit:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <SOAP-ENV:Body>
      <SOAP-ENV:Fault>
         <faultcode>SOAP-ENV:Server</faultcode>
         <faultstring xml:lang="en">Unknown JAXB exception; nested exception is javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.</faultstring>
      </SOAP-ENV:Fault>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

error generated from Junit:

org.springframework.ws.soap.client.SoapFaultClientException: Unknown JAXB exception; nested exception is javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.
    at org.springframework.ws.soap.client.core.SoapFaultMessageResolver.resolveFault(SoapFaultMessageResolver.java:37)
    at org.springframework.ws.client.core.WebServiceTemplate.handleFault(WebServiceTemplate.java:776)
    at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:602)
    at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:539)
    at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:494)
    at org.springframework.ws.client.core.WebServiceTemplate.sendSourceAndReceiveToResult(WebServiceTemplate.java:438)
    at org.springframework.ws.client.core.WebServiceTemplate.sendSourceAndReceiveToResult(WebServiceTemplate.java:423)
    at com.nbad.eChannel.Common.InContainerTests.testWebServiceRequestAndResponse(InContainerTests.java:44)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

My SOAP request is as below:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>

     <sch:MyUserRequest>
        <sch:SomeNumber>8009618916</sch:SomeNumber>
        <sch:ReferenceID>ReferenceIDReferenceID</sch:ReferenceID>
     </sch:MyUserRequest>

</soapenv:Body>
</soapenv:Envelope>

Again I receive the proper response(one record) if I do changes in the xsd file for getting the single record and corresponding changes in java object file created but face issue when try to get multiple record response.

Please help me to find where I am doing mistake or missing something.

Body:
I have got similar issue, I had generated the stubs using CXF. I got similar error and on analysis I have found that the list I'm creating had some null values which caused it. I have replaced null values with empty string. My code is as below using Java 8. If I enable the commented line of code I get  java.util.ArrayList nor any of its super class is known to this context  exception.

Hope this will help someone.

    model.keySet().forEach( val ->{
                TestRequest.Param param = new Param();
                param.setKey(val);
                param.setValue(model.get(val) != null ?model.get(val).toString():""); //works fine
                    //below line has caused the issue
                    //param.setValue(model.get(val));
                request.getParam().add(param);// this is the list on my request
            });


问:
How do I parse object data from MySQL database using PHP PDO?
I have run into an issue while trying to return object data from my database. I followed this tutorial to build a DB wrapper and have been trying to extend the functionality of it to suit my needs. My problem is that when I use the DB class "get" method to return data, it also returns an instance of the PDO object itself. I am wondering how I parse this data so that I only return objects from the database, and not the database object itself. I want to be able to display different database values for each object eventually.

Here is all of my relevant code:

```<code>class DB {

private static $_instance = null; //stores instance of database
private $_pdo,
        $_query,
        $_error = false,
        $_results,
        $_count = 0;

private function __construct() {
    try {
        $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'),  Config::get('mysql/password'));
    } catch(PDOException $e){
        die($e->getMessage());
    }
}

public static function getInstance() {
    if(!isset(self::$_instance)){
        self::$_instance = new DB();
    }
    return self::$_instance;
}

public function query($sql, $params = array()){
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)) {
        $x = 1;
        if(count($params)) {
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }
        if($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
    }
    return $this;
}

public function action($action, $table, $where = array()) {
    if(count($where) === 3) {
        $operators = array('=', '>', '<', '>=', '<=');

        $field = $where[0];
        $operator = $where[1];
        $value = $where[2];

        if(in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
            if(!$this->query($sql, array($value))->error()) {
                return $this;
            }
        }

    } return $this;

}

public function get($table, $where) {
    return $this->action('SELECT *', $table, $where);

}
}

class Schedule {

private $_db;
protected $_games = array();

public function __construct() {

    $this->_db = DB::getInstance();

}

public function listGames() {

    $data = $this->_db->get('games', array('id', '>', 0));
    var_dump($data);

    echo '<br>';

}
}
</code>```

答:
The problem with these video tutorials is their authors who have no clue on the subject, making the result MUCH MUCH WORSE than if you weren't using their mental excrement at all. The damage they are inflicting is so bad that I even had to write a dedicated article that explains why all these helpless "wrappers" are totally unusable for the any real life application, Your first database wrapper's childhood diseases.

Take this wrapper from the video for instance:

Error reporting is completely flawed

A useless function for SELECTs.

Statefulness

Protected PDO instance

So, in essence, you'll be unable to get from this "wrapper" even such a silly thing as Insert Id. And no error reporting could help you even to realize the problem.

As of your code, just don't bargain for saving yourself typing an SQL keyword. It's silly. SQL is a precious thing, do not dismiss it in favor of some gibberish shortcuts. Neither you should diminish PDO to a state of a crippled invalid, trashing off its most brilliant features.

Your wrapper should make all PDO and SQL features accessible instead of discarding them. So it goes:

```<code>class DB
{
    protected static $instance;
    protected $pdo;

    protected function __construct() {
            $opt  = array(
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                PDO::ATTR_EMULATE_PREPARES   => FALSE,
            );
            $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHAR;
            $this->pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);

    }

    // a classical static method to make it universally available
    public static function instance()
    {
        if (self::$instance === null)
        {
            self::$instance = new self;
        }
        return self::$instance;
    }

    // a proxy to native PDO methods
    public function __call($method, $args)
    {
        return call_user_func_array(array($this->pdo, $method), $args);
    }

    // a helper function to run prepared statements smoothly
    public function run($sql, $args = [])
    {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($args);
        return $stmt;
    }
}
</code>```

this wrapper is ten times simpler and at the same time ten times more powerful than that from the video.

And now your class

```<code>class Schedule
{
    private $_db;

    public function __construct()
    {
        $this->_db = DB::instance();
    }

    public function listGames()
    {
        $data = $this->_db->query('SELECT * FROM games')->fetchAll();
        var_dump($data);
        echo '<br>';
    }
}
</code>```

The secret here is that PDO can already give you object data, with not a single extra line of coding.

Although this simple example is not very impressive, the secret here is that this wrapper will serve you for any other example as well, when that from the video will choke. Try to think of any other example and I will show you how simple yet powerful this wrapper is.

Body:
I have run into an issue while trying to return object data from my database. I followed this tutorial to build a DB wrapper and have been trying to extend the functionality of it to suit my needs. My problem is that when I use the DB class "get" method to return data, it also returns an instance of the PDO object itself. I am wondering how I parse this data so that I only return objects from the database, and not the database object itself. I want to be able to display different database values for each object eventually.

Here is all of my relevant code:

class DB {

private static $_instance = null; //stores instance of database
private $_pdo,
        $_query,
        $_error = false,
        $_results,
        $_count = 0;

private function __construct() {
    try {
        $this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'),  Config::get('mysql/password'));
    } catch(PDOException $e){
        die($e->getMessage());
    }
}

public static function getInstance() {
    if(!isset(self::$_instance)){
        self::$_instance = new DB();
    }
    return self::$_instance;
}

public function query($sql, $params = array()){
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)) {
        $x = 1;
        if(count($params)) {
            foreach($params as $param) {
                $this->_query->bindValue($x, $param);
                $x++;
            }
        }
        if($this->_query->execute()) {
            $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count = $this->_query->rowCount();
        } else {
            $this->_error = true;
        }
    }
    return $this;
}

public function action($action, $table, $where = array()) {
    if(count($where) === 3) {
        $operators = array('=', '>', '<', '>=', '<=');

        $field = $where[0];
        $operator = $where[1];
        $value = $where[2];

        if(in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
            if(!$this->query($sql, array($value))->error()) {
                return $this;
            }
        }

    } return $this;

}

public function get($table, $where) {
    return $this->action('SELECT *', $table, $where);

}
}

class Schedule {

private $_db;
protected $_games = array();

public function __construct() {

    $this->_db = DB::getInstance();

}

public function listGames() {

    $data = $this->_db->get('games', array('id', '>', 0));
    var_dump($data);

    echo '
';

}
}

Body:
The problem with these video tutorials is their authors who have no clue on the subject, making the result MUCH MUCH WORSE than if you weren't using their mental excrement at all. The damage they are inflicting is so bad that I even had to write a dedicated article that explains why all these helpless "wrappers" are totally unusable for the any real life application, Your first database wrapper's childhood diseases.

Take this wrapper from the video for instance:

Error reporting is completely flawed

A useless function for SELECTs.

Statefulness

Protected PDO instance

So, in essence, you'll be unable to get from this "wrapper" even such a silly thing as Insert Id. And no error reporting could help you even to realize the problem.

As of your code, just don't bargain for saving yourself typing an SQL keyword. It's silly. SQL is a precious thing, do not dismiss it in favor of some gibberish shortcuts. Neither you should diminish PDO to a state of a crippled invalid, trashing off its most brilliant features.

Your wrapper should make all PDO and SQL features accessible instead of discarding them. So it goes:

class DB
{
    protected static $instance;
    protected $pdo;

    protected function __construct() {
            $opt  = array(
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                PDO::ATTR_EMULATE_PREPARES   => FALSE,
            );
            $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHAR;
            $this->pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);

    }

    // a classical static method to make it universally available
    public static function instance()
    {
        if (self::$instance === null)
        {
            self::$instance = new self;
        }
        return self::$instance;
    }

    // a proxy to native PDO methods
    public function __call($method, $args)
    {
        return call_user_func_array(array($this->pdo, $method), $args);
    }

    // a helper function to run prepared statements smoothly
    public function run($sql, $args = [])
    {
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($args);
        return $stmt;
    }
}

this wrapper is ten times simpler and at the same time ten times more powerful than that from the video.

And now your class

class Schedule
{
    private $_db;

    public function __construct()
    {
        $this->_db = DB::instance();
    }

    public function listGames()
    {
        $data = $this->_db->query('SELECT * FROM games')->fetchAll();
        var_dump($data);
        echo '<br>';
    }
}

The secret here is that PDO can already give you object data, with not a single extra line of coding.

Although this simple example is not very impressive, the secret here is that this wrapper will serve you for any other example as well, when that from the video will choke. Try to think of any other example and I will show you how simple yet powerful this wrapper is.


问:
os.chmod() is Python 2.7 only works for file?
It seems os.chmod(path, stat.S_IWSUR) only works for file. Is it a known bug? How can I chmod for a whole folder including its content?</p>

答:
os.chmod is not intended to replicate all features of the chmod shell command; it's more like the chmod system call. Particularly, like the system call and unlike the shell command, it doesn't support a recursive chmod; you'd have to do that yourself with something like os.walk.

You can os.chmod a directory, but it won't chmod the directory's contents.


问:
How to convert anything to a String safely in JavaScript
If I have:

```<code>var test = {toString: function(){alert("evil code"); return "test";}};
</code>```

how can I convert test to a string? without calling test.toString() and without using a typeof x == "string" check since I want to allow non strings.

Note: this is for a FF extension dealing with objects from a content page's js scope.

答:
Your (toString: function(){alert("evil code"); return "test";}) doesn't even get parsed here, it throws a syntax error. I think you wanted to use {} instead of ().

Normally you could use an empty string and the plus operator to perform a cast:

```<code>""+test;
""+2; // "2"
""+4.5 // "4.5"
""+[1, 2, 3] // "1,2,3"
""+{} // '[object Object]'
</code>```

But here, there's no real way to convert the object safely.

You can use delete test.toString to get rid of the overridden method, after that it will fall back to the normal toString method which returns '[object Object]'. You can also convert the toString method itself into a string via test.toString.toString().

```<code>"function () { alert("evil code"); return "test"; }"
</code>```

It's up to you what you exactly want to do here.

Body:
If I have:

var test = {toString: function(){alert("evil code"); return "test";}};

how can I convert test to a string? without calling test.toString() and without using a typeof x == "string" check since I want to allow non strings.

Note: this is for a FF extension dealing with objects from a content page's js scope.

Body:
Your (toString: function(){alert("evil code"); return "test";}) doesn't even get parsed here, it throws a syntax error. I think you wanted to use {} instead of ().

Normally you could use an empty string and the plus operator to perform a cast:

""+test;
""+2; // "2"
""+4.5 // "4.5"
""+[1, 2, 3] // "1,2,3"
""+{} // '[object Object]'

But here, there's no real way to convert the object safely.

You can use delete test.toString to get rid of the overridden method, after that it will fall back to the normal toString method which returns '[object Object]'. You can also convert the toString method itself into a string via test.toString.toString().

"function () { alert("evil code"); return "test"; }"

It's up to you what you exactly want to do here.


问:
How to migrate data to Alfresco from Ftp servers as data sources?
The Situation: I'm going to implement a digital repository using alfresco community version 5.1 to manage our university digital content which is stored at a moment in differents ftp servers (software installers, books, thesis). I intent to use alfresco as a backend and Orchard CMS as our intranet frontend which is a non functional requierement and communicate both with CMIS. The general idea is that we use a social networking approch in which every user can modify metadata, add tags in order to improve the search, which by the way is the general objective of my work (allows searches and download to the digital content of our intranet , because right know it takes a lot of time to find anything because it is storage in a ftp server without a good cataloging).
I already successfully created a custom data model but when a decided to migrate the content from these ftps, i didn't find any documentation about it. I read about bulk import tool but it happent that i need the data locally in the same computer that runs alfresco, and as i said, the data source are different ftp server.
So How can i migrate data from differents ftps servers as datasource to Alfresco?. Is it necessary to physically import files to Alfresco or can i work with index pointing to the ftp files (keep the files in the ftps and have in Alfresco a reference of that object (I only have search and download functional requierements))?.
Please I need your help as a guidence because here in cuba we dont have experience working with Alfresco and it is very difficult to have access to internet. So if you can point out the way of fixing this, or any recommendation i will be forever greatfull. Thank You and Again so sorry to disturb You</p>

答:
If this were a one-time thing, you could use an FTP client of some sort to simply drag and drop the files from your FTP server into Alfresco's FTP server. This would copy the files only and would not set any custom metadata.

Alternatively, you could write some Java to do this. Java can read from FTP servers and can write to Alfresco via CMIS. This would give you the opportunity to set some properties on the objects written into Alfresco beyond just the file name, creation date, and modification date.

However, if you are going to do this regularly, you might want to look at an integration tool. For example, you could use Apache Camel to watch the FTP servers, and when there is a change, it could fetch the file and write it to Alfresco via CMIS.

This will likely take some coding to make it work exactly right, but hopefully this gives you some options to consider.


问:
JEST and ES6 import - root folder based imports does not working
I have a React project based on React Redux Starter Kit.

In Jest tests: when I trying to import something with root-based path like "components/Link" - it does not work. Only relative paths are working.

Putting

```<code>{ "jest": { "rootDir": "<rootDir>/src" } }
</code>```

in file package.json does not work.

Is there another way?

File package.json:

```<code>{
  "name": "react-redux-starter-kit",
  "version": "3.0.0-alpha.2",
  "description": "",
  "main": "index.js",
  "engines": {
    "node": ">=4.5.0",
    "npm": "^3.0.0"
  },
  "scripts": {
    "clean": "rimraf dist",
    "compile": "better-npm-run compile",
    "lint": "eslint bin build config server src tests",
    "lint:fix": "npm run lint -- --fix",
    "start": "better-npm-run start",
    "dev": "better-npm-run dev",
    "test": "jest",
    "test:dev": "npm run test -- --watch",
    "deploy": "better-npm-run deploy",
    "deploy:dev": "better-npm-run deploy:dev",
    "deploy:prod": "better-npm-run deploy:prod",
    "codecov": "cat coverage/*/lcov.info | codecov"
  },
  "betterScripts": {
    "compile": {
      "command": "node bin/compile",
      "env": {
        "DEBUG": "app:*"
      }
    },
    "dev": {
      "command": "nodemon bin/server --ignore dist --ignore coverage --ignore tests --ignore src",
      "env": {
        "NODE_ENV": "development",
        "DEBUG": "app:*"
      }
    },
    "deploy": {
      "command": "npm run lint && npm run clean && npm run compile",
      "env": {
        "DEBUG": "app:*"
      }
    },
    "deploy:dev": {
      "command": "npm run deploy",
      "env": {
        "NODE_ENV": "development",
        "DEBUG": "app:*"
      }
    },
    "deploy:prod": {
      "command": "npm run deploy",
      "env": {
        "NODE_ENV": "production",
        "DEBUG": "app:*"
      }
    },
    "start": {
      "command": "node bin/server",
      "env": {
        "DEBUG": "app:*"
      }
    },
    "test": {
      "command": "node ./node_modules/karma/bin/karma start build/karma.conf",
      "env": {
        "NODE_ENV": "test",
        "DEBUG": "app:*"
      }
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/davezuko/react-redux-starter-kit.git"
  },
  "author": "MyCityOnline",
  "license": "MIT",
  "dependencies": {
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.5",
    "babel-plugin-transform-runtime": "^6.15.0",
    "babel-preset-es2015": "^6.14.0",
    "babel-preset-react": "^6.11.1",
    "babel-preset-stage-0": "^6.3.13",
    "babel-runtime": "^6.11.6",
    "better-npm-run": "0.0.11",
    "cropperjs": "^1.0.0-beta.2",
    "css-loader": "^0.25.0",
    "cssnano": "^3.7.4",
    "debug": "^2.2.0",
    "dotenv": "^2.0.0",
    "es6-promise": "^4.1.0",
    "essence-core": "^1.0.20",
    "essence-switch": "^1.0.10",
    "exports-loader": "^0.6.3",
    "extract-text-webpack-plugin": "^1.0.0",
    "file-loader": "^0.9.0",
    "font-awesome": "^4.7.0",
    "fs-extra": "^0.30.0",
    "html-webpack-plugin": "^2.22.0",
    "imports-loader": "^0.6.5",
    "ip": "^1.1.2",
    "isomorphic-fetch": "^2.2.1",
    "json-loader": "^0.5.4",
    "jwt-decode": "^2.1.0",
    "lodash": "^4.16.3",
    "moment": "^2.17.1",
    "node-sass": "^3.7.0",
    "normalize.css": "^4.1.1",
    "pikaday": "^1.5.1",
    "postcss-loader": "^0.13.0",
    "react": "^15.0.0",
    "react-dom": "^15.0.0",
    "react-redux": "^4.4.5",
    "react-router": "^2.8.0",
    "redux": "^3.6.0",
    "redux-api-middleware": "^1.0.2",
    "redux-thunk": "^2.0.0",
    "rimraf": "^2.5.4",
    "sass-loader": "^4.0.0",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.6",
    "webpack": "^1.12.14",
    "whatwg-fetch": "^2.0.1",
    "yargs": "^5.0.0"
  },
  "devDependencies": {
    "babel-eslint": "^6.0.0-beta.6",
    "babel-jest": "^19.0.0",
    "babel-plugin-istanbul": "^2.0.1",
    "breakpoint-sass": "^2.7.0",
    "chai": "^3.4.1",
    "chai-as-promised": "^5.3.0",
    "chai-enzyme": "^0.5.0",
    "cheerio": "^0.20.0",
    "codecov": "^1.0.1",
    "connect-history-api-fallback": "^1.3.0",
    "enzyme": "^2.0.0",
    "eslint": "^3.0.1",
    "eslint-config-standard": "^6.2.1",
    "eslint-config-standard-react": "^4.0.0",
    "eslint-plugin-babel": "^3.2.0",
    "eslint-plugin-promise": "^3.3.0",
    "eslint-plugin-react": "^6.0.0",
    "eslint-plugin-standard": "^2.0.0",
    "express": "^4.14.0",
    "http-proxy-middleware": "^0.17.2",
    "jest": "^19.0.2",
    "karma": "^1.0.0",
    "karma-coverage": "^1.0.0",
    "karma-mocha": "^1.0.1",
    "karma-mocha-reporter": "^2.0.0",
    "karma-phantomjs-launcher": "^1.0.2",
    "karma-webpack-with-fast-source-maps": "^1.9.2",
    "less": "^2.7.1",
    "less-loader": "^2.2.3",
    "mocha": "^3.0.1",
    "nodemon": "^1.10.2",
    "phantomjs-prebuilt": "^2.1.12",
    "react-addons-test-utils": "^15.0.0",
    "redbox-react": "^1.2.10",
    "redux-logger": "^2.6.1",
    "regenerator-runtime": "^0.10.3",
    "sinon": "^1.17.5",
    "sinon-chai": "^2.8.0",
    "susy": "^2.2.12",
    "webpack-dev-middleware": "^1.6.1",
    "webpack-hot-middleware": "^2.12.2"
  },
    "jest": {
        "rootDir": "<rootDir>/src"
  }
}
</code>```

Final working Jest part of file package.json:

```<code>"jest": {
    "rootDir": "./src/",
    "moduleFileExtensions": ["js", "jsx"],
    "moduleDirectories": ["node_modules", "bower_components", "src"],
    "verbose": true
}
</code>```

答:
I think that if you don't want to use relative paths, you have to define additional moduleDirectories, like

```<code>// package.json
{
  "jest": {
    "moduleFileExtensions": ["js", "jsx"],
    "moduleDirectories": ["node_modules", "bower_components", "src"],
  }
}
</code>```

More about moduleDirectories in jest docs and configuring jest to find files.

Body:
I have a React project based on React Redux Starter Kit.

In Jest tests: when I trying to import something with root-based path like "components/Link" - it does not work. Only relative paths are working.

Putting

{ "jest": { "rootDir": "<rootDir>/src" } }

in file package.json does not work.

Is there another way?

File package.json:

{
  "name": "react-redux-starter-kit",
  "version": "3.0.0-alpha.2",
  "description": "",
  "main": "index.js",
  "engines": {
    "node": ">=4.5.0",
    "npm": "^3.0.0"
  },
  "scripts": {
    "clean": "rimraf dist",
    "compile": "better-npm-run compile",
    "lint": "eslint bin build config server src tests",
    "lint:fix": "npm run lint -- --fix",
    "start": "better-npm-run start",
    "dev": "better-npm-run dev",
    "test": "jest",
    "test:dev": "npm run test -- --watch",
    "deploy": "better-npm-run deploy",
    "deploy:dev": "better-npm-run deploy:dev",
    "deploy:prod": "better-npm-run deploy:prod",
    "codecov": "cat coverage/*/lcov.info | codecov"
  },
  "betterScripts": {
    "compile": {
      "command": "node bin/compile",
      "env": {
        "DEBUG": "app:*"
      }
    },
    "dev": {
      "command": "nodemon bin/server --ignore dist --ignore coverage --ignore tests --ignore src",
      "env": {
        "NODE_ENV": "development",
        "DEBUG": "app:*"
      }
    },
    "deploy": {
      "command": "npm run lint && npm run clean && npm run compile",
      "env": {
        "DEBUG": "app:*"
      }
    },
    "deploy:dev": {
      "command": "npm run deploy",
      "env": {
        "NODE_ENV": "development",
        "DEBUG": "app:*"
      }
    },
    "deploy:prod": {
      "command": "npm run deploy",
      "env": {
        "NODE_ENV": "production",
        "DEBUG": "app:*"
      }
    },
    "start": {
      "command": "node bin/server",
      "env": {
        "DEBUG": "app:*"
      }
    },
    "test": {
      "command": "node ./node_modules/karma/bin/karma start build/karma.conf",
      "env": {
        "NODE_ENV": "test",
        "DEBUG": "app:*"
      }
    }
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/davezuko/react-redux-starter-kit.git"
  },
  "author": "MyCityOnline",
  "license": "MIT",
  "dependencies": {
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.5",
    "babel-plugin-transform-runtime": "^6.15.0",
    "babel-preset-es2015": "^6.14.0",
    "babel-preset-react": "^6.11.1",
    "babel-preset-stage-0": "^6.3.13",
    "babel-runtime": "^6.11.6",
    "better-npm-run": "0.0.11",
    "cropperjs": "^1.0.0-beta.2",
    "css-loader": "^0.25.0",
    "cssnano": "^3.7.4",
    "debug": "^2.2.0",
    "dotenv": "^2.0.0",
    "es6-promise": "^4.1.0",
    "essence-core": "^1.0.20",
    "essence-switch": "^1.0.10",
    "exports-loader": "^0.6.3",
    "extract-text-webpack-plugin": "^1.0.0",
    "file-loader": "^0.9.0",
    "font-awesome": "^4.7.0",
    "fs-extra": "^0.30.0",
    "html-webpack-plugin": "^2.22.0",
    "imports-loader": "^0.6.5",
    "ip": "^1.1.2",
    "isomorphic-fetch": "^2.2.1",
    "json-loader": "^0.5.4",
    "jwt-decode": "^2.1.0",
    "lodash": "^4.16.3",
    "moment": "^2.17.1",
    "node-sass": "^3.7.0",
    "normalize.css": "^4.1.1",
    "pikaday": "^1.5.1",
    "postcss-loader": "^0.13.0",
    "react": "^15.0.0",
    "react-dom": "^15.0.0",
    "react-redux": "^4.4.5",
    "react-router": "^2.8.0",
    "redux": "^3.6.0",
    "redux-api-middleware": "^1.0.2",
    "redux-thunk": "^2.0.0",
    "rimraf": "^2.5.4",
    "sass-loader": "^4.0.0",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.6",
    "webpack": "^1.12.14",
    "whatwg-fetch": "^2.0.1",
    "yargs": "^5.0.0"
  },
  "devDependencies": {
    "babel-eslint": "^6.0.0-beta.6",
    "babel-jest": "^19.0.0",
    "babel-plugin-istanbul": "^2.0.1",
    "breakpoint-sass": "^2.7.0",
    "chai": "^3.4.1",
    "chai-as-promised": "^5.3.0",
    "chai-enzyme": "^0.5.0",
    "cheerio": "^0.20.0",
    "codecov": "^1.0.1",
    "connect-history-api-fallback": "^1.3.0",
    "enzyme": "^2.0.0",
    "eslint": "^3.0.1",
    "eslint-config-standard": "^6.2.1",
    "eslint-config-standard-react": "^4.0.0",
    "eslint-plugin-babel": "^3.2.0",
    "eslint-plugin-promise": "^3.3.0",
    "eslint-plugin-react": "^6.0.0",
    "eslint-plugin-standard": "^2.0.0",
    "express": "^4.14.0",
    "http-proxy-middleware": "^0.17.2",
    "jest": "^19.0.2",
    "karma": "^1.0.0",
    "karma-coverage": "^1.0.0",
    "karma-mocha": "^1.0.1",
    "karma-mocha-reporter": "^2.0.0",
    "karma-phantomjs-launcher": "^1.0.2",
    "karma-webpack-with-fast-source-maps": "^1.9.2",
    "less": "^2.7.1",
    "less-loader": "^2.2.3",
    "mocha": "^3.0.1",
    "nodemon": "^1.10.2",
    "phantomjs-prebuilt": "^2.1.12",
    "react-addons-test-utils": "^15.0.0",
    "redbox-react": "^1.2.10",
    "redux-logger": "^2.6.1",
    "regenerator-runtime": "^0.10.3",
    "sinon": "^1.17.5",
    "sinon-chai": "^2.8.0",
    "susy": "^2.2.12",
    "webpack-dev-middleware": "^1.6.1",
    "webpack-hot-middleware": "^2.12.2"
  },
    "jest": {
        "rootDir": "<rootDir>/src"
  }
}

Final working Jest part of file package.json:

"jest": {
    "rootDir": "./src/",
    "moduleFileExtensions": ["js", "jsx"],
    "moduleDirectories": ["node_modules", "bower_components", "src"],
    "verbose": true
}

Body:
I think that if you don't want to use relative paths, you have to define additional moduleDirectories, like

// package.json
{
  "jest": {
    "moduleFileExtensions": ["js", "jsx"],
    "moduleDirectories": ["node_modules", "bower_components", "src"],
  }
}

More about moduleDirectories in jest docs and configuring jest to find files.