问:
Python: parse JSON in loop
I have a function that pick-ups Country,City,Latitude,Longitude from a database and search on Yelp API for particular business.

And everything works fine:

```<code>def get_movietheaters_for(country, city, latitude, longitude):
    connection2 = pyodbc.connect('DRIVER={SQL Server};'
                                 'SERVER=ASPIRES3;'
                                 'DATABASE=worldcitiespop;'
                                 'UID=sqlninja;'
                                 'PWD=sqlninja')
    cursor2 = connection2.cursor()
    # Call Yelp API to pull business data
    # (Yelp v3 API: https://nz.yelp.com/developers/documentation/v3)
    url = 'https://api.yelp.com/v3/businesses/search'
    params = {'cc': country,
              'location': city,
              'cll': "%s,%s" % (latitude, longitude),
              'categories': args.category,
              'limit': args.limit}
    response = requests.get(url = url, headers = headers, params=params)
    # if response.status_code == 200:
    response_data = response.json()

    sqlStatement = "INSERT INTO VistaYelp (ID, Name, City, Zip_code, Country, State, Address1, Address2, Address3, Latitude, Longitude, Phone, Yelp_URL, Review_Count, Rating) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" # Query
    # Here we go to store JSON elements for SQL

    for SQL_element in response_data['businesses']:
        SQL_ID = SQL_element['id']
        SQL_Name = SQL_element['name']
        SQL_City = SQL_element['location']['city']
        SQL_Zip_code = SQL_element['location']['zip_code']
        SQL_Country = SQL_element['location']['country']
        SQL_State = SQL_element['location']['state']
        SQL_Address1 = SQL_element['location']['address1']
        SQL_Address2 = SQL_element['location']['address2']
        SQL_Address3 = SQL_element['location']['address3']
        SQL_Latitude = SQL_element['coordinates']['latitude']
        SQL_Longitude = SQL_element['coordinates']['longitude']
        SQL_Phone = SQL_element['phone']
        SQL_YelpURL = SQL_element['url']
        SQL_Review = SQL_element['review_count']
        SQL_Rating = SQL_element['rating']

        if args.do == 'show':
            print (SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,
                SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone)
        elif args.do == 'save':
            cursor2.execute(sqlStatement, SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone,SQL_YelpURL,SQL_Review,SQL_Rating)
            connection2.commit()

    if args.do == 'show':
        print ('\nTotal Cinemas found: ' , len(response_data['businesses']),' for Latitude and Longitude ', latitude, longitude)
    elif args.do == 'save':
        print ('\nTotal Cinemas found and saved in database: ' , len(response_data['businesses']),' for', latitude, longitude)
</code>```

Problem start when the script search for a town that doesn't exists or is not in the Yelp database, so JSON call returns me:

```<code>{
  "error": {
    "code": "LOCATION_NOT_FOUND",
    "description": "Could not execute search, try specifying a more exact location."
  }
}
</code>```

and the script dies in terrible pain (my pain actually):

And it make sense to me, Python is saying:

```<code>    for SQL_element in response_data['businesses']:
KeyError: 'businesses'
</code>```

Which translated means:"Hey dude, you know 'businesses' JSON element, there is no such element in the response, so I don't know what to do, so I stop here."

How can I structure something like: keep doing your job and if response_data['error']['code'] == 'LOCATION_NOT_FOUND': do nothing?

答:
You should probably try to catch the error and abort further execution of the function.

```<code>if "error" in response_data:
    return #Function will stop on a return call
</code>```

You could even return something like a status if you want, e.g.

```<code>return True
return False
</code>```

See this question for more information on the return command.

Title: Python: parse JSON in loop

Body:
I have a function that pick-ups Country,City,Latitude,Longitude from a database and search on Yelp API for particular business.

And everything works fine:

def get_movietheaters_for(country, city, latitude, longitude):
    connection2 = pyodbc.connect('DRIVER={SQL Server};'
                                 'SERVER=ASPIRES3;'
                                 'DATABASE=worldcitiespop;'
                                 'UID=sqlninja;'
                                 'PWD=sqlninja')
    cursor2 = connection2.cursor()
    # Call Yelp API to pull business data
    # (Yelp v3 API: https://nz.yelp.com/developers/documentation/v3)
    url = 'https://api.yelp.com/v3/businesses/search'
    params = {'cc': country,
              'location': city,
              'cll': "%s,%s" % (latitude, longitude),
              'categories': args.category,
              'limit': args.limit}
    response = requests.get(url = url, headers = headers, params=params)
    # if response.status_code == 200:
    response_data = response.json()

    sqlStatement = "INSERT INTO VistaYelp (ID, Name, City, Zip_code, Country, State, Address1, Address2, Address3, Latitude, Longitude, Phone, Yelp_URL, Review_Count, Rating) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" # Query
    # Here we go to store JSON elements for SQL

    for SQL_element in response_data['businesses']:
        SQL_ID = SQL_element['id']
        SQL_Name = SQL_element['name']
        SQL_City = SQL_element['location']['city']
        SQL_Zip_code = SQL_element['location']['zip_code']
        SQL_Country = SQL_element['location']['country']
        SQL_State = SQL_element['location']['state']
        SQL_Address1 = SQL_element['location']['address1']
        SQL_Address2 = SQL_element['location']['address2']
        SQL_Address3 = SQL_element['location']['address3']
        SQL_Latitude = SQL_element['coordinates']['latitude']
        SQL_Longitude = SQL_element['coordinates']['longitude']
        SQL_Phone = SQL_element['phone']
        SQL_YelpURL = SQL_element['url']
        SQL_Review = SQL_element['review_count']
        SQL_Rating = SQL_element['rating']

        if args.do == 'show':
            print (SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,
                SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone)
        elif args.do == 'save':
            cursor2.execute(sqlStatement, SQL_ID,SQL_Name,SQL_City,SQL_Zip_code,SQL_Country,SQL_State,SQL_Address1,SQL_Address2,SQL_Address3,SQL_Latitude,SQL_Longitude,SQL_Phone,SQL_YelpURL,SQL_Review,SQL_Rating)
            connection2.commit()

    if args.do == 'show':
        print ('\nTotal Cinemas found: ' , len(response_data['businesses']),' for Latitude and Longitude ', latitude, longitude)
    elif args.do == 'save':
        print ('\nTotal Cinemas found and saved in database: ' , len(response_data['businesses']),' for', latitude, longitude)

Problem start when the script search for a town that doesn't exists or is not in the Yelp database, so JSON call returns me:

{
  "error": {
    "code": "LOCATION_NOT_FOUND",
    "description": "Could not execute search, try specifying a more exact location."
  }
}

and the script dies in terrible pain (my pain actually):

And it make sense to me, Python is saying:

    for SQL_element in response_data['businesses']:
KeyError: 'businesses'

Which translated means:"Hey dude, you know 'businesses' JSON element, there is no such element in the response, so I don't know what to do, so I stop here."

How can I structure something like: keep doing your job and if response_data['error']['code'] == 'LOCATION_NOT_FOUND': do nothing?

Body:
You should probably try to catch the error and abort further execution of the function.

if "error" in response_data:
    return #Function will stop on a return call

You could even return something like a status if you want, e.g.

return True
return False

See this question for more information on the return command.


来源: stackexchange

问:
How can I retrieve values from POST request payload in Java REST service?
I would like to send a post request from AngularJS application.
I call

```<code>var data = {name: "Dave", age: 18};
$http.post(serviceAddress + 'cxf/addPerson', data};
</code>```

Java CXF side:

```<code>@POST
public Response addPerson( @Context HttpServletRequest request ) {
    String name = request.getParameter("name");
    int age = Integer.parseInt(request.getParameter("age"));
    . . .
}
</code>```

I get null for name and age and request.getParameterMap is empty as well.

How can I get this values from request payload? My Chrome developer tools says it sends name and age in request payload. So the server should retrieve it.

答:
A better way to pass data into a Post method is to send JSon, and then convert into a class (example code taken from http://www.mkyong.com/webservices/jax-rs/integrate-jackson-with-resteasy/):

```<code>import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("/json/product")
public class JSONService {

    @GET
    @Path("/get")
    @Produces("application/json")
    public Product getProductInJSON() {

        Product product = new Product();
        product.setName("iPad 3");
        product.setQty(999);

        return product;

    }

    @POST
    @Path("/post")
    @Consumes("application/json")
    public Response createProductInJSON(Product product) {

        String result = "Product created : " + product;
        return Response.status(201).entity(result).build();

    }

}
</code>```

There are some samples in Git -> https://github.com/apache/cxf

```<code>git clone git@github.com:apache/cxf.git
cd apache-cxf-3.1.11-src/distribution/src/main/release/samples/
</code>```

The ./distribution/src/main/release/samples directory.

ContentLicense: CC BY-SA 3.0

Body:
I would like to send a post request from AngularJS application.
I call

var data = {name: "Dave", age: 18};
$http.post(serviceAddress + 'cxf/addPerson', data};

Java CXF side:

@POST
public Response addPerson( @Context HttpServletRequest request ) {
    String name = request.getParameter("name");
    int age = Integer.parseInt(request.getParameter("age"));
    . . .
}

I get null for name and age and request.getParameterMap is empty as well.

How can I get this values from request payload? My Chrome developer tools says it sends name and age in request payload. So the server should retrieve it.

Body:
A better way to pass data into a Post method is to send JSon, and then convert into a class (example code taken from http://www.mkyong.com/webservices/jax-rs/integrate-jackson-with-resteasy/):

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("/json/product")
public class JSONService {

    @GET
    @Path("/get")
    @Produces("application/json")
    public Product getProductInJSON() {

        Product product = new Product();
        product.setName("iPad 3");
        product.setQty(999);

        return product;

    }

    @POST
    @Path("/post")
    @Consumes("application/json")
    public Response createProductInJSON(Product product) {

        String result = "Product created : " + product;
        return Response.status(201).entity(result).build();

    }

}

There are some samples in Git -> https://github.com/apache/cxf

git clone git@github.com:apache/cxf.git
cd apache-cxf-3.1.11-src/distribution/src/main/release/samples/

The ./distribution/src/main/release/samples directory.


问:
Angular 4 select option auto populate from page load, does not work with ngModel
I have update/edit feature page, where page loads/populates with existing values from DB so that user can change and update-submit.

All other controls working fine except <select> dropdown when I put [(ngModel)] ="" in select tag, but if I remove ngModel then it populates values correctly.

But I need to bind selected value, so ngModel comes in where it fails. Below is my code

Plunk URL - https://plnkr.co/edit/HqCOOE4fg3nmwssOXIz3?p=preview

```<code><select [(ngModel)]="selectedItem" name="kannelSettingsId" class="form-control">
   <option *ngFor="let item of kannelList;let index=index; trackBy:trackByIdx()" [value]="item.kannelSettingsId" [selected]="item.kannelSettingsId === bind.kannelSettings.kannelSettingsId">
      {{item.server}}
   </option>
</select>
</code>```

答:
@AJT-82 , Yes I tried that too even I tried with dummy values but no success.

But its  WORKING now - by adding #bindForm="ngForm" & #kannelSettingsId="ngModel"

<form class="form-horizontal" #bindForm="ngForm">
   <select required minlength="1" #kannelSettingsId="ngModel"
          [(ngModel)]="bind.kannelSettings.kannelSettingsId"
                name="updateKannelSettingsId" class="form-control">
      <option *ngFor="let item of kannelList;"
         [value]="item.kannelSettingsId"
         [selected]="item.kannelSettingsId === bind.kannelSettings.kannelSettingsId">

       {{item.server}}

      </option>
   </select>
</form>```

Body:
I have update/edit feature page, where page loads/populates with existing values from DB so that user can change and update-submit.

All other controls working fine except <select> dropdown when I put [(ngModel)] ="" in select tag, but if I remove ngModel then it populates values correctly.

But I need to bind selected value, so ngModel comes in where it fails. Below is my code

Plunk URL - https://plnkr.co/edit/HqCOOE4fg3nmwssOXIz3?p=preview

<select [(ngModel)]="selectedItem" name="kannelSettingsId" class="form-control">
   <option *ngFor="let item of kannelList;let index=index; trackBy:trackByIdx()" [value]="item.kannelSettingsId" [selected]="item.kannelSettingsId === bind.kannelSettings.kannelSettingsId">
      {{item.server}}
   </option>
</select>


问:
Does the WebPack entry have to be a JavaScript File
When you use WebPack, you typically have to set an entry point to a .js file. Is this a requirement? I have two scenarios:

I want to convert a .scss to a .css file.

I want to minify images using imagemin.

I don't have or need any JavaScript. How can this be achieved using WebPack? Is that even the right tool? I've done this using Gulp in the past. Does WebPack only make sense when you require images and CSS from your JavaScript files?

答:
For .scss to sass use sass-loader and css-loader.
and for minifying images use image-webpack-loader.

Whole configuration for webpack.conig.js is show below

```<code>module.exports = {
    entry: './app.js',
    output: {
        filename: 'bundle.js'
    },
    module: {
        rules: [
        {
            test: /\.s[ac]ss$/,
            use: ExtractTextPlugin.extract({
                use: ['css-loader', 'sass-loader'],

                fallback: 'style-loader'
            })
        }, {
            loader: 'image-webpack-loader',
            query: {
                mozjpeg: {
                    progressive: true,
                },
                gifsicle: {
                    interlaced: false,
                },
                optipng: {
                    optimizationLevel: 4,
                },
                pngquant: {
                    quality: '75-90',
                    speed: 3,
                },
            }
        }
        ]
    }
}
</code>```

Body:
For .scss to sass use sass-loader and css-loader.
and for minifying images use image-webpack-loader.

Whole configuration for webpack.conig.js is show below

module.exports = {
    entry: './app.js',
    output: {
        filename: 'bundle.js'
    },
    module: {
        rules: [
        {
            test: /\.s[ac]ss$/,
            use: ExtractTextPlugin.extract({
                use: ['css-loader', 'sass-loader'],

                fallback: 'style-loader'
            })
        }, {
            loader: 'image-webpack-loader',
            query: {
                mozjpeg: {
                    progressive: true,
                },
                gifsicle: {
                    interlaced: false,
                },
                optipng: {
                    optimizationLevel: 4,
                },
                pngquant: {
                    quality: '75-90',
                    speed: 3,
                },
            }
        }
        ]
    }
}


问:
Foreign keys in tables
when we create a foreign key in a table does it always become a duplicate index?</p>

答:
In DB2 for z/OS, if you create a table with a foreign key, you do not have to define an index on its underlying column.

An index will not be defined automatically when you create the table.  If you want one, you can create one separately (via a CREATE INDEX statement).  I think it is common to define an index that includes the foreign key column(s), but it is not a requirement.  It all depends on how your application accesses the data.

For an overview on DB2 keys, check this out:  http://publib.boulder.ibm.com/infocenter/zos/basics/index.jsp?topic=/com.ibm.db2z.doc.intro/db2z_keys.html.

ContentLicense: CC BY-SA 2.5

Title: Foreign keys in tables


问:
Override open variable for class in Swift and SpriteKit for use in XCode's ActionEditor
I'm trying to make small platformer game, just in learning purposes. I've tried to animate character with array of SKTextures like this:

```<code>let animation: SKAction = SKAction.animate(
    with: frames.map {
        let texture : SKTexture = SKTexture(imageNamed: $0)
        texture.filteringMode = SKTextureFilteringMode.nearest

        return texture
    },
    timePerFrame: 0.15
)
</code>```

frames variable is array of SKTextures. I've used map to set filtering mode for each texture. This works fine and dandy, but than i've discovered that i can create animations (actions) in ActionEditor in XCode with AnimateWithTextures action. And here lies my problem. This is much more efficient, but i can't change filtering mode for textures in animation in ActionEditor. I've looked into SKTexture class and saw this:

```<code>open class SKTexture : NSObject, NSCopying, NSCoding {
    ...
    /**
    The filtering mode the texture should use when not drawn at native size. Defaults to SKTextureFilteringLinear.
    */
    open var filteringMode: SKTextureFilteringMode
    ...
}
</code>```

If i'm not mistaken open means that i can override variable, but i don't know how. I want to set default value of filteringMode to SKTextureFilteringMode.nearest for all SKTextures so ActionEditor will use textures with texture filtering set to nearest neighbor.

Also if you know how to set filtering mode for textures in specific action – i would like to know how to do it too. Thanks

答:
you can create a function to setup the animation for you, and create an extension to SKTexture with your custom init, and when your ready just call it to your node.

```<code>extension SKTexture { // Declare this extension outside your class decleration
convenience init(customImageNamed: String) {
    self.init(imageNamed: customImageNamed)
    self.filteringMode = .nearest
}
}

func setupAnimationWithPrefix(_ prefix: String, start: Int, end: Int, timePerFrame: TimeInterval) -> SKAction{
    var textures = [SKTexture]()
    for i in start...end{
        textures.append(SKTexture(customImageNamed: "\(prefix)\(i)"))
    }
    return SKAction.animate(with: textures, timePerFrame: timePerFrame)
}
</code>```

if you have 10 images named image1, image2, image3 ect..then this is how you would use this function

```<code>func runAction(){
    let action = setupAnimationWithPrefix("image", start: 1, end: 10, timePerFrame: 0.1)
    yourNode.run(action)
} // you can change timePerFrame to your liking i find 0.1 sec per frame the best
</code>```

Body:
I'm trying to make small platformer game, just in learning purposes. I've tried to animate character with array of SKTextures like this:

let animation: SKAction = SKAction.animate(
    with: frames.map {
        let texture : SKTexture = SKTexture(imageNamed: $0)
        texture.filteringMode = SKTextureFilteringMode.nearest

        return texture
    },
    timePerFrame: 0.15
)

frames variable is array of SKTextures. I've used map to set filtering mode for each texture. This works fine and dandy, but than i've discovered that i can create animations (actions) in ActionEditor in XCode with AnimateWithTextures action. And here lies my problem. This is much more efficient, but i can't change filtering mode for textures in animation in ActionEditor. I've looked into SKTexture class and saw this:

open class SKTexture : NSObject, NSCopying, NSCoding {
    ...
    /**
    The filtering mode the texture should use when not drawn at native size. Defaults to SKTextureFilteringLinear.
    */
    open var filteringMode: SKTextureFilteringMode
    ...
}

If i'm not mistaken open means that i can override variable, but i don't know how. I want to set default value of filteringMode to SKTextureFilteringMode.nearest for all SKTextures so ActionEditor will use textures with texture filtering set to nearest neighbor.

Also if you know how to set filtering mode for textures in specific action – i would like to know how to do it too. Thanks

Body:
you can create a function to setup the animation for you, and create an extension to SKTexture with your custom init, and when your ready just call it to your node.

extension SKTexture { // Declare this extension outside your class decleration
convenience init(customImageNamed: String) {
    self.init(imageNamed: customImageNamed)
    self.filteringMode = .nearest
}
}

func setupAnimationWithPrefix(_ prefix: String, start: Int, end: Int, timePerFrame: TimeInterval) -> SKAction{
    var textures = [SKTexture]()
    for i in start...end{
        textures.append(SKTexture(customImageNamed: "\(prefix)\(i)"))
    }
    return SKAction.animate(with: textures, timePerFrame: timePerFrame)
}

if you have 10 images named image1, image2, image3 ect..then this is how you would use this function

func runAction(){
    let action = setupAnimationWithPrefix("image", start: 1, end: 10, timePerFrame: 0.1)
    yourNode.run(action)
} // you can change timePerFrame to your liking i find 0.1 sec per frame the best


问:
Speed Up Hot Folder Data Upload
I have CSV file of around 188MB. When I try to upload data using hot folder technique its taking too much time 10-12 hrs. How can I speedup the data upload?

Thanks

答:
Default value of impex.import.workers is 1. Try to change this value. And I recommend making performance test with a bit smaller file first, than 188Mb (just to get swift results)

Adjust the number of impex threads on the backoffice server to speed up ImpEx file processing. It is recommended that you start with it equal to the number of cores available on a backoffice node. You should not adjust it any higher than 2 * number of cores, and this is only if the IMPEX processes will be the only item running on the node. The actual value could be somewhere in between and will only be determined by testing and analyzing the number of other processes, jobs, apps running on your server to ensure you are not maxing out CPU.
  NOTE: this value could be higher for lower environments since Hybris will likely be the only process running.

Taken from Tuning Parameters - Hybris Wiki

Title: Speed Up Hot Folder Data Upload


问:
Getting NPE on simple Regex Replacing (Scala on Spark)
I wrote a simple code to parse a large XML file ( extract lines, clean text, and remove any html tags from it) using Apache Spark.

I'm seeing a NullPointerException when calling .replaceAllIn on a string, which is non-null.

The funny thing is that I have no errors when I run the code locally, using input from disk, but I get a NullPointerException when I run the same code on AWS EMR, loading the input file from S3.

Here is the relevant code:

```<code>val HTML_TAGS_PATTERN = """<[^>]+>""".r

// other code here...

spark
.sparkContext
.textFile(pathToInputFile, numPartitions)
.filter { str => str.startsWith("  <row ") }
.toDS()
.map { str =>

  Locale.setDefault(new Locale("en", "US"))

  val parts = str.split(""""""")

  var title: String = ""
  var body: String = ""

  // some code ommitted here

  title = StringEscapeUtils.unescapeXml(title).toLowerCase.trim
  body = StringEscapeUtils.unescapeXml(body).toLowerCase // decode xml entities

  println("before replacing, body is: "+body)

  // NEXT LINE TRIGGERS NPE
  body = HTML_TAGS_PATTERN.replaceAllIn(body, " ") // take out htmltags

}
</code>```

Things I've tried:

printing the string just before calling replaceAllIn to make sure it's not null.

making sure the Locale is not null

printing out the exception message, and stacktrace: it just tells me that that line is where the NullPointerException occurs. Nothing more

Things that are different between my local setup and AWS EMR:

in my local setup, I load the input file from disk, on EMR I load it from s3.

in my local setup, I run Spark in standalone mode, on EMR it's run in cluster mode.

Everything else is the same on my machine and on AWS EMR: Scala version, Spark version, Java version, Cluster configs...

I have been trying to figure this out for some hours and I can't think of anything else to try.

EDIT

I've moved the call to r() to within the map{} body, like this:

```<code>val HTML_TAGS_PATTERN = """<[^>]+>"""

// code ommited

.map{

   body = HTML_TAGS_PATTERN.r.replaceAllIn(body, " ")

 }
</code>```

This also produces a NPE, wit the following stracktrace:

```<code>java.lang.NullPointerException
    at java.util.regex.Pattern.<init>(Pattern.java:1350)
    at java.util.regex.Pattern.compile(Pattern.java:1028)
    at scala.util.matching.Regex.<init>(Regex.scala:191)
    at scala.collection.immutable.StringLike$class.r(StringLike.scala:255)
    at scala.collection.immutable.StringOps.r(StringOps.scala:29)
    at scala.collection.immutable.StringLike$class.r(StringLike.scala:244)
    at scala.collection.immutable.StringOps.r(StringOps.scala:29)
    at ReadSOStanfordTokenize$$anonfun$2.apply(ReadSOStanfordTokenize.scala:102)
    at ReadSOStanfordTokenize$$anonfun$2.apply(ReadSOStanfordTokenize.scala:72)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:377)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$SingleDirectoryWriteTask.execute(FileFormatWriter.scala:243)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$org$apache$spark$sql$execution$datasources$FileFormatWriter$$executeTask$3.apply(FileFormatWriter.scala:190)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$org$apache$spar
</code>```

答:
I think you should try putting the regex inline like bellow.

This is a bit of a lame solution, you should be able to define a constant, maybe put it in a global object or something. Im not sure where you are defining it that would be a problem. But remember spark serialises the code and runs it on distributed workers, so something could be going wrong with that.

```<code>rdd.map { _ =>
   ...

   body = """<[^>]+>""".r.replaceAllIn(body, " ")

 }
</code>```

I get a very similar error when I run .r on a null String.

```<code>val x: String = null
x.r
java.lang.NullPointerException
  java.util.regex.Pattern.<init>(Pattern.java:1350)
  java.util.regex.Pattern.compile(Pattern.java:1028)
  scala.util.matching.Regex.<init>(Regex.scala:223)
  scala.collection.immutable.StringLike.r(StringLike.scala:281)
  scala.collection.immutable.StringLike.r$(StringLike.scala:281)
  scala.collection.immutable.StringOps.r(StringOps.scala:29)
  scala.collection.immutable.StringLike.r(StringLike.scala:270)
  scala.collection.immutable.StringLike.r$(StringLike.scala:270)
  scala.collection.immutable.StringOps.r(StringOps.scala:29)
</code>```

That error has slightly different line numbers, I think because of the scala version. Im on 2.12.2.

Body:
I wrote a simple code to parse a large XML file ( extract lines, clean text, and remove any html tags from it) using Apache Spark.

I'm seeing a NullPointerException when calling .replaceAllIn on a string, which is non-null.

The funny thing is that I have no errors when I run the code locally, using input from disk, but I get a NullPointerException when I run the same code on AWS EMR, loading the input file from S3.

Here is the relevant code:

val HTML_TAGS_PATTERN = """<[^>]+>""".r

// other code here...

spark
.sparkContext
.textFile(pathToInputFile, numPartitions)
.filter { str => str.startsWith("  <row ") }
.toDS()
.map { str =>

  Locale.setDefault(new Locale("en", "US"))

  val parts = str.split(""""""")

  var title: String = ""
  var body: String = ""

  // some code ommitted here

  title = StringEscapeUtils.unescapeXml(title).toLowerCase.trim
  body = StringEscapeUtils.unescapeXml(body).toLowerCase // decode xml entities

  println("before replacing, body is: "+body)

  // NEXT LINE TRIGGERS NPE
  body = HTML_TAGS_PATTERN.replaceAllIn(body, " ") // take out htmltags

}

Things I've tried:

printing the string just before calling replaceAllIn to make sure it's not null.

making sure the Locale is not null

printing out the exception message, and stacktrace: it just tells me that that line is where the NullPointerException occurs. Nothing more

Things that are different between my local setup and AWS EMR:

in my local setup, I load the input file from disk, on EMR I load it from s3.

in my local setup, I run Spark in standalone mode, on EMR it's run in cluster mode.

Everything else is the same on my machine and on AWS EMR: Scala version, Spark version, Java version, Cluster configs...

I have been trying to figure this out for some hours and I can't think of anything else to try.

EDIT

I've moved the call to r() to within the map{} body, like this:

val HTML_TAGS_PATTERN = """<[^>]+>"""

// code ommited

.map{

   body = HTML_TAGS_PATTERN.r.replaceAllIn(body, " ")

 }

This also produces a NPE, wit the following stracktrace:

java.lang.NullPointerException
    at java.util.regex.Pattern.<init>(Pattern.java:1350)
    at java.util.regex.Pattern.compile(Pattern.java:1028)
    at scala.util.matching.Regex.<init>(Regex.scala:191)
    at scala.collection.immutable.StringLike$class.r(StringLike.scala:255)
    at scala.collection.immutable.StringOps.r(StringOps.scala:29)
    at scala.collection.immutable.StringLike$class.r(StringLike.scala:244)
    at scala.collection.immutable.StringOps.r(StringOps.scala:29)
    at ReadSOStanfordTokenize$$anonfun$2.apply(ReadSOStanfordTokenize.scala:102)
    at ReadSOStanfordTokenize$$anonfun$2.apply(ReadSOStanfordTokenize.scala:72)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:377)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$SingleDirectoryWriteTask.execute(FileFormatWriter.scala:243)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$org$apache$spark$sql$execution$datasources$FileFormatWriter$$executeTask$3.apply(FileFormatWriter.scala:190)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$org$apache$spar

Body:
I think you should try putting the regex inline like bellow.

This is a bit of a lame solution, you should be able to define a constant, maybe put it in a global object or something. Im not sure where you are defining it that would be a problem. But remember spark serialises the code and runs it on distributed workers, so something could be going wrong with that.

rdd.map { _ =>
   ...

   body = """<[^>]+>""".r.replaceAllIn(body, " ")

 }

I get a very similar error when I run .r on a null String.

val x: String = null
x.r
java.lang.NullPointerException
  java.util.regex.Pattern.<init>(Pattern.java:1350)
  java.util.regex.Pattern.compile(Pattern.java:1028)
  scala.util.matching.Regex.<init>(Regex.scala:223)
  scala.collection.immutable.StringLike.r(StringLike.scala:281)
  scala.collection.immutable.StringLike.r$(StringLike.scala:281)
  scala.collection.immutable.StringOps.r(StringOps.scala:29)
  scala.collection.immutable.StringLike.r(StringLike.scala:270)
  scala.collection.immutable.StringLike.r$(StringLike.scala:270)
  scala.collection.immutable.StringOps.r(StringOps.scala:29)

That error has slightly different line numbers, I think because of the scala version. Im on 2.12.2.


问:
flask javascript not found in html file
I have a basic flask folder hierarchy. I have a templets folder which holds all my HTML files, and a static folder for my javascript files. I have a javascript that builds a table. I have run this script from my html file directly by placing the script tag in the HTML file, and it works. I want to move it out of the HTML file and place it in the static folder. When I do that and try to source the file I get the error that the script is not found.

I have tried two different ways to do this and the file is still not getting found. What am i doing wrong here?

```<code><script src="{{ url_for('static', filename='/static/table.js') }}"></script>
<script src="../static/table.js"></script>
</code>```

here is the exact error I get for both of these

```<code>Failed to load resource: the server responded with a status of 404 (NOT FOUND)
</code>```

答:
If you haven't already, you need to set up routes to send the files that the webpage requests from your flask server, you can use send_from_directory to let requests get any files from a specified directory, in your case, the folder containing your javascript.</p>

```<code>@app.route('/js/<path:path>')
def send_js(path): return send_from_directory('js', path)
</code>```

Title: flask javascript not found in html file

Body:
I have a basic flask folder hierarchy. I have a templets folder which holds all my HTML files, and a static folder for my javascript files. I have a javascript that builds a table. I have run this script from my html file directly by placing the script tag in the HTML file, and it works. I want to move it out of the HTML file and place it in the static folder. When I do that and try to source the file I get the error that the script is not found.

I have tried two different ways to do this and the file is still not getting found. What am i doing wrong here?

here is the exact error I get for both of these

Failed to load resource: the server responded with a status of 404 (NOT FOUND)

Body:
If you haven't already, you need to set up routes to send the files that the webpage requests from your flask server, you can use send_from_directory to let requests get any files from a specified directory, in your case, the folder containing your javascript.

@app.route('/js/<path:path>')
def send_js(path): return send_from_directory('js', path)


问:
How do I use ng-if to display or hide input fields?
Quite new to angular JS and need some help. How do I use ng-if to display or hide different input fields? I'm currently using ng-show but it doesn't completely remove the DOM, therefore making it difficult during validation. I want the input fields displaying within a specific div to become mandatory ONLY when selected.

When I click Select Fund, I want the showme2 div to display and the fields to become mandatory. When I click Select Product, I want the showme1 div to display and the fields to become mandatory. See my current code below:

```<code><div ng-show="showme1">
         <div class="form-group">
         <h3 class="col-xs-12 col-sm-3">Add Product details</h3>
           <label class="col-xs-12 col-sm-3 control-label" for="Product1</label>
           <div class="col-xs-12 col-sm-6">
              <input type="text" name="productName" class="form-control" id="productName1" required="required" placeholder="Product 1">
           </div>
        </div>

        <<div class="form-group">
         <h3 class="col-xs-12 col-sm-3">Add Product details</h3>
           <label class="col-xs-12 col-sm-3 control-label" for="Product2</label>
           <div class="col-xs-12 col-sm-6">
              <input type="text" name="productName" class="form-control" id="productName2" required="required" placeholder="Product 2">
           </div>
        </div>

        <div class="form-group">
           <label class="col-xs-12 col-sm-3 control-label"></label>
           <div class="col-xs-12 col-sm-6" align="center" ng-click="showme2=true; showme1=false"><a>(or Select Fund)</a><br /></div>
        </div>
</div>

<div ng-show="showme2">
         <div class="form-group">
         <h3 class="col-xs-12 col-sm-3">Add Fund details</h3>
           <label class="col-xs-12 col-sm-3 control-label" for="Product1</label>
           <div class="col-xs-12 col-sm-6">
              <input type="text" name="fundName" class="form-control" id="fundName1" required="required" placeholder="Fund 1">
           </div>
        </div>

        <<div class="form-group">
         <h3 class="col-xs-12 col-sm-3">Add Product details</h3>
           <label class="col-xs-12 col-sm-3 control-label" for="Product2</label>
           <div class="col-xs-12 col-sm-6">
              <input type="text" name="fundName" class="form-control" id="fundName2" required="required" placeholder="Fund 2">
           </div>
        </div>

            <div class="form-group">
           <label class="col-xs-12 col-sm-3 control-label"></label>
           <div class="col-xs-12 col-sm-6" ng-click="showme1=true; showme2=false" align="center"><a>(or Select Product)</a></div>
        </div>
</div>
</code>```

答:
Reference this stackoverflow answer to understand how ng-if is used.

You can use ng-if to achieve if(){..} else{..} in Angular.js.

```<code><div ng-if="data.id == 5">
<!-- If block -->
</div>
<div ng-if="data.id != 5">
<!-- Your Else Block -->
</div>
</code>```

Additionally, I've modified your code snippet in a CodePen to use ng-if, see here. https://codepen.io/silicaRich/pen/PjwwPv

JS

```<code>var TestApp = angular.module("TestApp", []);

</code>```

HTML

```<code>  <html>
  <head>
  </head>
  <body ng-app='TestApp'>

    <!-- Will display if showme == true -->
    <div ng-show="showme">
         <div class="form-group">
            <h3 class="col-xs-12 col-sm-3">Add Product details // showme1</h3>
           <label class="col-xs-12 col-sm-3 control-label" for="Product1"></label>
           <div class="col-xs-12 col-sm-6">
              <input type="text" name="productName" class="form-control" id="productName1" required="required" placeholder="Product 1">
           </div>
        </div>

        <div class="form-group">
         <h3 class="col-xs-12 col-sm-3">Add Product details // showme1</h3>
           <label class="col-xs-12 col-sm-3 control-label" for="Product2"></label>
           <div class="col-xs-12 col-sm-6">
              <input type="text" name="productName" class="form-control" id="productName2" required="required" placeholder="Product 2">
           </div>
        </div>

        <div class="form-group">
           <label class="col-xs-12 col-sm-3 control-label"></label>
           <div class="col-xs-12 col-sm-6" align="center" ng-click="showme=false;"><a>(or Select Fund) // showme2</a><br /></div>
        </div>
    </div>

    <!-- Will display if showme == false -->
    <div ng-show="!showme">
         <div class="form-group">
         <h3 class="col-xs-12 col-sm-3">Add Fund details // showme2 </h3>
           <label class="col-xs-12 col-sm-3 control-label" for="Product1"></label>
           <div class="col-xs-12 col-sm-6">
              <input type="text" name="fundName" class="form-control" id="fundName1" required="required" placeholder="Fund 1">
           </div>
        </div>

        <div class="form-group">
         <h3 class="col-xs-12 col-sm-3">Add Fund details // showme2 </h3>
           <label class="col-xs-12 col-sm-3 control-label" for="Product2"></label>
           <div class="col-xs-12 col-sm-6">
              <input type="text" name="fundName" class="form-control" id="fundName2" required="required" placeholder="Fund 2">
           </div>
        </div>

          <div class="form-group">
           <label class="col-xs-12 col-sm-3 control-label"></label>
           <div class="col-xs-12 col-sm-6" ng-click="showme=true;" align="center"><a>(or Select Product) // showme1</a></div>
        </div>
   </div>

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

Hope this helps.

Body:
Quite new to angular JS and need some help. How do I use ng-if to display or hide different input fields? I'm currently using ng-show but it doesn't completely remove the DOM, therefore making it difficult during validation. I want the input fields displaying within a specific div to become mandatory ONLY when selected.

When I click Select Fund, I want the showme2 div to display and the fields to become mandatory. When I click Select Product, I want the showme1 div to display and the fields to become mandatory. See my current code below:

Add Product details

           <label class="col-xs-12 col-sm-3 control-label" for="Product1

              <input type="text" name="productName" class="form-control" id="productName1" required="required" placeholder="Product 1">

        <

Add Product details

           <label class="col-xs-12 col-sm-3 control-label" for="Product2

              <input type="text" name="productName" class="form-control" id="productName2" required="required" placeholder="Product 2">

(or Select Fund)

Add Fund details

           <label class="col-xs-12 col-sm-3 control-label" for="Product1

              <input type="text" name="fundName" class="form-control" id="fundName1" required="required" placeholder="Fund 1">

        <

Add Product details

           <label class="col-xs-12 col-sm-3 control-label" for="Product2

              <input type="text" name="fundName" class="form-control" id="fundName2" required="required" placeholder="Fund 2">

(or Select Product)

Body:
Reference this stackoverflow answer to understand how ng-if is used.

You can use ng-if to achieve if(){..} else{..} in Angular.js.

<div ng-if="data.id == 5">
<!-- If block -->
</div>
<div ng-if="data.id != 5">
<!-- Your Else Block -->
</div>

Additionally, I've modified your code snippet in a CodePen to use ng-if, see here. https://codepen.io/silicaRich/pen/PjwwPv

JS

var TestApp = angular.module("TestApp", []);

HTML

  <html>
  <head>
  </head>
  <body ng-app='TestApp'>

    <!-- Will display if showme == true -->
    <div ng-show="showme">
         <div class="form-group">
            <h3 class="col-xs-12 col-sm-3">Add Product details // showme1</h3>
           <label class="col-xs-12 col-sm-3 control-label" for="Product1"></label>
           <div class="col-xs-12 col-sm-6">
              <input type="text" name="productName" class="form-control" id="productName1" required="required" placeholder="Product 1">
           </div>
        </div>

        <div class="form-group">
         <h3 class="col-xs-12 col-sm-3">Add Product details // showme1</h3>
           <label class="col-xs-12 col-sm-3 control-label" for="Product2"></label>
           <div class="col-xs-12 col-sm-6">
              <input type="text" name="productName" class="form-control" id="productName2" required="required" placeholder="Product 2">
           </div>
        </div>

        <div class="form-group">
           <label class="col-xs-12 col-sm-3 control-label"></label>
           <div class="col-xs-12 col-sm-6" align="center" ng-click="showme=false;"><a>(or Select Fund) // showme2</a><br /></div>
        </div>
    </div>

    <!-- Will display if showme == false -->
    <div ng-show="!showme">
         <div class="form-group">
         <h3 class="col-xs-12 col-sm-3">Add Fund details // showme2 </h3>
           <label class="col-xs-12 col-sm-3 control-label" for="Product1"></label>
           <div class="col-xs-12 col-sm-6">
              <input type="text" name="fundName" class="form-control" id="fundName1" required="required" placeholder="Fund 1">
           </div>
        </div>

        <div class="form-group">
         <h3 class="col-xs-12 col-sm-3">Add Fund details // showme2 </h3>
           <label class="col-xs-12 col-sm-3 control-label" for="Product2"></label>
           <div class="col-xs-12 col-sm-6">
              <input type="text" name="fundName" class="form-control" id="fundName2" required="required" placeholder="Fund 2">
           </div>
        </div>

          <div class="form-group">
           <label class="col-xs-12 col-sm-3 control-label"></label>
           <div class="col-xs-12 col-sm-6" ng-click="showme=true;" align="center"><a>(or Select Product) // showme1</a></div>
        </div>
   </div>

  </body>
  </html>

Hope this helps.

ContentLicense: CC BY-SA 4.0


问:
Find a character in a list of words
I am trying to find a specific character in a list of words and then print all the words that match. for example, I have a list of 6 words. I would like to find a way to select all the words with a ('.') (fullstop) in them and transfer them to another list.

Example:

```<code>List ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
</code>```

I would like it to find Charlie and its position in the list

I mostly just need the if statement for it
Thanks in advance!

This is what I have so far

```<code>sent = str(input('enter sentance '))
words = sent.split()
print (words)
</code>```

答:
If you want it without list comprehension:

```<code>sent = input('Enter sentence > ')
words = sent.split()
for word in words:
    if "." in word:
        print(word)
</code>```

Also, you if you're in Python 2.7, use raw_input, input for Python 3.

Title: Find a character in a list of words

Body:
I am trying to find a specific character in a list of words and then print all the words that match. for example, I have a list of 6 words. I would like to find a way to select all the words with a ('.') (fullstop) in them and transfer them to another list.

Example:

List ['alpha', 'bravo', 'charlie.', 'delta', 'echo']

I would like it to find Charlie and its position in the list

I mostly just need the if statement for it
Thanks in advance!

This is what I have so far

sent = str(input('enter sentance '))
words = sent.split()
print (words)

Body:
If you want it without list comprehension:

sent = input('Enter sentence > ')
words = sent.split()
for word in words:
    if "." in word:
        print(word)

Also, you if you're in Python 2.7, use raw_input, input for Python 3.


问:
Modify VBScript to stop excel dialog boxes from appearing
I'm trying to use a vbscript to open an excel spreadsheet, run a macro, and save the sheet for a daily inventory update.  I found the following code here and it is working fine for me, but i want it to run automatically without throwing up a prompts that I'm getting: "This will cancel a pending data refresh" (related to the macro I'm guessing)

I can't seem to find the right code to get this to happen.  Any help would be appreciated.

Here is the existing vbscript:

```<code>Option Explicit

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open("C:\testfiles\Daily Update.xlsm", 0, False)

xlApp.Run "RefreshData"
xlBook.Close(False)
xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing

WScript.Echo "Daily Update Finished."
WScript.Quit
</code>```

and here is the Excel Macro:

```<code>Sub RefreshData()
'
' RefreshData Macro
'
' Keyboard Shortcut: Ctrl+Shift+O
'
    ActiveWorkbook.RefreshAll
    ActiveWorkbook.Save
End Sub
</code>```

答:
xlapp.displayalerts = false in the vbscript OR application.displayalerts = false in the module will suppress the alerts.

Make sure you set it back to true at the end of the code.

Body:
I'm trying to use a vbscript to open an excel spreadsheet, run a macro, and save the sheet for a daily inventory update.  I found the following code here and it is working fine for me, but i want it to run automatically without throwing up a prompts that I'm getting: "This will cancel a pending data refresh" (related to the macro I'm guessing)

I can't seem to find the right code to get this to happen.  Any help would be appreciated.

Here is the existing vbscript:

Option Explicit

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open("C:\testfiles\Daily Update.xlsm", 0, False)

xlApp.Run "RefreshData"
xlBook.Close(False)
xlApp.Quit

Set xlBook = Nothing
Set xlApp = Nothing

WScript.Echo "Daily Update Finished."
WScript.Quit

and here is the Excel Macro:

Sub RefreshData()
'
' RefreshData Macro
'
' Keyboard Shortcut: Ctrl+Shift+O
'
    ActiveWorkbook.RefreshAll
    ActiveWorkbook.Save
End Sub


问:
Using the AutoComplete feature of ComboBox, while limiting values to those in the list?
In WinForms 2.0, a ComboBox has an Auto-Complete feature, that displays a custom Drop-Down list with only the values that start with the entered text.

However, if I want to limit valid values to only those that appear in the ComboBox's list of items, I can do that by setting the DropDownStyle to DropDownList, which stops the user from entering a value.

However, now I can't use the Auto-Complete feature, which requires user input.

Is there another way to limit input to the list, while still allowing use of the Auto-Complete feature? Note that I have seen some custom solutions for this, but I really like the way the matching Auto-Complete items are displayed in a Drop-Down list, and sorted even though the original list may not be.

EDIT: I have thought about just validating the entered value, i.e. testing user input if it is valid in, say, the TextChanged event, or even using the Validating event. The question then is what is the expected behavior? Do I clear their value (an empty value is also invalid), or do I use a default value? Closest matching value?

P.s. Is there any other tags that I could add to this question?

答: The way I've done this is to check the value against the list of possible values when they leave the box and don't let them leave an invalid value.  I don't know how you would want to handle it when you find that they've input an invalid value, but this is what I've done in the past.</p>

OwnerDisplayName: Schmuli

LastEditorDisplayName: DJ

OwnerDisplayName: Aaron Smith


问:
100% foolproof c# ftp file transfer code (with transactions if possible)
I want to write a small c# ftp client class library which basically needs to transfer files to a ftp location.

What I want, is a 100% foolproof code, where I can get some sort of acknowledgement that the ftp file transfer has been either 100% successful or failed.

No resume support is required.

Good to have (but secondary):

Some sort of distributed transaction where only if the file transfer is successful for a file, i update my db for that particular file with 1 (true)... if it is failed, then db to be updated with 0 (false).

But suppose the ftp file transfer was successful, but for whatever reasons the db could not be updated, then the file over ftp should be deleted - I can easily do this using dirty c# code (where i manually try to delete the file if db update failed).

But what I am exactly looking for is file system based transaction over ftp... so both the file transfer as well as db update is not committed until both are successful (hence no need for manual delete).

Any clues?

答:
.NET has an FTP client you can use. I don't know how robust it is in the face of FTP server quirks; you'll have to test it against your customer's FTP server. As for verifying that the upload was successful, the only tools you have are (1) making sure there was no transport error during the upload, (2) validating the file size when you're done.

The FTP server isn't going to support transactions, so you're going to have to manage that yourself, but this isn't really a complicated scenario. Use a transaction for the DB update; backing out the FTP upload is one call.


问:
How to see if form has been filled out in rails?
I have functions in my userinfo model and employer model to see if their respective forms have been filled out.
Right now, my userinfo model looks like this:

```<code>class Userinfo < ActiveRecord::Base
    belongs_to :user

    def info_complete?
        name? && email? && college? && gpa? && major?
    end

end
</code>```

And the emloyer model looks like this:

```<code>class Employer < ActiveRecord::Base
    belongs_to :user

    def info_complete?
        name? && company? && position? && number? && email?
    end
end
</code>```

The navbar in my layout/application.html.erb where the navbar code goes is this:

```<code>        <% if user_signed_in? %>
            <%if current_user.employer(&:info_complete?) %>
                <li><p>Employer form has been filled out</p></li>
            <%elsif current_user.userinfo(&:info_complete?) %>
                <li><p>Userinfo form has been filled out</p></li>
            <%else%>
                <li><p>Nothing has been filled out</p></li>
            <%end%>
            <li><%= link_to "Sign Out", destroy_user_session_path, method: :delete %></li>
        <% else %>
            <li><%= link_to "Log In", new_user_session_path %></li>
            <li><%= link_to "Sign Up", new_user_registration_path %></li>
        <% end %>
</code>```

As you can see, this is just for testing. I display a sentence to see if my logic works.

Then the userinfo/new form is this:

And the employer/new form is this:

As you can see in both the form pictures, in the navbar, it says the form has been filled out when the user just gets there. No information has been entered. Why does it pass "true" to the "info_complete?" functions in my models even though no data has been entered yet?

答:
here is your models..

user_info.rb

```<code>class Userinfo < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :name, :email, :college, :gpa, :major
end
</code>```

employer.rb

```<code>class Employer < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :name, :company, :position, :number, :email
end
</code>```

Controllers.

employers_controller.rb

```<code>Class EmployersController < ApplicationController
  def new
    @employer = Employer.new
  end

  def create
    @employer = Employer.new(valid_params)
    respond_to do |format|
      if @employer.save
        format.html { redirect_to root_path }
      else
        format.html { render :new }
      end
    end
  end

  private

  def valid_params
    params.require(:employer).permit(:name, :company, :position, :number, :email)
  end
end
</code>```

views.
employers/new.html.erb

```<code><%= render 'form' %>
</code>```

employers/_form.html.erb

```<code><% if @employers.errors.any %>
  <% @employers.full_messages.each do |m| %>
    <p><%= m %></p>
  <% end %>
<% end %>
</code>```

do the same for the user_info..

Body:
I have functions in my userinfo model and employer model to see if their respective forms have been filled out.
Right now, my userinfo model looks like this:

class Userinfo < ActiveRecord::Base
    belongs_to :user

    def info_complete?
        name? && email? && college? && gpa? && major?
    end

end

And the emloyer model looks like this:

class Employer < ActiveRecord::Base
    belongs_to :user

    def info_complete?
        name? && company? && position? && number? && email?
    end
end

The navbar in my layout/application.html.erb where the navbar code goes is this:

        <% if user_signed_in? %>
            <%if current_user.employer(&:info_complete?) %>

Employer form has been filled out

            <%elsif current_user.userinfo(&:info_complete?) %>

Userinfo form has been filled out

            <%else%>

Nothing has been filled out

            <%end%>

<%= link_to "Sign Out", destroy_user_session_path, method: :delete %>

        <% else %>

<%= link_to "Log In", new_user_session_path %>

<%= link_to "Sign Up", new_user_registration_path %>

        <% end %>

As you can see, this is just for testing. I display a sentence to see if my logic works.

Then the userinfo/new form is this:

And the employer/new form is this:

As you can see in both the form pictures, in the navbar, it says the form has been filled out when the user just gets there. No information has been entered. Why does it pass "true" to the "info_complete?" functions in my models even though no data has been entered yet?

Body:
here is your models..

user_info.rb

class Userinfo < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :name, :email, :college, :gpa, :major
end

employer.rb

class Employer < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :name, :company, :position, :number, :email
end

Controllers.

employers_controller.rb

Class EmployersController < ApplicationController
  def new
    @employer = Employer.new
  end

  def create
    @employer = Employer.new(valid_params)
    respond_to do |format|
      if @employer.save
        format.html { redirect_to root_path }
      else
        format.html { render :new }
      end
    end
  end

  private

  def valid_params
    params.require(:employer).permit(:name, :company, :position, :number, :email)
  end
end

views.
employers/new.html.erb

<%= render 'form' %>

employers/_form.html.erb

<% if @employers.errors.any %>
  <% @employers.full_messages.each do |m| %>
    <p><%= m %></p>
  <% end %>
<% end %>

do the same for the user_info..


问:
css percentage based background
How can I show a div with some text (which fills the div completely in width) and then show a background color which is only 40%, without obstructing the text.

The following is problematic because the text is within the inner div. I want it in the outer div so to speak.

This is a much longer text and takes up a lot of space

```

答:
You can make the inner DIV absolutely positioned, with a negative z-index and the desired width restriction as in the following snippet.

Note: The inner DIV is empty, the text is only in the outer DIV, not in the inner one)

.outer {
  position: relative;
}

.inner {
  position: absolute;
  top: 0;
  left: 0;
  width: 35%;
  height: 100%;
  background: #EAFEE2;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
<div class="inner"></div>
This is a much longer text and takes up a lot of space
</div></code>```

Title: css percentage based background

Body:
You can make the inner DIV absolutely positioned, with a negative z-index and the desired width restriction as in the following snippet.

Note: The inner DIV is empty, the text is only in the outer DIV, not in the inner one)

.outer {
  position: relative;
}

.inner {
  position: absolute;
  top: 0;
  left: 0;
  width: 35%;
  height: 100%;
  background: #EAFEE2;
  z-index: -1;
}

<div class="outer">
<div class="inner"></div>
This is a much longer text and takes up a lot of space
</div>


问:
concurrent SQL statements in different transanctions
Reading up the documentation of PL-SQL CREATE TRIGGER statement in ORACLE, I went through the following bit of information:

When a trigger fires, tables that the trigger references might be
  undergoing changes made by SQL statements in other users'
  transactions. SQL statements running in triggers follow the same rules
  that standalone SQL statements do.

It basically says the rules that would apply to two conflicting standalone SQL statements (running at the same time) are unchanged when one of the statements is performed from within a trigger.

So we have some "usual" rules about concurrent transactions and, as for these rules, the following two are mentioned:

Specifically:

Queries in the trigger see the current read-consistent materialized
  view of referenced tables and any data changed in the same
  transaction.

Updates in the trigger wait for existing data locks to be released
  before proceeding.

These two rules look like "obscure" to non-expert users.

What do they mean more precisely?

答:
Queries in the trigger see the current read-consistent materialized
  view of referenced tables and any data changed in the same
  transaction.

This means the data the trigger sees, like if it does a SELECT on a different table, represents the state of that table when the statement started running. The trigger does not see rows that have been changed by other sessions that have not been committed yet.

Updates in the trigger wait for existing data locks to be released
  before proceeding.

When an Oracle statement modifies a row, the row is locked against other people changing it until that session either commits or rolls back its transaction. So if you do an insert on table A, your trigger does an update on table B, but someone else's session has already done an update on table B for that same row, your transaction will wait until they commit or rollback.


答:
Assume you have a list l = ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
Then you can create a list with all words containing '.' in it by doing filter like below:

```<code>l = ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
list_with_dot = [x for x in l if x.find('.') != -1]
</code>```

Title: Find a character in a list of words

Body:
Assume you have a list l = ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
Then you can create a list with all words containing '.' in it by doing filter like below:

l = ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
list_with_dot = [x for x in l if x.find('.') != -1]


问:
Explain behaviors in mapping auto incremented composite id sequence with Hibernate
I have a table

```<code>CREATE TABLE `SomeEntity` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `subid` int(11) NOT NULL DEFAULT '0',
     PRIMARY KEY (`id`,`subid`),
</code>```

I have a entity class with an auto increment field in it.I want to read auto increment id assigned to it when it gets persisted

Annotations on getter are as below

```<code>  private long id;
   private int subid;
  @Id
  @GeneratedValue **//How do i correct this to have multiple rows with same id and different subid**
  @Column(name = "id")
  public long getId() {
    return id;
  }

  @Id
  @Column(name = "subid")
  public int getSubid() {
    return subid;
  }
</code>```

I want to have entities as

```<code>id 1 subid 0
id 1 subid 1
id 1 subid 2
id 2 subid 0
</code>```

subid is default 0 in database and i am incrementing it programmatically on updates to that row.
I tried the solution as in this SO post
JPA - Returning an auto generated id after persist()

```<code> @Transactional
  @Override
  public void daoSaveEntity(SomeEntity entity) {
    entityManager.persist(entity);
  }
</code>```

Now outside this transaction I am trying to get the auto increment id assigned

```<code>      @Override
      public long serviceSaveEntity(SomeEntity entity) {
        dao.daoSaveEntity(entity);
        return entity.getId();
      }
</code>```

I am calling this from a web service

```<code>  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public Response createEntity(SomeEntity entity) {
</code>```

The update method is as below

```<code> @Transactional
  public void updateReportJob(SomeEntity someEntity) {

    Query query =
        entityManager
.createQuery("UPDATE SomeEntity SET state=:newState WHERE id = :id");
    query.setParameter("newState","PASSIVE");
    query.setParameter("id", id);
    query.executeUpdate();
    double rand = Math.random();
    int i = (int) (rand * 300);
    try {
      Thread.sleep(i);  //only to simulate concurrency issues
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    List<Integer> resList =
        entityManager.createQuery("select max(subid) from SomeEntity WHERE id = :id")
            .setParameter("id", jobId).getResultList();
    // Increment old subid by 1
    int subid = resList.get(0);
    SomeEntity.setsubid(subid + 1);
    SomeEntity.setState("ACTIVE");
    // entityManager.merge(SomeEntity);
    entityManager.persist(SomeEntity);
  }
</code>```

i send N concurrent updates from N threads for entity with Id 1 and few other properties as below

SomeEnity entity = new SomeEntity();

```<code> entity.setId(1);
  long num = Thread.currentThread().getId();
  entity.setFieldOne("FieldOne" + num);
  entity.setFieldTwo("" + i);
  entity.setFieldThree("" + j);
  i++;
  j++;
</code>```

Case 1 with  With  @Id on id  and @Id  annotation on subid and  `entityManager.persist' in update
When i ran with 300 threads some failed with connection exception "too many connections" The databse state is

```<code>   id 1 subid 0
   id 1 subid 1
   id 1 subid 2
   ..  ....
   id 1 subid 150
</code>```

the subid is always incremental ,the race condition is only that which one will be ACTIVE is undefined because of race condition

Case 2 with  With  @Id on id and @Id  annotation on subid and `entityManager.merge' in update

id 1 subid 0
       id 1 subid 0
       id 2 subid 0
       ..  ....
       id 151 subid 0 (Perhaps just a co-incidence that one more thread  than case 1 was successful? )

Case 3 With @GeneratedValue and @Id on id and **NO @Id  annotation on subid  and entityManager.persist in update**
 exception -- Detached entity passed to persist

Case 3 With @GeneratedValue and @Id on id and **NO @Id  annotation on subid  and entityManager.merge in update**
 if update is run sequentially the database state is

```<code>id 1 subid 0
</code>```

after next update

```<code>  private long id;
   private int subid;
  @Id
  @GeneratedValue **//How do i correct this to have multiple rows with same id and different subid**
  @Column(name = "id")
  public long getId() {
    return id;
  }

  @Id
  @Column(name = "subid")
  public int getSubid() {
    return subid;
  }
</code>```0

after each update same row is updated (leading to only one row at a time)

```<code>  private long id;
   private int subid;
  @Id
  @GeneratedValue **//How do i correct this to have multiple rows with same id and different subid**
  @Column(name = "id")
  public long getId() {
    return id;
  }

  @Id
  @Column(name = "subid")
  public int getSubid() {
    return subid;
  }
</code>```1

Case 4 same as Case 3 with Concurrent updates
  if run concurrently(with 300 threads) i get the below exception

```<code>  private long id;
   private int subid;
  @Id
  @GeneratedValue **//How do i correct this to have multiple rows with same id and different subid**
  @Column(name = "id")
  public long getId() {
    return id;
  }

  @Id
  @Column(name = "subid")
  public int getSubid() {
    return subid;
  }
</code>```2

database state is
  id 1 subid 2     (Only one thread would have been successful but because of race condition updated subid from 0 to 2 )

Case 5 With @GeneratedValue and @Id on id and  @Id  annotation on subid

Create also fails with subid org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of SomeEntity.id

Please explain the causes.From the javadoc of methods i know that

persist - Make an instance managed and persistent.

merge - Merge the state of the given entity into the current persistence context.

My question is more towards how hibernate manages the annotations.
Why is there be a detached entity exception in case 3 when the session is not closed yet?
Why is there a IllegalArgumentException in case 5 ?

I am using hibernate 3.6  mysql 5 and Spring 4
Also please suggest a way achieve such incremental id and subid.(Using custom SelectGenerator ,with a demo implementation or any other way without doing a column concat)

答:
Just because no one mentioned this.

I have a table

```<code>CREATE TABLE `SomeEntity` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`subid` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`,`subid`),
</code>```

I have a entity class with an auto increment field in it.

[..]

subid is default 0 in database and i am incrementing it programmatically on updates to that row.

To me this sounds a lot like versioning.

There is actually an annotation that will do exactly what you want, without you having to write any code:

@Version

A versioned entity is marked with the @Version annotation,
  as illustrated in the following code snippet:

```<code>public class User {
    @ID Integer id;
    @Version Integer version;
}
</code>```

and its corresponding database schema has a version column,
  such as that created by the following SQL statement:

```<code>CREATE TABLE `User` (
    `id` NUMBER NOT NULL,
    `version` NUMBER,
    PRIMARY KEY (`id`)
);
</code>```

The version attribute can be an int, short, long, or timestamp.
  It is incremented when a transaction successfully commits.
  This results in an SQL operation such as the following:

```<code>UPDATE User SET ..., version = version + 1
WHERE id = ? AND version = readVersion
</code>```

source: blogs.oracle.com (emphasis mine)

I modified the example a bit. I recommend you to use the box types Integer, Long etc for database fields. Even id, which is NOT NULL, will be null before you save the entity for the first time. I find that using box types makes it explicit that these fields can and will be null.

Body:
I have a table

CREATE TABLE `SomeEntity` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `subid` int(11) NOT NULL DEFAULT '0',
     PRIMARY KEY (`id`,`subid`),

I have a entity class with an auto increment field in it.I want to read auto increment id assigned to it when it gets persisted

Annotations on getter are as below

  private long id;
   private int subid;
  @Id
  @GeneratedValue **//How do i correct this to have multiple rows with same id and different subid**
  @Column(name = "id")
  public long getId() {
    return id;
  }

  @Id
  @Column(name = "subid")
  public int getSubid() {
    return subid;
  }

I want to have entities as

id 1 subid 0
id 1 subid 1
id 1 subid 2
id 2 subid 0

subid is default 0 in database and i am incrementing it programmatically on updates to that row.
I tried the solution as in this SO post
JPA - Returning an auto generated id after persist()

 @Transactional
  @Override
  public void daoSaveEntity(SomeEntity entity) {
    entityManager.persist(entity);
  }

Now outside this transaction I am trying to get the auto increment id assigned

      @Override
      public long serviceSaveEntity(SomeEntity entity) {
        dao.daoSaveEntity(entity);
        return entity.getId();
      }

I am calling this from a web service

  @POST
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public Response createEntity(SomeEntity entity) {

The update method is as below

 @Transactional
  public void updateReportJob(SomeEntity someEntity) {

    Query query =
        entityManager
.createQuery("UPDATE SomeEntity SET state=:newState WHERE id = :id");
    query.setParameter("newState","PASSIVE");
    query.setParameter("id", id);
    query.executeUpdate();
    double rand = Math.random();
    int i = (int) (rand * 300);
    try {
      Thread.sleep(i);  //only to simulate concurrency issues
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    List<Integer> resList =
        entityManager.createQuery("select max(subid) from SomeEntity WHERE id = :id")
            .setParameter("id", jobId).getResultList();
    // Increment old subid by 1
    int subid = resList.get(0);
    SomeEntity.setsubid(subid + 1);
    SomeEntity.setState("ACTIVE");
    // entityManager.merge(SomeEntity);
    entityManager.persist(SomeEntity);
  }

i send N concurrent updates from N threads for entity with Id 1 and few other properties as below

SomeEnity entity = new SomeEntity();

 entity.setId(1);
  long num = Thread.currentThread().getId();
  entity.setFieldOne("FieldOne" + num);
  entity.setFieldTwo("" + i);
  entity.setFieldThree("" + j);
  i++;
  j++;

Case 1 with  With  @Id on id  and @Id  annotation on subid and  `entityManager.persist' in update
When i ran with 300 threads some failed with connection exception "too many connections" The databse state is

   id 1 subid 0
   id 1 subid 1
   id 1 subid 2
   ..  ....
   id 1 subid 150

the subid is always incremental ,the race condition is only that which one will be ACTIVE is undefined because of race condition

Case 2 with  With  @Id on id and @Id  annotation on subid and `entityManager.merge' in update

id 1 subid 0
       id 1 subid 0
       id 2 subid 0
       ..  ....
       id 151 subid 0 (Perhaps just a co-incidence that one more thread  than case 1 was successful? )

Case 3 With @GeneratedValue and @Id on id and **NO @Id  annotation on subid  and entityManager.persist in update**
 exception -- Detached entity passed to persist

Case 3 With @GeneratedValue and @Id on id and **NO @Id  annotation on subid  and entityManager.merge in update**
 if update is run sequentially the database state is

id 1 subid 0

after next update

id 1 subid 1

after each update same row is updated (leading to only one row at a time)

id 1 subid 2

Case 4 same as Case 3 with Concurrent updates
  if run concurrently(with 300 threads) i get the below exception

 org.hibernate.HibernateException: More than one row with the given identifier was found: 1

database state is
  id 1 subid 2     (Only one thread would have been successful but because of race condition updated subid from 0 to 2 )

Case 5 With @GeneratedValue and @Id on id and  @Id  annotation on subid

Create also fails with subid org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of SomeEntity.id

Please explain the causes.From the javadoc of methods i know that

persist - Make an instance managed and persistent.

merge - Merge the state of the given entity into the current persistence context.

My question is more towards how hibernate manages the annotations.
Why is there be a detached entity exception in case 3 when the session is not closed yet?
Why is there a IllegalArgumentException in case 5 ?

I am using hibernate 3.6  mysql 5 and Spring 4
Also please suggest a way achieve such incremental id and subid.(Using custom SelectGenerator ,with a demo implementation or any other way without doing a column concat)

Body:
Just because no one mentioned this.

I have a table

CREATE TABLE `SomeEntity` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`subid` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`,`subid`),

I have a entity class with an auto increment field in it.

[..]

subid is default 0 in database and i am incrementing it programmatically on updates to that row.

To me this sounds a lot like versioning.

There is actually an annotation that will do exactly what you want, without you having to write any code:

@Version

A versioned entity is marked with the @Version annotation,
  as illustrated in the following code snippet:

public class User {
    @ID Integer id;
    @Version Integer version;
}

and its corresponding database schema has a version column,
  such as that created by the following SQL statement:

CREATE TABLE `User` (
    `id` NUMBER NOT NULL,
    `version` NUMBER,
    PRIMARY KEY (`id`)
);

The version attribute can be an int, short, long, or timestamp.
  It is incremented when a transaction successfully commits.
  This results in an SQL operation such as the following:

UPDATE User SET ..., version = version + 1
WHERE id = ? AND version = readVersion

source: blogs.oracle.com (emphasis mine)

I modified the example a bit. I recommend you to use the box types Integer, Long etc for database fields. Even id, which is NOT NULL, will be null before you save the entity for the first time. I find that using box types makes it explicit that these fields can and will be null.


问:
Human Interface Device (HID) in Xamarin/Xamarin.forms
I am attempting to develop a app to comunicate with bluetooth LE crossplataform. To do it, I'm trying to start with xamarin.forms and using 2 samples groups

A sample of android App by Microchips and Monkey.robotic

A sample of UWP project to connect by HID (I have a device to do it as a dongle service)

The sample of microsoft was:
https://github.com/oldnewthing/Windows-universal-samples/tree/master/Samples/CustomHidDeviceAccess

I'll use a Conditional Compilation to do both situations, but when I try to use it into Xamarin there are troubles around  some UWP references that didn't work , it is not compatible with xamarin and several await/async errors.

When I try to force by the other side (like .NET Standard 1.6) it didn't work either.

What is really compatible with (xamarin/xamarin.forms)2.+ ?

Is it possible to do, a HID connection using xamarin.forms design?

Thanks in advance.

答:
I think HID project should be referenced by UWP project. In PCL(Xamarin.Forms) project, you should use DependencyService to use that
https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/dependency-service/introduction/</p>


问:
Writing CSV file with arabic unicode in list
I am trying to write a csv file that contains a number of lists.  Within some of the lists, there is unicode that contains arabic.  For example:

```<code>list1 = ['No data'], list2 = ['data1', 'data2, '\\u...', '\\u...']
</code>```

The unicode also contains an extra backslash.  How would I create a csv, or change my code, to convert the unicode to arabic characters?

答:
You can encode/decode the char by using the following function :

```<code>your_string.encode("utf-8").decode('unicode-escape')
</code>```

for example:

```<code>test = "test \\u0643\\uFEBD"
print(test.encode("utf-8").decode('unicode-escape')) => test كﺽ
</code>```

EDIT 1:
to convert all your arrays you can either loop thru all the elements and convert them 1 by 1 or use map function like :

```<code>def f(string):
    return string.encode("utf-8").decode('unicode-escape')

for sublist in main_list:
    sublist = list(map(f, sublist))
</code>```

Body:
I am trying to write a csv file that contains a number of lists.  Within some of the lists, there is unicode that contains arabic.  For example:

list1 = ['No data'], list2 = ['data1', 'data2, '\\u...', '\\u...']

The unicode also contains an extra backslash.  How would I create a csv, or change my code, to convert the unicode to arabic characters?

Body:
You can encode/decode the char by using the following function :

your_string.encode("utf-8").decode('unicode-escape')

for example:

test = "test \\u0643\\uFEBD"
print(test.encode("utf-8").decode('unicode-escape')) => test كﺽ

EDIT 1:
to convert all your arrays you can either loop thru all the elements and convert them 1 by 1 or use map function like :

def f(string):
    return string.encode("utf-8").decode('unicode-escape')

for sublist in main_list:
    sublist = list(map(f, sublist))


问:
Print when textarea has overflow
I have a form with some text areas that allow a scroll bar when the text exceeds the text box. The user would like to be able to print the screen, and this text is not visible. How do I make all of the text visible for just printing? Am I better of making a print to pdf link or something?</p>

答:
Define a separate CSS for print media like this <link rel="stylesheet" href="print.css" type="text/css" media="print" /> and for the text area, define the overflow attribute as

```<code>overflow: visible;
</code>```

Title: Print when textarea has overflow

Body:
Define a separate CSS for print media like this <link rel="stylesheet" href="print.css" type="text/css" media="print" /> and for the text area, define the overflow attribute as

overflow: visible;


问:
Displaying text from file into a label or form background. Can't find answer to this
I am trying to display text from a .txt file into a label or the form itself without having to press a button. I want it to display the entire file as default when it opens, instead of opening it through a button.

I am not using textbox because I do not want the user to be able to edit the text. Please help. Thank you for your time!

答:
I think you should use the Label control and set the Label.Text in your page load method:

This should help:

Here's how you can use the Page_Load event, just put your code to load data in your Page_Load(object sender, EventArgs e) function:
https://msdn.microsoft.com/en-us/library/system.web.ui.page(v=vs.110).aspx#Anchor_10

MSDN suggests a label should be used if you want to show text on the page using the server code:
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.label(v=vs.110).aspx


问:
How to setup Webpack to change a specific config file for dev or production?
I have 2 files, config_local.js and config_prod.js.

How would you pass in a variable into webpack to basically generate a new file named config_api.js from either the local one or the production one.

config_local.js

```<code>"api": {
  "login": "http://localhost/app/api/login/",
  "users": "http://localhost/app/api/users/"
}
</code>```

config_prod.js

```<code>"api": {
  "login": "/app/api/login/",
  "users": "/app/api/users/"
}
</code>```

Then inside of my services/api.js file

```<code>import axios from 'axios'

export const userLogin = (username, password) => {
    const post_data = { username, password };
    return axios.post('http://localhost/app/api/login', post_data)
        .then(res => res);
};
</code>```

I could do something like so:

```<code>import axios from 'axios'
import api from 'config_api'

export const userLogin = (username, password) => {
    const post_data = { username, password };
    return axios.post(api.login, post_data)  // <--
        .then(res => res);
};
</code>```

答:
In package.json you can use scripts or even at commandline you can use environment variable.s

```<code> "scripts": {
    "dev": "NODE_ENV=development webpack",
    "production": "NODE_ENV=production webpack",
    "watch": "npm run dev -- --watch"
  },
</code>```

In webpack.config.js you can use

```<code>const inProduction = process.env.NODE_ENV === 'production';
const inDevelopment = process.env.NODE_ENV === "development";

if(inProduction)
//do this
if(inDevelopment)
//do that
</code>```

webpack by default looks for weback.config.js however for custom config you can use
webpack --config config_local.js

Body:
I have 2 files, config_local.js and config_prod.js.

How would you pass in a variable into webpack to basically generate a new file named config_api.js from either the local one or the production one.

config_local.js

"api": {
  "login": "http://localhost/app/api/login/",
  "users": "http://localhost/app/api/users/"
}

config_prod.js

"api": {
  "login": "/app/api/login/",
  "users": "/app/api/users/"
}

Then inside of my services/api.js file

import axios from 'axios'

export const userLogin = (username, password) => {
    const post_data = { username, password };
    return axios.post('http://localhost/app/api/login', post_data)
        .then(res => res);
};

I could do something like so:

import axios from 'axios'
import api from 'config_api'

export const userLogin = (username, password) => {
    const post_data = { username, password };
    return axios.post(api.login, post_data)  // <--
        .then(res => res);
};

Body:
In package.json you can use scripts or even at commandline you can use environment variable.s

 "scripts": {
    "dev": "NODE_ENV=development webpack",
    "production": "NODE_ENV=production webpack",
    "watch": "npm run dev -- --watch"
  },

In webpack.config.js you can use

const inProduction = process.env.NODE_ENV === 'production';
const inDevelopment = process.env.NODE_ENV === "development";

if(inProduction)
//do this
if(inDevelopment)
//do that

webpack by default looks for weback.config.js however for custom config you can use
webpack --config config_local.js