问:
select query to get all values based on distinct values using linq
I have n number of services and under each service there will be 2 routes(some times more than 2). Under each route there are n number of stops. I am getting values from db as  a table in below column order
ServiceId, Service Name,serviceLine color,RouteId, Route Name, Stop Id, Stop Name, Latitude, Longitude.

I want to convert it an object list of below format

 public class Service
    {
        public string ServiceId { get; set; }
        public string ServiceName { get; set; }
        public string ServiceLineColor { get; set; }
        public List<RouteData> RouteList { get; set; }
    }
    public class RouteData
    {
        public string RouteId { get; set; }
        public string RouteCode { get; set; }
        public string RouteName { get; set; }
        public List<StopData> stopList { get; set; }
    }
    public class StopData
    {
        public string StopCode { get; set; }
        public string StopName { get; set; }
        public string Latitude { get; set; }
        public string Longitude { get; set; }
        public string StopType { get; set; }
    }```

Is there any easy way in linq to convert data in to below format? I wanted to avoid looping.. since i am getting nearly 1k records from db. Please help me to solve this issue.

Or is it best to use db calls to format data. i didn't prefer that because if there is 50 services i need to do 50 db calls and again have to do data formatting logic.

答:
You have a number of stops, and for each stop entry in database you have to map it to a C# object. In this case, looping is inevitable, as far as I see. Linq, and eg. entity framework, use looping internally.

One option is to use entity framework or Linq to SQL. It will give you strong type classes representing each DB table. But you have to change your DB schema and use foreign keys to link service, route, and stops.

C# code would look exactly like yours, which is auto generated by entity framework and in-sync with DB schema.

Second option is to convert manually. Note, your current schema doesn't complient with Third normal form. If you don't want to change your schema, you could read and generate them using group by clause.

Body:
I have n number of services and under each service there will be 2 routes(some times more than 2). Under each route there are n number of stops. I am getting values from db as  a table in below column order
ServiceId, Service Name,serviceLine color,RouteId, Route Name, Stop Id, Stop Name, Latitude, Longitude.

I want to convert it an object list of below format

 public class Service
    {
        public string ServiceId { get; set; }
        public string ServiceName { get; set; }
        public string ServiceLineColor { get; set; }
        public List<RouteData> RouteList { get; set; }
    }
    public class RouteData
    {
        public string RouteId { get; set; }
        public string RouteCode { get; set; }
        public string RouteName { get; set; }
        public List<StopData> stopList { get; set; }
    }
    public class StopData
    {
        public string StopCode { get; set; }
        public string StopName { get; set; }
        public string Latitude { get; set; }
        public string Longitude { get; set; }
        public string StopType { get; set; }
    }

Is there any easy way in linq to convert data in to below format? I wanted to avoid looping.. since i am getting nearly 1k records from db. Please help me to solve this issue.

Or is it best to use db calls to format data. i didn't prefer that because if there is 50 services i need to do 50 db calls and again have to do data formatting logic.


来源: stackexchange

问:
Is it possible to suppress the display of all parameterized arguments when a test fails in pytest
I'm currently using python 3.5.1 and 3.6 and the latest versions of pytest.
When running pytest with parameterized tests i would like any failing tests to only display the test that failed and not all of the set up for the parameterized test.

To explain...

I have a number of tests that I have written using the @pytest.mark.parametrize decorator to allow me to run a test with many different inputs.

I also pass a list of ids for my parameterized arguments as shown in the example below:

```<code>@pytest.mark.parametrize('input_name12, output_name12',
    [
        ('chloroform', None),
        ('chloroform-d', (['deuterated'], '-d'))]
    ],
    ids=[
        "unlabelled chloroform",
        "chloroform deuterio-labelled with -d"
    ]
def test_isotope_extract(input_name12, output_name12):
    assert isotope_extract(input_name12) == output_name12
</code>```

In some cases I have 10+ sets of arguments that I want to run in my tests.  This generally works ok. However, when I run the tests, if one or more of my parameterised tests fails the whole block of all of the parameterized test is output to the terminal for each failure. ie a failure for one of the tests in the above code would result in all of the code in that block being displayed in the terminal as well as the specific detail of which assertion failed.

Is there any way to suppress the display of the whole parameterized test, so that when I get a failure I only see the assertion that failed and the associated Id?

答: This is because pytest prints the code of the function that failed. You can prevent that by using --tb=short.

ContentLicense: CC BY-SA 3.0

Body:
I'm currently using python 3.5.1 and 3.6 and the latest versions of pytest.
When running pytest with parameterized tests i would like any failing tests to only display the test that failed and not all of the set up for the parameterized test.

To explain...

I have a number of tests that I have written using the @pytest.mark.parametrize decorator to allow me to run a test with many different inputs.

I also pass a list of ids for my parameterized arguments as shown in the example below:

@pytest.mark.parametrize('input_name12, output_name12',
    [
        ('chloroform', None),
        ('chloroform-d', (['deuterated'], '-d'))]
    ],
    ids=[
        "unlabelled chloroform",
        "chloroform deuterio-labelled with -d"
    ]
def test_isotope_extract(input_name12, output_name12):
    assert isotope_extract(input_name12) == output_name12

In some cases I have 10+ sets of arguments that I want to run in my tests.  This generally works ok. However, when I run the tests, if one or more of my parameterised tests fails the whole block of all of the parameterized test is output to the terminal for each failure. ie a failure for one of the tests in the above code would result in all of the code in that block being displayed in the terminal as well as the specific detail of which assertion failed.

Is there any way to suppress the display of the whole parameterized test, so that when I get a failure I only see the assertion that failed and the associated Id?


问:
Java - How is memory leak in Java harmful? How can it possibly get used for a bad cause?
Creating a memory leak with Java

I was going through above "interview" question. After reading it's answers I myself ended up having a few questions.

Let's guess there is already a memory leak in the code.
How is that harmful? How can the data go in wrong hands?

I am pretty sure that System.read(); (or something like that) is not going to read the data from the memory leak. Is that even possible?

Please help with some reference/code/documents.

答:
Memory leak is really a broad argument, to be honest I've voted to close your question (because too broad) but on the other hand I would try to give you a little spark of what behind this problem.

Consider that you're creating a session in memory for every user connected to your web service, but you don't throw away the session after some time, simply because you forget or because a bad design of your application, this would cause a memory leak.

And again, consider that you don't close your open files or sockets.

Or consider that somewhere you save a reference to all the intermediate data structures produced by your process. In this case there is no way for the garbage collector to free the allocated memory.

Memory leaks mostly happens in long running application, because in the short run a memory leak have little chances to generate a out of memory exception. But in the long run the thing changes, there are applications that runs for months or even years.

There are so many situation where a memory leaks could happen. Many framework or libraries and even the languages try to save the programmers by this "bad" situations, but I personally think that is the experience of the programmer that does the difference.

For example in Java the Try with resource Statement is an example of language features born to help programmers in such situation (this helps to not forget).

So when designing your own objects that should close some resource at end of their life, try to implement java.lang.AutoCloseable interface and add the appropriate methods. Have a look at how many classes are now implementing the Autocloseable interface, this also explain how is important the memory (leak) and resource handling.

I would also suggest to study the difference between Java stack and heap memory management.

Once I experienced a Tomcat instance that hanged a server every three months. After some time the server had to be restarted every three week, till the time the server had to be restarted every day.

Comes out that "someone", wrote a for loop instead to add a while clause in a sql query.

So, there are programmers that does this as full time job, that are expert in this kind of investigations and that are able to find and correct memory leaks.


问:
Change config FlySystem uses in Laravel
The Laravel documentation states that th FlySystem config is located in config/filesystems.php. Is there a way I can change where this file is loaded or can i state when using a disk to load from a different config?

So instead of

```<code>Storage::disk('local')->put('file.txt', 'Contents');
</code>```

Something like

```<code> Storage::disk('myconfig::local')->put('file.txt', 'Contents');
</code>```

答:
It Supported Drivers: "local", "ftp", "s3", "rackspace";

Maybe you need take a look this docs

src/Illuminate/Filesystem/FilesystemManager.php#L70

```<code>/**
 * Get the filesystem connection configuration.
 *
 * @param  string  $name
 * @return array
 */
protected function getConfig($name)
{
    return $this->app['config']["filesystems.disks.{$name}"];
}
</code>```

```<code>'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_KEY'),
            'secret' => env('AWS_SECRET'),
            'region' => env('AWS_REGION'),
            'bucket' => env('AWS_BUCKET'),
        ],

    ]
</code>```

Title: Change config FlySystem uses in Laravel

Body:
The Laravel documentation states that th FlySystem config is located in config/filesystems.php. Is there a way I can change where this file is loaded or can i state when using a disk to load from a different config?

So instead of

Storage::disk('local')->put('file.txt', 'Contents');

Something like

 Storage::disk('myconfig::local')->put('file.txt', 'Contents');

Body:
It Supported Drivers: "local", "ftp", "s3", "rackspace";

Maybe you need take a look this docs

src/Illuminate/Filesystem/FilesystemManager.php#L70

/**
 * Get the filesystem connection configuration.
 *
 * @param  string  $name
 * @return array
 */
protected function getConfig($name)
{
    return $this->app['config']["filesystems.disks.{$name}"];
}

'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_KEY'),
            'secret' => env('AWS_SECRET'),
            'region' => env('AWS_REGION'),
            'bucket' => env('AWS_BUCKET'),
        ],

    ]


问:
Decorators in different jars than implementation
I use Jboss 7.1.1 with Weld 1.1.10.

I have a war that includes two jars. In api.jar I have interfaces and in impl.jar I have implementations of the interfaces.

api.jar:

```<code>public interface MyInterface {
    public void myMethod();
}
</code>```

impl.jar:

```<code>public class MyClass implements MyInterface {
    public void myMethod() {
        System.out.println("This is my implementation");
    }
}
</code>```

webapp.war:

```<code>public class MyRestApi {
    @Inject private MyInterface injected;

    @GET public Response doSomething() {
        injected.myMethod();
        return Response.ok().build();
    }
}
</code>```

Now I want include a decorator for MyInterface which I include in a third jar

decorator.jar:

```<code>@Decorator public class MyDecorator implements MyInterface {
    @Inject @Delegate @Any private MyInterface delegate;

    public void myMethod() {
        System.out.println("This is my decorator");
        delegate.myMethod();
    }
}
</code>```

I would like to activate the decorator in beans.xml in the decorator.jar, but it seems that the only way to get the decorator to work is to activate it in impl.jar. This is not very practical since impl.jar does not know of decorator.jar. And what if I at a future point want to include more decorators, or have the same decorator apply to different implementations?

Given that I am limited to Jboss 7.1.1 atm, and upgrading to CDI 1.1 is not an option, how can I make the decorator work independent of the implementation?

Here is the beans.xml to activate the decorator

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <decorators>
        <class>org.company.project.decorator.MyDecorator</class>
    </decorators>
</beans>
</code>```

This is what I've found so far: If I put it in the war, in place of an empty one, the decorator is not activated. If I put it in decorator.jar, in place of an empty one, the decorator is not activated. If I put it in impl.jar, in place of an empty one, the decorator is activated.

答:
Reading the documentation[1], seems not possible:

The decorators that you specify in the beans.xml file apply only to
  classes in the same archive.

So, you can put the class in a different Jar, but you cannot put the configuration esewhere.

[1]https://docs.oracle.com/javaee/7/tutorial/cdi-adv007.htm

Body:
I use Jboss 7.1.1 with Weld 1.1.10.

I have a war that includes two jars. In api.jar I have interfaces and in impl.jar I have implementations of the interfaces.

api.jar:

public interface MyInterface {
    public void myMethod();
}

impl.jar:

public class MyClass implements MyInterface {
    public void myMethod() {
        System.out.println("This is my implementation");
    }
}

webapp.war:

public class MyRestApi {
    @Inject private MyInterface injected;

    @GET public Response doSomething() {
        injected.myMethod();
        return Response.ok().build();
    }
}

Now I want include a decorator for MyInterface which I include in a third jar

decorator.jar:

@Decorator public class MyDecorator implements MyInterface {
    @Inject @Delegate @Any private MyInterface delegate;

    public void myMethod() {
        System.out.println("This is my decorator");
        delegate.myMethod();
    }
}

I would like to activate the decorator in beans.xml in the decorator.jar, but it seems that the only way to get the decorator to work is to activate it in impl.jar. This is not very practical since impl.jar does not know of decorator.jar. And what if I at a future point want to include more decorators, or have the same decorator apply to different implementations?

Given that I am limited to Jboss 7.1.1 atm, and upgrading to CDI 1.1 is not an option, how can I make the decorator work independent of the implementation?

Here is the beans.xml to activate the decorator

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <decorators>
        <class>org.company.project.decorator.MyDecorator</class>
    </decorators>
</beans>

This is what I've found so far: If I put it in the war, in place of an empty one, the decorator is not activated. If I put it in decorator.jar, in place of an empty one, the decorator is not activated. If I put it in impl.jar, in place of an empty one, the decorator is activated.


问:
Can I use JOIN instead of a subquery to get COUNT() across tables in MySQL?
I have one table that stores posts. Each post object has a postTypeId that denotes if it's a question post or an answer post. I would like to get question posts and count the number of answer posts each question post has. Can I do this using a JOIN instead of a subquery as shown below? The schema assumes the following: postsTable(id, postTypeId, parentId, title)

```<code>SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.title
    , (SELECT COUNT(answers.id) AS answerCount FROM posts AS answers WHERE posts.id = answers.parentId GROUP BY posts.postTypeId)
    FROM posts
    WHERE posts.postTypeId = '1'
</code>```

Also, is the GROUP By necessary in the subquery?

答:
```<code>    SELECT posts.id, posts.postTypeId, posts.parentId, posts.title, COUNT(answers.id) AS answerCount
    FROM posts
    LEFT JOIN posts ON posts.id = answers.parentId
    WHERE posts.postTypeId = '1'
    GROUP BY posts.id
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have one table that stores posts. Each post object has a postTypeId that denotes if it's a question post or an answer post. I would like to get question posts and count the number of answer posts each question post has. Can I do this using a JOIN instead of a subquery as shown below? The schema assumes the following: postsTable(id, postTypeId, parentId, title)

SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.title
    , (SELECT COUNT(answers.id) AS answerCount FROM posts AS answers WHERE posts.id = answers.parentId GROUP BY posts.postTypeId)
    FROM posts
    WHERE posts.postTypeId = '1'

Also, is the GROUP By necessary in the subquery?


问:
How Can i subtract two columns in different tables in SQL
I want to enter in a query the subtract between two columns in different tables it keeps saying error ...</p>

```<code>SELECT FlightDate,
       Plane,
       Destination,
       Capacity
FROM
       FlightSchedule,
       Routes,
       Aircrafts
WHERE
       FlightSchedule.RID=Routes.RouteID
       AND FlightSchedule.Plane=Aircrafts.AcID
       AND (SELECT SUM(Capacity)
            FROM Aircrafts)
            -
           (SELECT Class , count(*)
           FROM Tickets);
</code>```

答:
The query is wrong on multiple levels.

First of all, you cannot put the details of SELECT capacity as a sub query under WHERE. The WHERE clause is for conditional parameters.

Try this:

```<code>WITH VACANCY as (SELECT SUM(Capacity) FROM Aircrafts) - (SELECT Count(*) FROM Tickets)
SELECT FlightDate,Plane, Destination, Vacancy
FROM FlightSchedule,Routes,Aircrafts
WHERE  FlightSchedule.RID=Routes.RouteID AND FlightSchedule.Plane=Aircrafts.AcID;
</code>```

You also need to a condition for the select count for tickets but I don't know the schema of tickets so...

Body:
I want to enter in a query the subtract between two columns in different tables it keeps saying error ...

SELECT FlightDate,
       Plane,
       Destination,
       Capacity
FROM
       FlightSchedule,
       Routes,
       Aircrafts
WHERE
       FlightSchedule.RID=Routes.RouteID
       AND FlightSchedule.Plane=Aircrafts.AcID
       AND (SELECT SUM(Capacity)
            FROM Aircrafts)
            -
           (SELECT Class , count(*)
           FROM Tickets);

Body:
The query is wrong on multiple levels.

First of all, you cannot put the details of SELECT capacity as a sub query under WHERE. The WHERE clause is for conditional parameters.

Try this:

WITH VACANCY as (SELECT SUM(Capacity) FROM Aircrafts) - (SELECT Count(*) FROM Tickets)
SELECT FlightDate,Plane, Destination, Vacancy
FROM FlightSchedule,Routes,Aircrafts
WHERE  FlightSchedule.RID=Routes.RouteID AND FlightSchedule.Plane=Aircrafts.AcID;

You also need to a condition for the select count for tickets but I don't know the schema of tickets so...


问:
How to use single object instance for class to set the multiple member value?
Curretly i am using below code to set the DateRanges Class member variables.

```<code>       DateRanges DateRanges1 = new DateRanges();
       DateRanges DateRanges2 = new DateRanges();
       DateRanges DateRanges3 = new DateRanges();

        DateRanges1.Label = "Last Week";
        DateRanges1.Range = Lastweek;
        this.dateRange.Ranges.Add(DateRanges1);
        DateRanges2.Label = "Last 1 Month";
        DateRanges2.Range = Lastmonth;
        this.dateRange.Ranges.Add(DateRanges2);
        DateRanges3.Label = "Last 2 Months";
        DateRanges3.Range = Last2month;
        this.dateRange.Ranges.Add(DateRanges3);
</code>```

I want to reduce the code in this. is there any way to do this.

Here DateRanges, class that have label(string type), ranges(object) members.
this.daterange.ranges is my custom component property.
Thanks for any help.

答:
You can have only one variable instead of 3 variables:</p>

```<code>    var DateRanges = new DateRanges {
        Label = "Last Week",
        Range = Lastweek
    };
    this.dateRange.Ranges.Add(DateRanges);

    DateRanges = new DateRanges {
        Label = "Last 1 Month",
        Range = Lastmonth
    };
    this.dateRange.Ranges.Add(DateRanges);

    DateRanges = new DateRanges {
        Label = "Last 2 Months",
        Range = Last2month
    };
    this.dateRange.Ranges.Add(DateRanges);
</code>```

Body:
Curretly i am using below code to set the DateRanges Class member variables.

       DateRanges DateRanges1 = new DateRanges();
       DateRanges DateRanges2 = new DateRanges();
       DateRanges DateRanges3 = new DateRanges();

        DateRanges1.Label = "Last Week";
        DateRanges1.Range = Lastweek;
        this.dateRange.Ranges.Add(DateRanges1);
        DateRanges2.Label = "Last 1 Month";
        DateRanges2.Range = Lastmonth;
        this.dateRange.Ranges.Add(DateRanges2);
        DateRanges3.Label = "Last 2 Months";
        DateRanges3.Range = Last2month;
        this.dateRange.Ranges.Add(DateRanges3);

I want to reduce the code in this. is there any way to do this.

Here DateRanges, class that have label(string type), ranges(object) members.
this.daterange.ranges is my custom component property.
Thanks for any help.

Body:
You can have only one variable instead of 3 variables:

    var DateRanges = new DateRanges {
        Label = "Last Week",
        Range = Lastweek
    };
    this.dateRange.Ranges.Add(DateRanges);

    DateRanges = new DateRanges {
        Label = "Last 1 Month",
        Range = Lastmonth
    };
    this.dateRange.Ranges.Add(DateRanges);

    DateRanges = new DateRanges {
        Label = "Last 2 Months",
        Range = Last2month
    };
    this.dateRange.Ranges.Add(DateRanges);


问:
How do I Store an Array Variable Inside of Another Array Variable using while loop and for each?
How do I Store an Array Variable Inside of Another Array Variable using while loop and for each?

Like this(array inside array)

答:
You are probably looking for

```<code>   <?php
    $format = array('Roman' =>  array('one'=>'I','two'=>'II'),
    'Arbic' =>  array('one'=>'1','two'=>'2'));
    while (list($key, $value) = each($format)) {
           echo $value;
    foreach( $key as $key1 => $value1)   {
    echo $key1 .'='.$value1;
    }

    ?>
</code>```

I have not tested .

Body:
You are probably looking for

   <?php
    $format = array('Roman' =>  array('one'=>'I','two'=>'II'),
    'Arbic' =>  array('one'=>'1','two'=>'2'));
    while (list($key, $value) = each($format)) {
           echo $value;
    foreach( $key as $key1 => $value1)   {
    echo $key1 .'='.$value1;
    }

    ?>

I have not tested .


问:
django.core.exceptions.ValidationError: [u"'' value has an invalid
models.py

```<code>    # -*- coding:utf-8 -*-
    from __future__ import unicode_literals
    from django.db import models
    # Create your models here.

    class moption(models.Model):

        pub_date = models.DateTimeField('pub time', auto_now_add=True, editable=True)
</code>```

when I command "python manage.py migrate"

```<code>Operations to perform:
  Apply all migrations: Price, admin, auth, contenttypes, sessions
Running migrations:
  Applying Price.0006_moption_pub_date...Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Python27\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
    field,
  File "C:\Python27\lib\site-packages\django\db\backends\mysql\schema.py", line 43, in add_field
    super(DatabaseSchemaEditor, self).add_field(model, field)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 395, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 147, in column_sql
    default_value = self.effective_default(field)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 221, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 755, in get_db_prep_save
    prepared=False)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1440, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1419, in get_prep_value
    value = super(DateTimeField, self).get_prep_value(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1275, in get_prep_value
    return self.to_python(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1403, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: [u"'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
</code>```

who can tell me,thanks,

答:
Deleting all your migrations, dropping your database are rather extrement suggestions and i would advice you against that. In fact, do not do either of these unless you have full data backups and al your migrations are in version control.

Right, now let's look at the signature for DateTimeField

class DateTimeField(auto_now=False, auto_now_add=False, **options)

And your usage

```<code>  pub_date = models.DateTimeField('pub time', auto_now_add=True, editable=True)
</code>```

What is this 'pub time'? What ever it is, it's causing a faulty migration to be created.

After you fix your code, look at your database, see inside the django_migrations table and find the number of the last applied migration for this app. Anything in your migrations folder with a higher number is an unapplied migration. Delete only the unapplied migrations. And then delete the '*.pyc' files in the dame folder. Now do

```<code>./manage.py makemigrations
./manage.py migrate
</code>```

Body:
models.py

    # -*- coding:utf-8 -*-
    from __future__ import unicode_literals
    from django.db import models
    # Create your models here.

    class moption(models.Model):

        pub_date = models.DateTimeField('pub time', auto_now_add=True, editable=True)

when I command "python manage.py migrate"

Operations to perform:
  Apply all migrations: Price, admin, auth, contenttypes, sessions
Running migrations:
  Applying Price.0006_moption_pub_date...Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Python27\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
    field,
  File "C:\Python27\lib\site-packages\django\db\backends\mysql\schema.py", line 43, in add_field
    super(DatabaseSchemaEditor, self).add_field(model, field)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 395, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 147, in column_sql
    default_value = self.effective_default(field)
  File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 221, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 755, in get_db_prep_save
    prepared=False)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1440, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1419, in get_prep_value
    value = super(DateTimeField, self).get_prep_value(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1275, in get_prep_value
    return self.to_python(value)
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1403, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: [u"'' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]

who can tell me,thanks,

Body:
Deleting all your migrations, dropping your database are rather extrement suggestions and i would advice you against that. In fact, do not do either of these unless you have full data backups and al your migrations are in version control.

Right, now let's look at the signature for DateTimeField

class DateTimeField(auto_now=False, auto_now_add=False, **options)

And your usage

  pub_date = models.DateTimeField('pub time', auto_now_add=True, editable=True)

What is this 'pub time'? What ever it is, it's causing a faulty migration to be created.

After you fix your code, look at your database, see inside the django_migrations table and find the number of the last applied migration for this app. Anything in your migrations folder with a higher number is an unapplied migration. Delete only the unapplied migrations. And then delete the '*.pyc' files in the dame folder. Now do

./manage.py makemigrations
./manage.py migrate


问:
SQL GROUP BY one field and list latest value of two other fields at the same time
Take in consideration this data:

```<code>id      firstname   lastname    registration_date
101126423   foo         bar     2010-06-17 13:31:00.000
101126423   foo         bar     2010-06-17 13:31:00.000
101126423   foo         bar jr  2010-06-18 12:13:00.000
101152718   john        doe     2010-02-26 19:08:00.000
101152718   john        doe     2010-02-26 19:08:00.000
101152718   john        doe     2010-02-26 19:08:00.000
</code>```

You can have customers with with the same id but with a different firstname / lastname! I want to get all distinct ids but with the latest firstname/lastname (based on registration_date).

For my example I would get:

```<code>id      firstname   lastname
101126423   foo         bar jr
101152718   john        doe
</code>```

So far I got:

```<code>SELECT DISTINCT id, firstname, lastname
FROM member
</code>```

but it's obviously not working... I've tried other queries with no success so far. Maybe having can help me but I never used it...

I use SQL Server 2008 in this project.

答:
A couple options for you:

Option 1:

```<code>;with cte as(
  select id, max(registration_date) lastReg
  from member
  group by id
)
select distinct m.id, m.firstname, m.lastname
from member m
  join cte c on m.id=c.id
            and m.registration_date = c.lastReg
</code>```

Option 2:

```<code>;with cte as(
  select id, firstname, lastname,
         row_number() over(partition by id order by registration_date desc) as 'order'
  from member
)
select id, firstname, lastname
from cte
where order = 1
</code>```

The biggest difference in the two, with regards to their results, is how they handle the case where the most recent registration time is duplicated for an id with multiple names.  In this case, Option 1 will return both names that have the latest registration date and Option 2 will only return one (randomly).  An example of this case is (a slight tweak of your sample data):

```<code>id          firstname   lastname    registration_date
101126423   foo         bar         2010-06-17 13:31:00.000
101126423   foo         bar         2010-06-18 12:13:00.000
101126423   foo         bar jr      2010-06-18 12:13:00.000
101152718   john        doe         2010-02-26 19:08:00.000
101152718   john        doe         2010-02-26 19:08:00.000
101152718   john        doe         2010-02-26 19:08:00.000

--Option 1 result:
id          firstname   lastname
101126423   foo         bar
101126423   foo         bar jr
101152718   john        doe

--Option 2 result (possibility 1):
id          firstname   lastname
101126423   foo         bar
101152718   john        doe

--Option 2 result (possibility 2):
id          firstname   lastname
101126423   foo         bar jr
101152718   john        doe
</code>```

Body:
Take in consideration this data:

id      firstname   lastname    registration_date
101126423   foo         bar     2010-06-17 13:31:00.000
101126423   foo         bar     2010-06-17 13:31:00.000
101126423   foo         bar jr  2010-06-18 12:13:00.000
101152718   john        doe     2010-02-26 19:08:00.000
101152718   john        doe     2010-02-26 19:08:00.000
101152718   john        doe     2010-02-26 19:08:00.000

You can have customers with with the same id but with a different firstname / lastname! I want to get all distinct ids but with the latest firstname/lastname (based on registration_date).

For my example I would get:

id      firstname   lastname
101126423   foo         bar jr
101152718   john        doe

So far I got:

SELECT DISTINCT id, firstname, lastname
FROM member

but it's obviously not working... I've tried other queries with no success so far. Maybe having can help me but I never used it...

I use SQL Server 2008 in this project.

Body:
A couple options for you:

Option 1:

;with cte as(
  select id, max(registration_date) lastReg
  from member
  group by id
)
select distinct m.id, m.firstname, m.lastname
from member m
  join cte c on m.id=c.id
            and m.registration_date = c.lastReg

Option 2:

;with cte as(
  select id, firstname, lastname,
         row_number() over(partition by id order by registration_date desc) as 'order'
  from member
)
select id, firstname, lastname
from cte
where order = 1

The biggest difference in the two, with regards to their results, is how they handle the case where the most recent registration time is duplicated for an id with multiple names.  In this case, Option 1 will return both names that have the latest registration date and Option 2 will only return one (randomly).  An example of this case is (a slight tweak of your sample data):

id          firstname   lastname    registration_date
101126423   foo         bar         2010-06-17 13:31:00.000
101126423   foo         bar         2010-06-18 12:13:00.000
101126423   foo         bar jr      2010-06-18 12:13:00.000
101152718   john        doe         2010-02-26 19:08:00.000
101152718   john        doe         2010-02-26 19:08:00.000
101152718   john        doe         2010-02-26 19:08:00.000

--Option 1 result:
id          firstname   lastname
101126423   foo         bar
101126423   foo         bar jr
101152718   john        doe

--Option 2 result (possibility 1):
id          firstname   lastname
101126423   foo         bar
101152718   john        doe

--Option 2 result (possibility 2):
id          firstname   lastname
101126423   foo         bar jr
101152718   john        doe


问:
How to bundle AWS Cognito within Aurelia Framework
Since my previous post on another question was deleted, even though it was pretty explicit in presenting the problem (in that context), I will try again as a stand alone question.

I am trying to bundle Amazon Cognito with aurelia.json. I have followed everything I could thin of in the answers provided by jsachs and Nathan in the mentioned article, however I think something is incomplete.

```<code>  {
    "name": "account-components-bundle.js",
    "source": {
      "include": [
        "**/components/account/**/*.js",
        "**/components/account/**/*.{html,css}"
      ]
    },
    "dependencies": [
      {
          "name": "aws-sdk",
          "path": "../node_modules/aws-sdk/dist",
          "main": "aws-sdk.min",
          "exports": "AWS"
      }
    ],
    "prepend": [
      "node_modules/aws-sdk/dist/aws-sdk.min.js",
      "node_modules/amazon-cognito-identity-js/dist/aws-cognito-sdk.min.js",
      "node_modules/amazon-cognito-identity-js/dist/amazon-cognito-identity.min.js",
      "node_modules/bluebird/js/browser/bluebird.core.js",
      "node_modules/requirejs/require.js"
    ]
  },
</code>```

If you add only the prepend directive, au build will not throw any error, however I have no way of calling the Cognito classes.

Adding the dependencies directive in the form above will eventually bundle the package, however at page load you will get the following error (please keep in mind I am not calling anything yet within our own code):

```<code>Unhandled rejection Error: Script error for "aws-sdk/global", needed by: components/account/login
http://requirejs.org/docs/errors.html#scripterror
    at makeError (https://white.dev/dist/aurelia-bundle.js:4419:17)
    at HTMLScriptElement.onScriptError (https://white.dev/dist/aurelia-bundle.js:5989:36)
From previous event:
    at DefaultLoader.loadModule (https://white.dev/dist/aurelia-bundle.js:14914:14)
    at ViewEngine.importViewModelResource (https://white.dev/dist/aurelia-bundle.js:23006:26)
    at CompositionEngine.ensureViewModel (https://white.dev/dist/aurelia-bundle.js:24276:32)
    at CompositionEngine.createController (https://white.dev/dist/aurelia-bundle.js:24252:19)
    at CompositionEngine._createControllerAndSwap (https://white.dev/dist/aurelia-bundle.js:24227:19)
    at CompositionEngine.compose (https://white.dev/dist/aurelia-bundle.js:24313:21)
    at processInstruction (https://white.dev/dist/aurelia-bundle.js:24798:32)
    at Compose.bind (https://white.dev/dist/aurelia-bundle.js:24689:7)
    at Controller.bind (https://white.dev/dist/aurelia-bundle.js:23196:24)
    at View.bind (https://white.dev/dist/aurelia-bundle.js:21200:24)
    at If._runValueChanged (https://white.dev/dist/aurelia-bundle.js:24887:19)
    at If.valueChanged (https://white.dev/dist/aurelia-bundle.js:24842:31)
    at If.bind (https://white.dev/dist/aurelia-bundle.js:24831:12)
From previous event:
    at CompositionEngine._createControllerAndSwap (https://white.dev/dist/aurelia-bundle.js:24227:45)
    at CompositionEngine.compose (https://white.dev/dist/aurelia-bundle.js:24313:21)
    at TemplatingEngine.compose (https://white.dev/dist/aurelia-bundle.js:24576:38)
    at Aurelia.setRoot (https://white.dev/dist/aurelia-bundle.js:13886:21)
    at Object._callee$ (https://white.dev/dist/app-bundle.js:86:37)
    at tryCatch (https://white.dev/dist/aurelia-bundle.js:3:27199)
    at Generator.invoke [as _invoke] (https://white.dev/dist/aurelia-bundle.js:3:28901)
    at Generator.t.(anonymous function) [as next] (https://white.dev/dist/aurelia-bundle.js:3:27447)
    at step (https://white.dev/dist/app-bundle.js:25:44)
    at https://white.dev/dist/app-bundle.js:36:29
From previous event:
    at step (https://white.dev/dist/app-bundle.js:35:55)
    at https://white.dev/dist/app-bundle.js:43:24
From previous event:
    at Object.<anonymous> (https://white.dev/dist/app-bundle.js:22:20)
    at Object.configure (https://white.dev/dist/app-bundle.js:97:25)
    at https://white.dev/dist/aurelia-bundle.js:12465:29
From previous event:
    at config (https://white.dev/dist/aurelia-bundle.js:12460:56)
    at https://white.dev/dist/aurelia-bundle.js:12496:14
From previous event:
    at bootstrap (https://white.dev/dist/aurelia-bundle.js:12495:26)
    at https://white.dev/dist/aurelia-bundle.js:12482:9
    at <anonymous>
From previous event:
    at run (https://white.dev/dist/aurelia-bundle.js:12477:61)
    at Object.<anonymous> (https://white.dev/dist/aurelia-bundle.js:12502:37)
    at Object.execCb (https://white.dev/dist/aurelia-bundle.js:5947:33)
    at Module.check (https://white.dev/dist/aurelia-bundle.js:5134:51)
    at Module.enable (https://white.dev/dist/aurelia-bundle.js:5427:22)
    at Object.enable (https://white.dev/dist/aurelia-bundle.js:5808:39)
    at Module.<anonymous> (https://white.dev/dist/aurelia-bundle.js:5412:33)
    at https://white.dev/dist/aurelia-bundle.js:4385:23
    at each (https://white.dev/dist/aurelia-bundle.js:4310:31)
    at Module.enable (https://white.dev/dist/aurelia-bundle.js:5364:17)
    at Module.init (https://white.dev/dist/aurelia-bundle.js:5039:26)
    at https://white.dev/dist/aurelia-bundle.js:5711:36
</code>```

The moment I go further and try to extend the dependencies (not use the already compiled libraries), I get to the same old problem mentioned in the previous post.

```<code>    "dependencies": [
      {
        "name": "lodash",
        "path": "../node_modules/lodash",
        "main": "index"
      },
      {
        "name": "xmlbuilder",
        "path": "../node_modules/xmlbuilder",
        "main": "lib/index"
      },
      {
          "name": "aws-sdk",
          "path": "../node_modules/aws-sdk",
          "main": "lib/aws",
          "exports": "AWS"
      }
    ],
</code>```

This dependencies, when running au build, will lead to

```<code>File not found or not accessible: /path/to/project/node_modules/aws-sdk/lib/region_config_data.json.js. Requested by /path/to/project/node_modules/aws-sdk/lib/aws.js
{ Error: ENOENT: no such file or directory, open '/path/to/project/node_modules/aws-sdk/lib/region_config_data.json.js'
    at Object.fs.openSync (fs.js:584:18)
    at Object.fs.readFileSync (fs.js:491:33)
    at Object.exports.readFileSync (/path/to/project/node_modules/aurelia-cli/lib/file-system.js:74:13)
    at fileRead (/path/to/project/node_modules/aurelia-cli/lib/build/bundled-source.js:101:27)
    at Object.context.fileRead (/path/to/project/node_modules/aurelia-cli/lib/build/amodro-trace/lib/loader/Loader.js:179:18)
    at Object.context.load (/path/to/project/node_modules/aurelia-cli/lib/build/amodro-trace/lib/loader/Loader.js:370:32)
    at Module.load (eval at <anonymous> (/path/to/project/node_modules/aurelia-cli/lib/build/amodro-trace/lib/loader/Loader.js:14:1), <anonymous>:832:29)
    at Module.fetch (eval at <anonymous> (/path/to/project/node_modules/aurelia-cli/lib/build/amodro-trace/lib/loader/Loader.js:14:1), <anonymous>:822:66)
    at Module.check (eval at <anonymous> (/path/to/project/node_modules/aurelia-cli/lib/build/amodro-trace/lib/loader/Loader.js:14:1), <anonymous>:854:30)
    at Module.enable (eval at <anonymous> (/path/to/project/node_modules/aurelia-cli/lib/build/amodro-trace/lib/loader/Loader.js:14:1), <anonymous>:1173:22)
errno: -2,
code: 'ENOENT',
syscall: 'open',
</code>```

I think this is caused by the fact that requirejs in comparison to nodejs require() may not support loading json files and it always expects the file to be a js one.

At this point in my debugging quest I am kinda stuck. Has anyone got any suggestions in how this can be achieved? I would be very grateful.

To avoid and exclude some previous questions to my approaches, I have tried to add to the bundle dependencies "amazon-cognito-identity-js" as well, in more than one form (both dist and lib files). The outcome is the same as the one above. I get stuck at json.js error.

Edit 1

I managed to clean all compile errors with the following form for aurelia.json, however the classes are not loading properly.

```<code>"bundles": [
  {
    "name": "app-bundle.js",
    "source": {
      "include": [
        "**/src/main.js",
        "**/src/app.js",
        "**/src/environment.js",
        "**/src/app.{html,css}"
      ]
    }
  },
  ...
  {
    "name": "vendor-bundle.js",
    "dependencies": [
      ...
      {
        "name": "lodash",
        "path": "../node_modules/lodash",
        "main": "index"
      },
      {
        "name": "xmlbuilder",
        "path": "../node_modules/xmlbuilder",
        "main": "lib/index"
      },
      {
        "name": "aws-sdk",
        "path": "../node_modules/aws-sdk",
        "main": "dist/aws-sdk",
        "exports": "AWS"
      }
    ],
    "append": [
      "node_modules/amazon-cognito-identity-js/dist/aws-cognito-sdk.min.js",
      "node_modules/amazon-cognito-identity-js/dist/amazon-cognito-identity.min.js"
    ]
  },
  ...
]
</code>```

答:
Funny to give the answer myself, but hey... if it will help others...

I managed to bundle the scripts by prepending them in the aurelia-bundle.js ahead of every other scripts that need to be loaded. Please understand, that (for me), placing the scripts in any other position that the following, will end up in neither loading correctly or not loading at all.

Don't pretend this is a general solution, but hey... works for me.
Please find a more detailed history here.

```<code>{
  "name": "aurelia-bundle.js",
  "prepend": [
    "node_modules/aws-sdk/dist/aws-sdk.min.js",
    "node_modules/amazon-cognito-identity-js/dist/aws-cognito-sdk.min.js",
    "node_modules/amazon-cognito-identity-js/dist/amazon-cognito-identity.min.js",
    "node_modules/babel-polyfill/dist/polyfill.min.js",
    "node_modules/whatwg-fetch/fetch.js",
    "node_modules/bluebird/js/browser/bluebird.core.js",
    "node_modules/aurelia-cli/lib/resources/scripts/configure-bluebird.js",
    "node_modules/requirejs/require.js"
  ],
  "dependencies": [
    "aurelia-animator-css",
    "aurelia-binding",
    "aurelia-bootstrapper",
    "aurelia-dependency-injection",
    "aurelia-event-aggregator",
</code>```

Body:
Since my previous post on another question was deleted, even though it was pretty explicit in presenting the problem (in that context), I will try again as a stand alone question.

I am trying to bundle Amazon Cognito with aurelia.json. I have followed everything I could thin of in the answers provided by jsachs and Nathan in the mentioned article, however I think something is incomplete.

  {
    "name": "account-components-bundle.js",
    "source": {
      "include": [
        "**/components/account/**/*.js",
        "**/components/account/**/*.{html,css}"
      ]
    },
    "dependencies": [
      {
          "name": "aws-sdk",
          "path": "../node_modules/aws-sdk/dist",
          "main": "aws-sdk.min",
          "exports": "AWS"
      }
    ],
    "prepend": [
      "node_modules/aws-sdk/dist/aws-sdk.min.js",
      "node_modules/amazon-cognito-identity-js/dist/aws-cognito-sdk.min.js",
      "node_modules/amazon-cognito-identity-js/dist/amazon-cognito-identity.min.js",
      "node_modules/bluebird/js/browser/bluebird.core.js",
      "node_modules/requirejs/require.js"
    ]
  },

If you add only the prepend directive, au build will not throw any error, however I have no way of calling the Cognito classes.

Adding the dependencies directive in the form above will eventually bundle the package, however at page load you will get the following error (please keep in mind I am not calling anything yet within our own code):

Unhandled rejection Error: Script error for "aws-sdk/global", needed by: components/account/login
http://requirejs.org/docs/errors.html#scripterror
    at makeError (https://white.dev/dist/aurelia-bundle.js:4419:17)
    at HTMLScriptElement.onScriptError (https://white.dev/dist/aurelia-bundle.js:5989:36)
From previous event:
    at DefaultLoader.loadModule (https://white.dev/dist/aurelia-bundle.js:14914:14)
    at ViewEngine.importViewModelResource (https://white.dev/dist/aurelia-bundle.js:23006:26)
    at CompositionEngine.ensureViewModel (https://white.dev/dist/aurelia-bundle.js:24276:32)
    at CompositionEngine.createController (https://white.dev/dist/aurelia-bundle.js:24252:19)
    at CompositionEngine._createControllerAndSwap (https://white.dev/dist/aurelia-bundle.js:24227:19)
    at CompositionEngine.compose (https://white.dev/dist/aurelia-bundle.js:24313:21)
    at processInstruction (https://white.dev/dist/aurelia-bundle.js:24798:32)
    at Compose.bind (https://white.dev/dist/aurelia-bundle.js:24689:7)
    at Controller.bind (https://white.dev/dist/aurelia-bundle.js:23196:24)
    at View.bind (https://white.dev/dist/aurelia-bundle.js:21200:24)
    at If._runValueChanged (https://white.dev/dist/aurelia-bundle.js:24887:19)
    at If.valueChanged (https://white.dev/dist/aurelia-bundle.js:24842:31)
    at If.bind (https://white.dev/dist/aurelia-bundle.js:24831:12)
From previous event:
    at CompositionEngine._createControllerAndSwap (https://white.dev/dist/aurelia-bundle.js:24227:45)
    at CompositionEngine.compose (https://white.dev/dist/aurelia-bundle.js:24313:21)
    at TemplatingEngine.compose (https://white.dev/dist/aurelia-bundle.js:24576:38)
    at Aurelia.setRoot (https://white.dev/dist/aurelia-bundle.js:13886:21)
    at Object._callee$ (https://white.dev/dist/app-bundle.js:86:37)
    at tryCatch (https://white.dev/dist/aurelia-bundle.js:3:27199)
    at Generator.invoke [as _invoke] (https://white.dev/dist/aurelia-bundle.js:3:28901)
    at Generator.t.(anonymous function) [as next] (https://white.dev/dist/aurelia-bundle.js:3:27447)
    at step (https://white.dev/dist/app-bundle.js:25:44)
    at https://white.dev/dist/app-bundle.js:36:29
From previous event:
    at step (https://white.dev/dist/app-bundle.js:35:55)
    at https://white.dev/dist/app-bundle.js:43:24
From previous event:
    at Object.<anonymous> (https://white.dev/dist/app-bundle.js:22:20)
    at Object.configure (https://white.dev/dist/app-bundle.js:97:25)
    at https://white.dev/dist/aurelia-bundle.js:12465:29
From previous event:
    at config (https://white.dev/dist/aurelia-bundle.js:12460:56)
    at https://white.dev/dist/aurelia-bundle.js:12496:14
From previous event:
    at bootstrap (https://white.dev/dist/aurelia-bundle.js:12495:26)
    at https://white.dev/dist/aurelia-bundle.js:12482:9
    at <anonymous>
From previous event:
    at run (https://white.dev/dist/aurelia-bundle.js:12477:61)
    at Object.<anonymous> (https://white.dev/dist/aurelia-bundle.js:12502:37)
    at Object.execCb (https://white.dev/dist/aurelia-bundle.js:5947:33)
    at Module.check (https://white.dev/dist/aurelia-bundle.js:5134:51)
    at Module.enable (https://white.dev/dist/aurelia-bundle.js:5427:22)
    at Object.enable (https://white.dev/dist/aurelia-bundle.js:5808:39)
    at Module.<anonymous> (https://white.dev/dist/aurelia-bundle.js:5412:33)
    at https://white.dev/dist/aurelia-bundle.js:4385:23
    at each (https://white.dev/dist/aurelia-bundle.js:4310:31)
    at Module.enable (https://white.dev/dist/aurelia-bundle.js:5364:17)
    at Module.init (https://white.dev/dist/aurelia-bundle.js:5039:26)
    at https://white.dev/dist/aurelia-bundle.js:5711:36

The moment I go further and try to extend the dependencies (not use the already compiled libraries), I get to the same old problem mentioned in the previous post.

    "dependencies": [
      {
        "name": "lodash",
        "path": "../node_modules/lodash",
        "main": "index"
      },
      {
        "name": "xmlbuilder",
        "path": "../node_modules/xmlbuilder",
        "main": "lib/index"
      },
      {
          "name": "aws-sdk",
          "path": "../node_modules/aws-sdk",
          "main": "lib/aws",
          "exports": "AWS"
      }
    ],

This dependencies, when running au build, will lead to

File not found or not accessible: /path/to/project/node_modules/aws-sdk/lib/region_config_data.json.js. Requested by /path/to/project/node_modules/aws-sdk/lib/aws.js
{ Error: ENOENT: no such file or directory, open '/path/to/project/node_modules/aws-sdk/lib/region_config_data.json.js'
    at Object.fs.openSync (fs.js:584:18)
    at Object.fs.readFileSync (fs.js:491:33)
    at Object.exports.readFileSync (/path/to/project/node_modules/aurelia-cli/lib/file-system.js:74:13)
    at fileRead (/path/to/project/node_modules/aurelia-cli/lib/build/bundled-source.js:101:27)
    at Object.context.fileRead (/path/to/project/node_modules/aurelia-cli/lib/build/amodro-trace/lib/loader/Loader.js:179:18)
    at Object.context.load (/path/to/project/node_modules/aurelia-cli/lib/build/amodro-trace/lib/loader/Loader.js:370:32)
    at Module.load (eval at <anonymous> (/path/to/project/node_modules/aurelia-cli/lib/build/amodro-trace/lib/loader/Loader.js:14:1), <anonymous>:832:29)
    at Module.fetch (eval at <anonymous> (/path/to/project/node_modules/aurelia-cli/lib/build/amodro-trace/lib/loader/Loader.js:14:1), <anonymous>:822:66)
    at Module.check (eval at <anonymous> (/path/to/project/node_modules/aurelia-cli/lib/build/amodro-trace/lib/loader/Loader.js:14:1), <anonymous>:854:30)
    at Module.enable (eval at <anonymous> (/path/to/project/node_modules/aurelia-cli/lib/build/amodro-trace/lib/loader/Loader.js:14:1), <anonymous>:1173:22)
errno: -2,
code: 'ENOENT',
syscall: 'open',

I think this is caused by the fact that requirejs in comparison to nodejs require() may not support loading json files and it always expects the file to be a js one.

At this point in my debugging quest I am kinda stuck. Has anyone got any suggestions in how this can be achieved? I would be very grateful.

To avoid and exclude some previous questions to my approaches, I have tried to add to the bundle dependencies "amazon-cognito-identity-js" as well, in more than one form (both dist and lib files). The outcome is the same as the one above. I get stuck at json.js error.

Edit 1

I managed to clean all compile errors with the following form for aurelia.json, however the classes are not loading properly.

"bundles": [
  {
    "name": "app-bundle.js",
    "source": {
      "include": [
        "**/src/main.js",
        "**/src/app.js",
        "**/src/environment.js",
        "**/src/app.{html,css}"
      ]
    }
  },
  ...
  {
    "name": "vendor-bundle.js",
    "dependencies": [
      ...
      {
        "name": "lodash",
        "path": "../node_modules/lodash",
        "main": "index"
      },
      {
        "name": "xmlbuilder",
        "path": "../node_modules/xmlbuilder",
        "main": "lib/index"
      },
      {
        "name": "aws-sdk",
        "path": "../node_modules/aws-sdk",
        "main": "dist/aws-sdk",
        "exports": "AWS"
      }
    ],
    "append": [
      "node_modules/amazon-cognito-identity-js/dist/aws-cognito-sdk.min.js",
      "node_modules/amazon-cognito-identity-js/dist/amazon-cognito-identity.min.js"
    ]
  },
  ...
]

Body:
Funny to give the answer myself, but hey... if it will help others...

I managed to bundle the scripts by prepending them in the aurelia-bundle.js ahead of every other scripts that need to be loaded. Please understand, that (for me), placing the scripts in any other position that the following, will end up in neither loading correctly or not loading at all.

Don't pretend this is a general solution, but hey... works for me.
Please find a more detailed history here.

{
  "name": "aurelia-bundle.js",
  "prepend": [
    "node_modules/aws-sdk/dist/aws-sdk.min.js",
    "node_modules/amazon-cognito-identity-js/dist/aws-cognito-sdk.min.js",
    "node_modules/amazon-cognito-identity-js/dist/amazon-cognito-identity.min.js",
    "node_modules/babel-polyfill/dist/polyfill.min.js",
    "node_modules/whatwg-fetch/fetch.js",
    "node_modules/bluebird/js/browser/bluebird.core.js",
    "node_modules/aurelia-cli/lib/resources/scripts/configure-bluebird.js",
    "node_modules/requirejs/require.js"
  ],
  "dependencies": [
    "aurelia-animator-css",
    "aurelia-binding",
    "aurelia-bootstrapper",
    "aurelia-dependency-injection",
    "aurelia-event-aggregator",


问:
`cin` incorrectly parses `double` input on Mac
A little bit of background - I'm new to learning C++. I'm working through Accelerated C++ and following things along. In chapter 4, the code I've got doesn't quite work as the book suggests, and I've double-checked all my of code to make sure I'm not mis-typing something from their example (I can't see any errors, anyway).

I have the following struct and two functions:

```<code>struct Student {
  std::string        name;
  double             midtermGrade, finalGrade;
  std::vector<double>homework;
};

std::istream& read(std::istream& is, Student& s) {
  is >> s.name >> s.midtermGrade >> s.finalGrade;

  std::cout << std::endl << "Name: " << s.name << std::endl
            << " - Md: " << s.midtermGrade << std::endl
            << " - Fn: " << s.finalGrade << std::endl;

  read_hw(is, s.homework);

  return is;
}

std::istream& read_hw(std::istream& in, std::vector<double>& hw) {
  if (in) {
    hw.clear();

    double h;

    while (in >> h) {
      std::cout << " - Hw: " << h << std::endl;
      hw.push_back(h);
    }

    in.clear();
  }

  return in;
}
</code>```

In int main() I'm calling that code like this:

```<code>Student record;
while (read(std::cin, record)) {
</code>```

If I compile and run, then paste (or type) in the following input, I get the following output:

```<code>// Input
Johnny 70 80 50 Fred 95 90 100 Joe 40 40 50

// Output
Name: Johnny
 - Md: 70
 - Fn: 80
 - Hw: 50

Name: red
 - Md: 95
 - Fn: 90
 - Hw: 100

Name: Joe
 - Md: 40
 - Fn: 40
 - Hw: 50
</code>```

As you can see, "Fred" has become "red". I've tried this with a whole bunch of names; anything starting with A-F is affected by the same issue, which caused me to suspect it may be a hexadecimal issue. However, "Nick" becomes "k" and "Xander" simply becomes "r".

I'm utterly baffled. Do you have any idea what's going on?

As requested, here's a MCVE:

```<code>#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

struct Student {
  std::string        name;
  double             midtermGrade, finalGrade;
  std::vector<double>homework;
};

std::istream& read_hw(std::istream& in, std::vector<double>& hw) {
  if (in) {
    hw.clear();

    double h;

    while (in >> h) {
      std::cout << " - Hw: " << h << std::endl;
      hw.push_back(h);
    }

    in.clear();
  }

  return in;
}

std::istream& read(std::istream& is, Student& s) {
  is >> s.name >> s.midtermGrade >> s.finalGrade;

  std::cout << std::endl << "Name: " << s.name << std::endl
            << " - Md: " << s.midtermGrade << std::endl
            << " - Fn: " << s.finalGrade << std::endl;

  read_hw(is, s.homework);

  return is;
}

int main()
{
  Student record;

  std::vector<Student> students;

  while (read(std::cin, record)) {}

  return 0;
}
</code>```

答:
If you have specific requirements for how the decision is to be made whether something is a double or not, you have to write code that implements those requirements. The standard permits any leading characters that could be part of a valid floating point representation to be discarded. Letters like "e", "i", "n" and "f" can be part of a valid floating point representation.

For why this kind of coding is never a good idea, see Falsehoods Programmers Believe About Names, particularly number 15.

Body:
A little bit of background - I'm new to learning C++. I'm working through Accelerated C++ and following things along. In chapter 4, the code I've got doesn't quite work as the book suggests, and I've double-checked all my of code to make sure I'm not mis-typing something from their example (I can't see any errors, anyway).

I have the following struct and two functions:

struct Student {
  std::string        name;
  double             midtermGrade, finalGrade;
  std::vector<double>homework;
};

std::istream& read(std::istream& is, Student& s) {
  is >> s.name >> s.midtermGrade >> s.finalGrade;

  std::cout << std::endl << "Name: " << s.name << std::endl
            << " - Md: " << s.midtermGrade << std::endl
            << " - Fn: " << s.finalGrade << std::endl;

  read_hw(is, s.homework);

  return is;
}

std::istream& read_hw(std::istream& in, std::vector<double>& hw) {
  if (in) {
    hw.clear();

    double h;

    while (in >> h) {
      std::cout << " - Hw: " << h << std::endl;
      hw.push_back(h);
    }

    in.clear();
  }

  return in;
}

In int main() I'm calling that code like this:

Student record;
while (read(std::cin, record)) {

If I compile and run, then paste (or type) in the following input, I get the following output:

// Input
Johnny 70 80 50 Fred 95 90 100 Joe 40 40 50

// Output
Name: Johnny
 - Md: 70
 - Fn: 80
 - Hw: 50

Name: red
 - Md: 95
 - Fn: 90
 - Hw: 100

Name: Joe
 - Md: 40
 - Fn: 40
 - Hw: 50

As you can see, "Fred" has become "red". I've tried this with a whole bunch of names; anything starting with A-F is affected by the same issue, which caused me to suspect it may be a hexadecimal issue. However, "Nick" becomes "k" and "Xander" simply becomes "r".

I'm utterly baffled. Do you have any idea what's going on?

As requested, here's a MCVE:

#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

struct Student {
  std::string        name;
  double             midtermGrade, finalGrade;
  std::vector<double>homework;
};

std::istream& read_hw(std::istream& in, std::vector<double>& hw) {
  if (in) {
    hw.clear();

    double h;

    while (in >> h) {
      std::cout << " - Hw: " << h << std::endl;
      hw.push_back(h);
    }

    in.clear();
  }

  return in;
}

std::istream& read(std::istream& is, Student& s) {
  is >> s.name >> s.midtermGrade >> s.finalGrade;

  std::cout << std::endl << "Name: " << s.name << std::endl
            << " - Md: " << s.midtermGrade << std::endl
            << " - Fn: " << s.finalGrade << std::endl;

  read_hw(is, s.homework);

  return is;
}

int main()
{
  Student record;

  std::vector<Student> students;

  while (read(std::cin, record)) {}

  return 0;
}


问:
How can I stop processing of non-existent domains?
Our website is allowing any prefix/subdomain before the domain.

So if our site is www.domain.com, then the server is allowing;
www.anything.domain.com, where 'anything' can be literally anything, and it displays whatever is on the page that actually exists.

So, www.anything.domain.com/something.php displays the content that should only be accessible via www.domain.com/something.php.

Is there any way using .htaccess to stop this from happening, or redirect it to the version that does actually exist?

Or does this need to be done on the server?

Does anyone know why this is being allowed?

答:
Ideally, this should be configured in server configuration files (also, you can configure DNS to simply not resolve unwanted hostnames, but that is for another question probably).

If you don't have access to server configuration, you can do it in .htaccess:

```<code># to block access if any domain except example.com or www.example.com was used
RewriteEngine On
RewriteCond %{HTTP_HOST}  !=www.example.com
RewriteCond %{HTTP_HOST}  !=example.com
RewriteRule ^ - [F]
</code>```

or

```<code># if any domain except example.com or www.example.com was used,
# redirect the request to www.example
RewriteEngine On
RewriteCond %{HTTP_HOST}  !=www.example.com
RewriteCond %{HTTP_HOST}  !=example.com
RewriteRule ^ http://www.example.com%{REQUEST_URI} [R=301]
</code>```

Body:
Ideally, this should be configured in server configuration files (also, you can configure DNS to simply not resolve unwanted hostnames, but that is for another question probably).

If you don't have access to server configuration, you can do it in .htaccess:

# to block access if any domain except example.com or www.example.com was used
RewriteEngine On
RewriteCond %{HTTP_HOST}  !=www.example.com
RewriteCond %{HTTP_HOST}  !=example.com
RewriteRule ^ - [F]

or

# if any domain except example.com or www.example.com was used,
# redirect the request to www.example
RewriteEngine On
RewriteCond %{HTTP_HOST}  !=www.example.com
RewriteCond %{HTTP_HOST}  !=example.com
RewriteRule ^ http://www.example.com%{REQUEST_URI} [R=301]


问:
Can a Slicer be applied to multiple Values?
Using Excel 2010.

I'm not even sure how to word this question but here goes:
I have a pivot chart that displays 4 pieces of info by Help desk by Month.

Screenshot of pivot table fields

I can add slicers to the resulting chart for the Month Yr and Service Desk but I'm wondering if it's possible to add a slicer for the Values?  The managers may only want to see Calls and Emails in the chart or just see Portal or whatever and I'd hate for them to have to go to the source pivot table and remove the data element from Pivot Table Field List.

Screenshot of resulting chart (certain proprietary info is purposely cut off)

Is this possible and if so, how?

Thank you.

答:
Yes you can do this, but it will require some VBA. I've previously written code to do this that you can find at the following link:
Converting multiple variables into values with excel pivot tables or power pivot</p>


问:
jquery - get elements by tag within a specific div?
I'm trying to get all input elements within a certain div, but it seems to return all inputs on any given page... is there a way to do this?</p>

```<code>if($('#umi-form')) {
          var inputs = document.getElementsByTagName('input');
}
</code>```

答:
Your if() test will always evaluate true. You should use the length property in the if().

```<code>var uform = $('#umi-form');
if(uform.length) {
    var inputs = uform.find('input');
}
</code>```

If you were hoping to get a nodeList instead of a jQuery object, do this:

```<code>var uform = $('#umi-form');
if(uform[0]) {
    var inputs = uform[0].getElementsByTagName('input');
}
</code>```

Body:
I'm trying to get all input elements within a certain div, but it seems to return all inputs on any given page... is there a way to do this?

if($('#umi-form')) {
          var inputs = document.getElementsByTagName('input');
}

Body:
Your if() test will always evaluate true. You should use the length property in the if().

var uform = $('#umi-form');
if(uform.length) {
    var inputs = uform.find('input');
}

If you were hoping to get a nodeList instead of a jQuery object, do this:

var uform = $('#umi-form');
if(uform[0]) {
    var inputs = uform[0].getElementsByTagName('input');
}


问:
PyQt4 to PyQt5 -> mainFrame() deprecated, need fix to load web pages
I'm doing Sentdex's PyQt4 YouTube tutorial right here. I'm trying to follow along but use PyQt5 instead. It's a simple web scraping app. I followed along with Sentdex's tutorial and I got here:

Now I'm trying to write the same application with PyQt5 and this is what I have:

```<code>import os
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl, QEventLoop
from PyQt5.QtWebEngineWidgets import QWebEnginePage
from bs4 import BeautifulSoup
import requests

class Client(QWebEnginePage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.loadFinished.connect(self._loadFinished)
        self.load(QUrl(url))
        self.app.exec_()

    def _loadFinished(self):
        self.app.quit()

url = 'https://pythonprogramming.net/parsememcparseface/'
client_response = Client(url)

#I think the issue is here at LINE 26
source = client_response.mainFrame().toHtml()

soup = BeautifulSoup(source, "html.parser")
js_test = soup.find('p', class_='jstest')
print(js_test.text)
</code>```

When I run this, I get the message:

```<code>source = client_response.mainFrame().toHtml()
AttributeError: 'Client' object has no attribute 'mainFrame'
</code>```

I've tried a few different solutions but none work. Any help would be appreciated.

EDIT

Logging QUrl(url) on line 15 returns this value:

PyQt5.QtCore.QUrl('https://pythonprogramming.net/parsememcparseface/')

When I try source = client_response.load(QUrl(url)) for line 26, I end up with the message:

File "test3.py", line 28, in <module>
          soup = BeautifulSoup(source, "html.parser")
        File "/Users/MYNAME/.venv/qtproject/lib/python3.6/site-packages/bs4/__init__.py", line 192, in __init__
          elif len(markup) <= 256 and (
      TypeError: object of type 'NoneType' has no len()

When I try source = client_response.url() I get:

```<code>soup = BeautifulSoup(source, "html.parser")
      File "/Users/MYNAME/.venv/qtproject/lib/python3.6/site-packages/bs4/__init__.py", line 192, in __init__
        elif len(markup) <= 256 and (
    TypeError: object of type 'QUrl' has no len()
</code>```

答:
you must call the QWebEnginePage::toHtml() inside the definition of the class. QWebEnginePage::toHtml() takes a pointer function or a lambda as a parameter, and this pointer function must in turn take a parameter of 'str' type (this is the parameter that contains the page's html). Here is sample code below.

```<code>import bs4 as bs
import sys
import urllib.request
from PyQt5.QtWebEngineWidgets import QWebEnginePage
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl

class Page(QWebEnginePage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.html = ''
        self.loadFinished.connect(self._on_load_finished)
        self.load(QUrl(url))
        self.app.exec_()

    def _on_load_finished(self):
        self.html = self.toHtml(self.Callable)
        print('Load finished')

    def Callable(self, html_str):
        self.html = html_str
        self.app.quit()

def main():
    page = Page('https://pythonprogramming.net/parsememcparseface/')
    soup = bs.BeautifulSoup(page.html, 'html.parser')
    js_test = soup.find('p', class_='jstest')
    print js_test.text

if __name__ == '__main__': main()
</code>```

Body:
I'm doing Sentdex's PyQt4 YouTube tutorial right here. I'm trying to follow along but use PyQt5 instead. It's a simple web scraping app. I followed along with Sentdex's tutorial and I got here:

Now I'm trying to write the same application with PyQt5 and this is what I have:

import os
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl, QEventLoop
from PyQt5.QtWebEngineWidgets import QWebEnginePage
from bs4 import BeautifulSoup
import requests

class Client(QWebEnginePage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.loadFinished.connect(self._loadFinished)
        self.load(QUrl(url))
        self.app.exec_()

    def _loadFinished(self):
        self.app.quit()

url = 'https://pythonprogramming.net/parsememcparseface/'
client_response = Client(url)

#I think the issue is here at LINE 26
source = client_response.mainFrame().toHtml()

soup = BeautifulSoup(source, "html.parser")
js_test = soup.find('p', class_='jstest')
print(js_test.text)

When I run this, I get the message:

source = client_response.mainFrame().toHtml()
AttributeError: 'Client' object has no attribute 'mainFrame'

I've tried a few different solutions but none work. Any help would be appreciated.

EDIT

Logging QUrl(url) on line 15 returns this value:

PyQt5.QtCore.QUrl('https://pythonprogramming.net/parsememcparseface/')

When I try source = client_response.load(QUrl(url)) for line 26, I end up with the message:

File "test3.py", line 28, in <module>
          soup = BeautifulSoup(source, "html.parser")
        File "/Users/MYNAME/.venv/qtproject/lib/python3.6/site-packages/bs4/__init__.py", line 192, in __init__
          elif len(markup) <= 256 and (
      TypeError: object of type 'NoneType' has no len()

When I try source = client_response.url() I get:

soup = BeautifulSoup(source, "html.parser")
      File "/Users/MYNAME/.venv/qtproject/lib/python3.6/site-packages/bs4/__init__.py", line 192, in __init__
        elif len(markup) <= 256 and (
    TypeError: object of type 'QUrl' has no len()

Body:
you must call the QWebEnginePage::toHtml() inside the definition of the class. QWebEnginePage::toHtml() takes a pointer function or a lambda as a parameter, and this pointer function must in turn take a parameter of 'str' type (this is the parameter that contains the page's html). Here is sample code below.

import bs4 as bs
import sys
import urllib.request
from PyQt5.QtWebEngineWidgets import QWebEnginePage
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl

class Page(QWebEnginePage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.html = ''
        self.loadFinished.connect(self._on_load_finished)
        self.load(QUrl(url))
        self.app.exec_()

    def _on_load_finished(self):
        self.html = self.toHtml(self.Callable)
        print('Load finished')

    def Callable(self, html_str):
        self.html = html_str
        self.app.quit()

def main():
    page = Page('https://pythonprogramming.net/parsememcparseface/')
    soup = bs.BeautifulSoup(page.html, 'html.parser')
    js_test = soup.find('p', class_='jstest')
    print js_test.text

if __name__ == '__main__': main()


问:
How to copy some records from TableA to TableB with slick-streaming and akka-streaming
There are two tables TableA and TableB.

I need to copy some records from TableA to TableB. I use slick-3.0 and use the following way:

```<code>import akka.stream._
import akka.stream.scaladsl._
...

//{{ READ DATA FROM TABLE A
val q = TableA.filter(somePredicate).result
val source = Source.fromPublisher {
      db.stream(q.result).mapResult { r =>
        val record: RecordA = someTransformation(r)
        record
      }
    }.grouped(50) // grouping because I want to write records in batch mode
//}}

//{{ WRITE DATA TO TABLE B
val f:Future[Done] = source.runWith(Sink.foreach { batch: Seq[RecordA] =>
      //TODO how to write batch to TableB asynchronously?
      val insertAction = TableB ++= batch  // insert batch to table
      val fInsert: Future[_] = db.run(insertAction)
      Await.result(fInsert, ...)           // #1 this works only with blocking
})
//}}
</code>```

But I've faced with an issue - how to write batch to TableB asynchronously (see TODO). Now the above code works with blocking to inner future only (see #1 comment). Is there a right way for implementing that task asynchronously?

答:
use mapAsync it expects a future to be returned and exposes the "unwrapped" result in the next stage.

```<code>source.mapAsync(4){batch: Seq[RecordA] =>
      val insertAction = TableB ++= batch  // insert batch to table
      db.run(insertAction)
}).to(Sink.ignore).run
</code>```

Body:
There are two tables TableA and TableB.

I need to copy some records from TableA to TableB. I use slick-3.0 and use the following way:

import akka.stream._
import akka.stream.scaladsl._
...

//{{ READ DATA FROM TABLE A
val q = TableA.filter(somePredicate).result
val source = Source.fromPublisher {
      db.stream(q.result).mapResult { r =>
        val record: RecordA = someTransformation(r)
        record
      }
    }.grouped(50) // grouping because I want to write records in batch mode
//}}

//{{ WRITE DATA TO TABLE B
val f:Future[Done] = source.runWith(Sink.foreach { batch: Seq[RecordA] =>
      //TODO how to write batch to TableB asynchronously?
      val insertAction = TableB ++= batch  // insert batch to table
      val fInsert: Future[_] = db.run(insertAction)
      Await.result(fInsert, ...)           // #1 this works only with blocking
})
//}}

But I've faced with an issue - how to write batch to TableB asynchronously (see TODO). Now the above code works with blocking to inner future only (see #1 comment). Is there a right way for implementing that task asynchronously?

Body:
use mapAsync it expects a future to be returned and exposes the "unwrapped" result in the next stage.

source.mapAsync(4){batch: Seq[RecordA] =>
      val insertAction = TableB ++= batch  // insert batch to table
      db.run(insertAction)
}).to(Sink.ignore).run


问:
JSON Parsing using Swift 3
I am calling a soap service in my application. I am getting this response in JSON from server

```<code>{
  "CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "IsCorporate":false,
  "ID":48,
  "Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "GroupID":null,
  "GroupName":null,
  "CustomerID":48
}
</code>```

I have tried what online tutorial suggests but I am not able to parse data. It gives me error that "Invalid value around character 0." My Code is this

```<code> let is_URL: String = "http://labs2.unitedtracker.com/WTService.asmx?op=GetTerminalNumber"

    let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
    let session = URLSession.shared

    lobj_Request.httpMethod = "POST"
    lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
    lobj_Request.addValue("labs2.unitedtracker.com", forHTTPHeaderField: "Host")
    lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    lobj_Request.addValue(String(is_SoapMessage.characters.count), forHTTPHeaderField: "Content-Length")
    lobj_Request.addValue("http://tempuri.org/GetTerminalNumber", forHTTPHeaderField: "SOAPAction")

    let task = session.dataTask(with: lobj_Request as URLRequest, completionHandler: {data, response, error -> Void in

        do {
            if let data = data,
                let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                let customerID = json["CustomerID"] as? [[String: Any]] {
                print(customerID)
            }
        } catch {
            print("Error deserializing JSON: \(error)")
        }

        if error != nil
        {
            print("Error: " + String(describing: error))
        }
    })
    task.resume()
</code>```

Can anyone suggest me what is wrong i m doing. And how should be such JSON response from Soap Service should be parsed.

Here is complete response from my Server.

```<code><?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetAuthenticateUserResponse xmlns="http://tempuri.org/"><GetAuthenticateUserResult>[{"CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ","IsCorporate":false,"ID":48,"Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ","GroupID":null,"GroupName":null,"CustomerID":48}]</GetAuthenticateUserResult></GetAuthenticateUserResponse></soap:Body></soap:Envelope>
</code>```

答:
The mistake is you wrapping String to [[String:Any]]

Instead of this:

```<code>if let data = data,
    let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
    let customerID = json["CustomerID"] as? [[String: Any]] {
        print(customerID)
}
</code>```

try this:

```<code>if let data = data,
   let json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]],
   let customerID = json["CustomerID"] as? String {
       print(customerID)
}
</code>```

Title: JSON Parsing using Swift 3

Body:
I am calling a soap service in my application. I am getting this response in JSON from server

{
  "CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "IsCorporate":false,
  "ID":48,
  "Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "GroupID":null,
  "GroupName":null,
  "CustomerID":48
}

I have tried what online tutorial suggests but I am not able to parse data. It gives me error that "Invalid value around character 0." My Code is this

 let is_URL: String = "http://labs2.unitedtracker.com/WTService.asmx?op=GetTerminalNumber"

    let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
    let session = URLSession.shared

    lobj_Request.httpMethod = "POST"
    lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
    lobj_Request.addValue("labs2.unitedtracker.com", forHTTPHeaderField: "Host")
    lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    lobj_Request.addValue(String(is_SoapMessage.characters.count), forHTTPHeaderField: "Content-Length")
    lobj_Request.addValue("http://tempuri.org/GetTerminalNumber", forHTTPHeaderField: "SOAPAction")

    let task = session.dataTask(with: lobj_Request as URLRequest, completionHandler: {data, response, error -> Void in

        do {
            if let data = data,
                let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                let customerID = json["CustomerID"] as? [[String: Any]] {
                print(customerID)
            }
        } catch {
            print("Error deserializing JSON: \(error)")
        }

        if error != nil
        {
            print("Error: " + String(describing: error))
        }
    })
    task.resume()

Can anyone suggest me what is wrong i m doing. And how should be such JSON response from Soap Service should be parsed.

Here is complete response from my Server.

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetAuthenticateUserResponse xmlns="http://tempuri.org/"><GetAuthenticateUserResult>[{"CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ","IsCorporate":false,"ID":48,"Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ","GroupID":null,"GroupName":null,"CustomerID":48}]</GetAuthenticateUserResult></GetAuthenticateUserResponse></soap:Body></soap:Envelope>

Body:
The mistake is you wrapping String to [[String:Any]]

Instead of this:

if let data = data,
    let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
    let customerID = json["CustomerID"] as? [[String: Any]] {
        print(customerID)
}

try this:

if let data = data,
   let json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]],
   let customerID = json["CustomerID"] as? String {
       print(customerID)
}


问:
extract word from string in sql server
I need to extract part of a string in sql server. Lets say I have this string in a column...

```<code>Name1=Bill Gates&Name2=Microsoft&Address1=The streetadress
</code>```

How can I extract the text that is equal to Name2 eg Microsoft?

答:
```<code>declare @string varchar(100) = 'Name1=Bill Gates&Name2=Microsoft&Address1=The streetadress'

select replace(PARSENAME (replace(@string, '&', '.'), 2), 'Name2=', '');
</code>```

Title: extract word from string in sql server

Body:
I need to extract part of a string in sql server. Lets say I have this string in a column...

Name1=Bill Gates&Name2=Microsoft&Address1=The streetadress

How can I extract the text that is equal to Name2 eg Microsoft?