问:
Linq to ad, disconnectedcontext exception fired
I have an exception which is fired when I test some code of mine using the library Linq to AD.

I am using a repository with this function :

```<code> public UserAD GetUser(string username)
        {
            UserAD user = null;
            using (Root = CreateDirectoryEntry())
            {
                var users = new DirectorySource<UserAD>(Root, SearchScope.Subtree);

                user = users.Where(x => x.AccountName == username)
                    .AsEnumerable()
                    .SingleOrDefault();             //not supported in LDAP; alternative in-memory SingleOrDefault

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

This works fine when I call it directly:

```<code>[TestMethod]
        public void RepositoryUtenteAD_GetUser()
        {
            UserAD user = repositoryAD.GetUser("TestAD_OK");

            Assert.AreEqual("blablabla", user.DistinguishedName);

            Assert.IsFalse(user.AccountDisabled);
        }
</code>```

But I may use another method which will call GetUser:

```<code>[TestMethod]
        public void RepositoryUtenteAD_AutenticazioneUtente_Authentication()
        {
            IAutenticazione auth = repositoryAD.AutenticazioneUtente("TestAD_OK", "TestAD_OK");
            Assert.IsTrue(auth.IsAuthenticated);
        }
</code>```

and the Authentication method is as follows (cleared of meaning and details, the error remaining there) :

```<code>public IAutenticazione AutenticazioneUtente(string username, string password)
        {
            bool IsWhyNotAuthentifiedFound = false;
            IAutenticazione authenticazione = new Autenticazione();

            UserAD user = GetUser(username);
            return authenticazione;
}
</code>```

The test is running fine, the assert is giving me the good value, but after the Cleanup of my test I have a disconnectedcontext exception fired. I assume it comes from the Interop.Adsi dll I use.

In GetUser(username) Should I copy everything I have in my UserAD to make a clone and so be clear off context...? Or is there a more clever way to approach?

Thanks for your reading!

答:
Found the solution even if it is a strange one. The bug only happens when running the test in debug mode, if i choose run instead of debug, everything is fine.

That close the chapter. Thanks for your reading.

Body:
I have an exception which is fired when I test some code of mine using the library Linq to AD.

I am using a repository with this function :

 public UserAD GetUser(string username)
        {
            UserAD user = null;
            using (Root = CreateDirectoryEntry())
            {
                var users = new DirectorySource<UserAD>(Root, SearchScope.Subtree);

                user = users.Where(x => x.AccountName == username)
                    .AsEnumerable()
                    .SingleOrDefault();             //not supported in LDAP; alternative in-memory SingleOrDefault

            }
            return user;
        }

This works fine when I call it directly:

[TestMethod]
        public void RepositoryUtenteAD_GetUser()
        {
            UserAD user = repositoryAD.GetUser("TestAD_OK");

            Assert.AreEqual("blablabla", user.DistinguishedName);

            Assert.IsFalse(user.AccountDisabled);
        }

But I may use another method which will call GetUser:

[TestMethod]
        public void RepositoryUtenteAD_AutenticazioneUtente_Authentication()
        {
            IAutenticazione auth = repositoryAD.AutenticazioneUtente("TestAD_OK", "TestAD_OK");
            Assert.IsTrue(auth.IsAuthenticated);
        }

and the Authentication method is as follows (cleared of meaning and details, the error remaining there) :

public IAutenticazione AutenticazioneUtente(string username, string password)
        {
            bool IsWhyNotAuthentifiedFound = false;
            IAutenticazione authenticazione = new Autenticazione();

            UserAD user = GetUser(username);
            return authenticazione;
}

The test is running fine, the assert is giving me the good value, but after the Cleanup of my test I have a disconnectedcontext exception fired. I assume it comes from the Interop.Adsi dll I use.

In GetUser(username) Should I copy everything I have in my UserAD to make a clone and so be clear off context...? Or is there a more clever way to approach?

Thanks for your reading!


来源: stackexchange

问:
Connect variables of the program with a function
My program has to take an integer N from the user (e.g. 5), creates a list of N integer random numbers from 1 up to 20 (e.g. [1,15,12,19,5]) and with the use of a function, calculates the average and the standard deviation of these numbers. My program so far is:

```<code>import random
import math

def stats(calculation):
    '''
    [9,20,15,9,11,19,2,4,16,8] -> MO = 11.30, SD = 6.07
    '''

    L=[]
    total = 0
    mathsum = 0

    for i in range(0,N,1):
        x=random.randint(1,20)
        L.append(x)

    for num in L:
        total += num

    MO = (total)/N

    for i in range(0,N,1):
        mathsum +=(L[i]-MO)**2

    sd = math.sqrt((1/(N-1))*mathsum)
    return N, L, '{:2.2f}'.format(MO), '{:2.2f}'.format(sd)

N=int(input('Give integer: '))
results = stats(N)
print('Number of integers: ', N)
print('List: ',L)
print('Average: ', MO, end='\t')
print('Standard deviation: ', sd)
</code>```

It shows only the number of the List, but after that it gives error and cannot print the other three elements (L, MO, sd).

What is the problem?

答:
There are some design issues with your code which lead to te error you are getting.

Your function accepts an argument (calculation) but doesn't do anything with it. Instead it relies on N being a global variable. This is usually considered a bad design.

Your function returns a tuple but your calling code doesn't do anything with it. Instead it tries to access local variables that were created inside the function which causes the NameError.

As a fix, I suggest passing the information correctly to the function, and the function should return a dictionary instead of a tuple (which will allow clearer access to the returned values rather than remembering indexes).

```<code>def stats(n):
    '''
    [9,20,15,9,11,19,2,4,16,8] -> MO = 11.30, SD = 6.07
    '''

    L = []
    total = 0
    mathsum = 0

    for i in range(0, n, 1):
        x = random.randint(1, 20)
        L.append(x)

    for num in L:
        total += num

    MO = total / n

    for i in range(0, n):
        mathsum += (L[i] - MO) ** 2

    sd = math.sqrt((1 / (n - 1)) * mathsum)
    return {'n': n,
            'numbers': L,
            'average': '{:2.2f}'.format(MO),
            'sd': '{:2.2f}'.format(sd)}

n = int(input('Give integer: '))
results = stats(n)
print('Number of integers: ', results['n'])
print('List: ', results['numbers'])
print('Average: ', results['average'], end='\t')
print('Standard deviation: ', results['sd'])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My program has to take an integer N from the user (e.g. 5), creates a list of N integer random numbers from 1 up to 20 (e.g. [1,15,12,19,5]) and with the use of a function, calculates the average and the standard deviation of these numbers. My program so far is:

import random
import math

def stats(calculation):
    '''
    [9,20,15,9,11,19,2,4,16,8] -> MO = 11.30, SD = 6.07
    '''

    L=[]
    total = 0
    mathsum = 0

    for i in range(0,N,1):
        x=random.randint(1,20)
        L.append(x)

    for num in L:
        total += num

    MO = (total)/N

    for i in range(0,N,1):
        mathsum +=(L[i]-MO)**2

    sd = math.sqrt((1/(N-1))*mathsum)
    return N, L, '{:2.2f}'.format(MO), '{:2.2f}'.format(sd)

N=int(input('Give integer: '))
results = stats(N)
print('Number of integers: ', N)
print('List: ',L)
print('Average: ', MO, end='\t')
print('Standard deviation: ', sd)

It shows only the number of the List, but after that it gives error and cannot print the other three elements (L, MO, sd).

What is the problem?

Body:
There are some design issues with your code which lead to te error you are getting.

Your function accepts an argument (calculation) but doesn't do anything with it. Instead it relies on N being a global variable. This is usually considered a bad design.

Your function returns a tuple but your calling code doesn't do anything with it. Instead it tries to access local variables that were created inside the function which causes the NameError.

As a fix, I suggest passing the information correctly to the function, and the function should return a dictionary instead of a tuple (which will allow clearer access to the returned values rather than remembering indexes).

def stats(n):
    '''
    [9,20,15,9,11,19,2,4,16,8] -> MO = 11.30, SD = 6.07
    '''

    L = []
    total = 0
    mathsum = 0

    for i in range(0, n, 1):
        x = random.randint(1, 20)
        L.append(x)

    for num in L:
        total += num

    MO = total / n

    for i in range(0, n):
        mathsum += (L[i] - MO) ** 2

    sd = math.sqrt((1 / (n - 1)) * mathsum)
    return {'n': n,
            'numbers': L,
            'average': '{:2.2f}'.format(MO),
            'sd': '{:2.2f}'.format(sd)}

n = int(input('Give integer: '))
results = stats(n)
print('Number of integers: ', results['n'])
print('List: ', results['numbers'])
print('Average: ', results['average'], end='\t')
print('Standard deviation: ', results['sd'])


问:
windows batch file eq was unexpected at this time
I am writing a windows batch script that will Install a service. First, I need to find if the service already exists. If the service exists, it has to check the state. If the state is running, it has to stop and delete the service.

This is my code : test.bat. I am running this from command line.

```<code>for /F "tokens=3 delims=: " %%H in ('sc query "IBMLibertyProfile" ^| findstr "STATE" ') do (
  if /I "%%H" EQ "RUNNING" (
   sc stop "IBMLibertyProfile"
  )
)
</code>```

I am getting error :

C:>test1.bat EQ was unexpected at this time.

C:>  if /I "%H" EQ "RUNNING" (

How to solve this error?

答:
Try this:

```<code>@rem If the service doesn't exist, exit.
@sc query IBMLibertyProfile > NUL 2>&1
@if %ERRORLEVEL% neq 0 @exit /b 0

@rem If the service is already stopped, delete it.
@sc query IBMLibertyProfile | findstr /s "STOPPED" > NUL 2>&1
@if %ERRORLEVEL% neq 0 @goto :DeleteService

@rem No matter it's state, tell it to stop.
@sc stop IBMLibertyProfile

@rem Wait for it to stop.
@set _WaitLoopCount=0
:StoppedWait
@if _WaitLoopCount equ 10 @goto :ServiceWaitTimeout
@timeout /t 3 > NUL 2>&1
@sc query IBMLibertyProfile | findstr /s "STOPPED" > NUL 2>&1
@if %ERRORLEVEL% neq 0 @goto :StoppedWait

@rem Delete the service and exit.
:DeleteService
@sc delete IBMLibertyProfile
@exit /b 0

:ServiceWaitTimeout
@echo Service failed to reach the STOPPED state. Reboot the computer and try again.
</code>```

NOTE: If your service is not well behaved, the script might hang. I'll leave it to you to work out how to deal with sc delete failures.

Body:
I am writing a windows batch script that will Install a service. First, I need to find if the service already exists. If the service exists, it has to check the state. If the state is running, it has to stop and delete the service.

This is my code : test.bat. I am running this from command line.

for /F "tokens=3 delims=: " %%H in ('sc query "IBMLibertyProfile" ^| findstr "STATE" ') do (
  if /I "%%H" EQ "RUNNING" (
   sc stop "IBMLibertyProfile"
  )
)

I am getting error :

C:>test1.bat EQ was unexpected at this time.

C:>  if /I "%H" EQ "RUNNING" (

How to solve this error?

Body:
Try this:

@rem If the service doesn't exist, exit.
@sc query IBMLibertyProfile > NUL 2>&1
@if %ERRORLEVEL% neq 0 @exit /b 0

@rem If the service is already stopped, delete it.
@sc query IBMLibertyProfile | findstr /s "STOPPED" > NUL 2>&1
@if %ERRORLEVEL% neq 0 @goto :DeleteService

@rem No matter it's state, tell it to stop.
@sc stop IBMLibertyProfile

@rem Wait for it to stop.
@set _WaitLoopCount=0
:StoppedWait
@if _WaitLoopCount equ 10 @goto :ServiceWaitTimeout
@timeout /t 3 > NUL 2>&1
@sc query IBMLibertyProfile | findstr /s "STOPPED" > NUL 2>&1
@if %ERRORLEVEL% neq 0 @goto :StoppedWait

@rem Delete the service and exit.
:DeleteService
@sc delete IBMLibertyProfile
@exit /b 0

:ServiceWaitTimeout
@echo Service failed to reach the STOPPED state. Reboot the computer and try again.

NOTE: If your service is not well behaved, the script might hang. I'll leave it to you to work out how to deal with sc delete failures.


问:
What is fx:id of JavaFX Alert OK Button?
I use TestFX framework for test my javaFX application.
I test my application like that :

```<code>@Test
public void shouldClickOnDeletMarkerButton() {
    FxRobot bot = new FxRobot();
    bot.robotContext();
    bot.clickOn("#deleteMarkerButton");
    bot.clickOn("javafx.scene.control.Alert.CANCEL_BUTTON"); //This doesn't work.
}
</code>```

I would like him to click on the OK button of JavaFX Alert Dialogs, but I have not found a fx:id.

What is fx:id of JavaFX Alert OK Button ?

EDIT : I solve my problem, FxRobot know "read", it is enough make this :

```<code>@Test
public void shouldClickOnDeletMarkerButtonWhenAnyMarkerAsBeenCreated() {
    bot.robotContext();
    bot.clickOn("#deleteMarkerButton");
    bot.clickOn("OK"); //Target text / Target Button / ...
}
</code>```

答:
```<code><?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<BorderPane fx:controller="sample.Controller" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
   <Button text="Click me!" fx:id="button" onAction="#clickAction" BorderPane.alignment="CENTER"/>
</BorderPane>
</code>```

Assigning an fx:id value to an element, as shown in the code for the Button control, creates a variable in the document's namespace, which you can refer to from elsewhere in the code.

Body:
I use TestFX framework for test my javaFX application.
I test my application like that :

@Test
public void shouldClickOnDeletMarkerButton() {
    FxRobot bot = new FxRobot();
    bot.robotContext();
    bot.clickOn("#deleteMarkerButton");
    bot.clickOn("javafx.scene.control.Alert.CANCEL_BUTTON"); //This doesn't work.
}

I would like him to click on the OK button of JavaFX Alert Dialogs, but I have not found a fx:id.

What is fx:id of JavaFX Alert OK Button ?

EDIT : I solve my problem, FxRobot know "read", it is enough make this :

@Test
public void shouldClickOnDeletMarkerButtonWhenAnyMarkerAsBeenCreated() {
    bot.robotContext();
    bot.clickOn("#deleteMarkerButton");
    bot.clickOn("OK"); //Target text / Target Button / ...
}

Body:
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<BorderPane fx:controller="sample.Controller" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
   <Button text="Click me!" fx:id="button" onAction="#clickAction" BorderPane.alignment="CENTER"/>
</BorderPane>

Assigning an fx:id value to an element, as shown in the code for the Button control, creates a variable in the document's namespace, which you can refer to from elsewhere in the code.


问:
Anyway to have undertow path template with wildcards
I need to handle requests that may have a number of sub path elements (that I can ignore), e.g. the following would all map to the same handler:

/abc?type=a

/abc/foo?type=a

/abc/foo/bar?type=a

The only code I have come up with is:

```<code>Handlers.pathTemplate().add("/{id}", handler).add("/{id}/foo", handler).add("/{id}/foo/bar", handler);
</code>```

But this is not ideal as I need to define each possible path, is there anyway to allow (and ignore) any number of paths following my prefix e.g.

```<code>Handlers.pathTemplate().add("/{id}*", handler)
</code>```

Handlers.path().addPrefixPath allows this sort of matching but then I would lose the path template variables.

答:
I would like you to reference this question. Routing template format for undertow

The accepted answer clearly outlines how to preserve the path variables through Handlers.routing()

Body:
I need to handle requests that may have a number of sub path elements (that I can ignore), e.g. the following would all map to the same handler:

/abc?type=a

/abc/foo?type=a

/abc/foo/bar?type=a

The only code I have come up with is:

Handlers.pathTemplate().add("/{id}", handler).add("/{id}/foo", handler).add("/{id}/foo/bar", handler);

But this is not ideal as I need to define each possible path, is there anyway to allow (and ignore) any number of paths following my prefix e.g.

Handlers.pathTemplate().add("/{id}*", handler)

Handlers.path().addPrefixPath allows this sort of matching but then I would lose the path template variables.


问:
Forming multidimensional array
I am having trouble in forming multidimensional array.
I am receiving data from database, then I need to create array which will be sent over api to make packing.

First I get values from form

```<code>$idNaloga = $_GET['idNaloga'];
$duzina = $_GET['duzina'];
$sirina = $_GET['sirina'];
$visina = $_GET['visina'];
</code>```

First I make query for trailer:

```<code>$truckTrailer = array(
    'w' => $sirina,
    'h' => $visina,
    'd' => $duzina,
    'max_wg' => '15000',
    'id' => $kamion1
);
</code>```

Then I use those values to make query

```<code>$stmt = "SELECT DISTINCT(nazivPanela) as paket FROM `paneli_pakovanja_2017` WHERE idNaloga = $idNaloga";

$q = $conn->query($stmt);

$nazivPaketa = array();

while($r = $q -> fetch()){
    $nazivPaketa[] = $r['paket'];
}
</code>```

Once I get names of packets, I make query for each packet. In this query I should get for each packet array that looks

```<code>array(
    'w' => '100',
    'h' => '90',
    'd' => '1350',
    'q' => '18',
    'vr' => '1',
    'wg' => '0',
    'id' => 'Paket'
),
</code>```

But I dont, I get only one array from the query below, but I should get 7.

```<code>foreach($nazivPaketa as $paket) {

$stmt2 = "SELECT max(duzina) as duzina, visinaPaketa, sirinaPaketa, nazivPanela FROM `paneli_pakovanja_2017` WHERE idNaloga = $idNaloga AND nazivPanela = $paket";

$q = $conn -> query($stmt2);

while($r=$q->fetch()) {

    $paketi = array(
        'w' => $r['sirinaPaketa'],
        'h' => $r['visinaPaketa'],
        'd' => $r['duzina'],
        'q' => '1',
        'vr' => '1',
        'wg' => '0',
        'id' => $r['nazivPanela']
    );
}
}
</code>```

At the end I need form array which will look like:

```<code>$data = array(

'bins' => array( // this array I have it is truck trailer

                array(
                        'w' => '250',
                        'h' => '360',
                        'd' => '1360',
                        'max_wg' => '15000',
                        'id' => '1'
                    )
            ),

'items' => array(  *// array I should get from $paketi
                array(
                        'w' => '100',
                        'h' => '90',
                        'd' => '1350',
                        'q' => '18',
                        'vr' => '1',
                        'wg' => '0',
                        'id' => 'Paket'
                    ),
                array(
                        'w' => '100',
                        'h' => '90',
                        'd' => '900',
                        'q' => '23',
                        'vr' => '1',
                        'wg' => '0',
                        'id' => 'Paket2'
                ),
                array(
                    'w' => '100',
                    'h' => '90',
                    'd' => '400',
                    'q' => '18',
                    'vr' => '1',
                    'wg' => '0',
                    'id' => 'Paket'
                )
            ),
</code>```

Don't know am I using right way, but need some kind of assistance

答:
You are overwriting the $packeti variable in the loop... You should instead add the value to an array.

```<code>$q = $conn -> query($stmt2);
$paketi = array();
while($r=$q->fetch()) {

    $paketi[] = array(
        'w' => $r['sirinaPaketa'],
        'h' => $r['visinaPaketa'],
        'd' => $r['duzina'],
        'q' => '1',
        'vr' => '1',
        'wg' => '0',
        'id' => $r['nazivPanela']
    );
}
}
</code>```

the $packeti[] will make sure your package information gets added to the array instead of completely replacing it.

Title: Forming multidimensional array

Body:
I am having trouble in forming multidimensional array.
I am receiving data from database, then I need to create array which will be sent over api to make packing.

First I get values from form

$idNaloga = $_GET['idNaloga'];
$duzina = $_GET['duzina'];
$sirina = $_GET['sirina'];
$visina = $_GET['visina'];

First I make query for trailer:

$truckTrailer = array(
    'w' => $sirina,
    'h' => $visina,
    'd' => $duzina,
    'max_wg' => '15000',
    'id' => $kamion1
);

Then I use those values to make query

$stmt = "SELECT DISTINCT(nazivPanela) as paket FROM `paneli_pakovanja_2017` WHERE idNaloga = $idNaloga";

$q = $conn->query($stmt);

$nazivPaketa = array();

while($r = $q -> fetch()){
    $nazivPaketa[] = $r['paket'];
}

Once I get names of packets, I make query for each packet. In this query I should get for each packet array that looks

array(
    'w' => '100',
    'h' => '90',
    'd' => '1350',
    'q' => '18',
    'vr' => '1',
    'wg' => '0',
    'id' => 'Paket'
),

But I dont, I get only one array from the query below, but I should get 7.

foreach($nazivPaketa as $paket) {

$stmt2 = "SELECT max(duzina) as duzina, visinaPaketa, sirinaPaketa, nazivPanela FROM `paneli_pakovanja_2017` WHERE idNaloga = $idNaloga AND nazivPanela = $paket";

$q = $conn -> query($stmt2);

while($r=$q->fetch()) {

    $paketi = array(
        'w' => $r['sirinaPaketa'],
        'h' => $r['visinaPaketa'],
        'd' => $r['duzina'],
        'q' => '1',
        'vr' => '1',
        'wg' => '0',
        'id' => $r['nazivPanela']
    );
}
}

At the end I need form array which will look like:

$data = array(

'bins' => array( // this array I have it is truck trailer

                array(
                        'w' => '250',
                        'h' => '360',
                        'd' => '1360',
                        'max_wg' => '15000',
                        'id' => '1'
                    )
            ),

'items' => array(  *// array I should get from $paketi
                array(
                        'w' => '100',
                        'h' => '90',
                        'd' => '1350',
                        'q' => '18',
                        'vr' => '1',
                        'wg' => '0',
                        'id' => 'Paket'
                    ),
                array(
                        'w' => '100',
                        'h' => '90',
                        'd' => '900',
                        'q' => '23',
                        'vr' => '1',
                        'wg' => '0',
                        'id' => 'Paket2'
                ),
                array(
                    'w' => '100',
                    'h' => '90',
                    'd' => '400',
                    'q' => '18',
                    'vr' => '1',
                    'wg' => '0',
                    'id' => 'Paket'
                )
            ),

Don't know am I using right way, but need some kind of assistance

Body:
You are overwriting the $packeti variable in the loop... You should instead add the value to an array.

$q = $conn -> query($stmt2);
$paketi = array();
while($r=$q->fetch()) {

    $paketi[] = array(
        'w' => $r['sirinaPaketa'],
        'h' => $r['visinaPaketa'],
        'd' => $r['duzina'],
        'q' => '1',
        'vr' => '1',
        'wg' => '0',
        'id' => $r['nazivPanela']
    );
}
}

the $packeti[] will make sure your package information gets added to the array instead of completely replacing it.


问:
Angular 2 - How to refresh my view datas?
I'm new in Angular 2 and I need some advices concerning my personal project.
I have two components, a formation list and a form to update my datas.
I work with services calls to update my datas and to display my formations list.
I had a problem with the datas update on my view but I resolved it by adding a timer to refresh datas.
I'm not fan of this solution because my service is called every second in my formation list interface :/

My question : What's the better way to refresh my view in my case ?

Thx in advance

答:
You should take a look at EventEmitter in Angular 2+.
Since you successfully updated your data in update form, an event should be emitted to the list component.
In list component, you should listen to the emitted event then refresh data by a service call.
This is an example of using EventEmitter:
https://developer.telerik.com/topics/web-development/component-event-binding-output-angular-2/</p>


问:
How to insert variable string into multiline comment in Python?
I want do define a Python function with exec like this:

```<code>exec """def my_func(alpha = 'a'):
  return alpha"""
</code>```

It works. However, for a specific reason I want to to define the alpha = 'a' in a separate string:

```<code>s = "alpha = 'a'"
exec """def my_func(s):
  return alpha"""
</code>```

but this one doesn't work. Is there a way to insert a string variable content into multiline comment string this way?

答:
Use the format function:</p>

```<code>s = "alpha = 'a'"
exec """def my_func({}):
  return alpha""".format(s)
</code>```

Body:
I want do define a Python function with exec like this:

exec """def my_func(alpha = 'a'):
  return alpha"""

It works. However, for a specific reason I want to to define the alpha = 'a' in a separate string:

s = "alpha = 'a'"
exec """def my_func(s):
  return alpha"""

but this one doesn't work. Is there a way to insert a string variable content into multiline comment string this way?

Body:
Use the format function:

s = "alpha = 'a'"
exec """def my_func({}):
  return alpha""".format(s)


问:
sending parameter to onHide event in ngx-bootstrap modal
I am opening a modal using component as a template, everything is ok, modal opens and I am subscribing to onHide Event, subscription works also.

but I have a challenge here,
I want to send a specific reason for example: 'message added successfully' as the reason . how can I do that?
how can I send a specific string as a reason?

currently, I am trying to set a value in MessageAddComponent component and access it in parent component using bsModalRef.Content, but it is not a good idea.

```<code>newMessage() {
    this.bsModalRef = this.modalService.show(MessageAddComponent, {
        class: 'modal-lg'
    });
    this.subscriptions.push(this.modalService.onHide.subscribe((reason: string) => {
        // i dont like this approach
        if (this.bsModalRef.content.anySuccessfulAction) {
            console.log('foo and bar')
        }
        this.unsubscribe();
    }));
}
</code>```

答:
found  solution finally:

inject BsModalService in the  component that is used as modal and then set dismiss reason as bellow

```<code>this.modalService.setDismissReason(theReason);
</code>```

Body:
I am opening a modal using component as a template, everything is ok, modal opens and I am subscribing to onHide Event, subscription works also.

but I have a challenge here,
I want to send a specific reason for example: 'message added successfully' as the reason . how can I do that?
how can I send a specific string as a reason?

currently, I am trying to set a value in MessageAddComponent component and access it in parent component using bsModalRef.Content, but it is not a good idea.

newMessage() {
    this.bsModalRef = this.modalService.show(MessageAddComponent, {
        class: 'modal-lg'
    });
    this.subscriptions.push(this.modalService.onHide.subscribe((reason: string) => {
        // i dont like this approach
        if (this.bsModalRef.content.anySuccessfulAction) {
            console.log('foo and bar')
        }
        this.unsubscribe();
    }));
}

Body:
found  solution finally:

inject BsModalService in the  component that is used as modal and then set dismiss reason as bellow

this.modalService.setDismissReason(theReason);


问:
What's the difference between express-session and cookie-session?
I am new with Express. As Express 4.x has removed bundled middlewares.

Any middleware I want to use should be required. When I read the README with express-session and cookie-session on github, I find it hard to understand the difference.

I tried to write some simple code to figure it out. I ran it twice for each middleware.

var express = require('express')
  , cookieParser = require('cookie-parser')
  , session = require('cookie-session')
  , express_sess = require('express-session')
  , app = express();

app.use(cookieParser())
app.use(session({ keys: ['abc'], name: 'user' }));
//app.use(express_sess({ secret: 'abc', key: 'user'}));
app.get('/', function (req, res, next) {
    res.end(JSON.stringify(req.cookies));
    console.log(req.session)
    console.log(req.cookies)
});

app.listen(3000);
```
<p>For <code>cookie-session</code>, I always get <code>{}</code> in my terminal.</p>
<p>For <code>express-session</code>, I get things like this.</p>
<pre class="lang-js prettyprint-override"><code>req.session: { cookie: {
     path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true
   }
}

req.cookie: {user: 's:aJ97vKA5CCwxqdTj0AV1siRQ.fWusS5+qfCKICtwkfrzcZ/Gq8P0Qdx/kx8mTBhoOhGU'}
</code>```

It really confuses me. So how to explain the result with the basic use? And what's the difference between them? When should I use them?

答:
The basic difference between both these relates to how and where is the session data being stored.
Cookie session is basically used for lightweight session applications where the session data is stored in a cookie but within the client [browser], whereas, Express Session stores just a mere session identifier within a cookie in the client end, whilst storing the session data entirely on the server.
Cookie Session is helpful in applications where no database is used in the back-end. However, the session data cannot exceed the cookie size. On conditions where a database is used, it acts like a cache to stop frequent database lookups which is expensive.

ContentLicense: CC BY-SA 4.0

Body:
I am new with Express. As Express 4.x has removed bundled middlewares.

Any middleware I want to use should be required. When I read the README with express-session and cookie-session on github, I find it hard to understand the difference.

I tried to write some simple code to figure it out. I ran it twice for each middleware.

var express = require('express')
  , cookieParser = require('cookie-parser')
  , session = require('cookie-session')
  , express_sess = require('express-session')
  , app = express();

app.use(cookieParser())
app.use(session({ keys: ['abc'], name: 'user' }));
//app.use(express_sess({ secret: 'abc', key: 'user'}));
app.get('/', function (req, res, next) {
    res.end(JSON.stringify(req.cookies));
    console.log(req.session)
    console.log(req.cookies)
});

app.listen(3000);

For cookie-session, I always get {} in my terminal.

For express-session, I get things like this.

req.session: { cookie: {
     path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true
   }
}

req.cookie: {user: 's:aJ97vKA5CCwxqdTj0AV1siRQ.fWusS5+qfCKICtwkfrzcZ/Gq8P0Qdx/kx8mTBhoOhGU'}

It really confuses me. So how to explain the result with the basic use? And what's the difference between them? When should I use them?


问:
Python- writing json file as list of dictionaries
I am writing a json file from information extracted from a url. How do I print each element of the dictionary on a separate line?

This is my current code:

```<code>dct=[{"name": name,
        "cuisine": cuisine,
        "price-range": price,
        "address": address,
        "rating": rating,
        "reviews": score,
        "district": district,
        "url": link
        }]

    with open('openrice_data.json', 'a') as file:
        file.write(json.dumps(dct))
</code>```

For example, it currently prints like this:

```<code>[{"cuisine": ["Japanese", "Hot Pot", "Buffet"], "rating": [3.5], "address": [22.3825, 114.1901], "url": ["https://www.openrice.com/en/hongkong/r-wagyu-more-sha-tin-japanese-hot-pot-r172321"], "reviews": [35, 17, 8], "name": "Wagyu More", "price-range": ["$101-200"], "district": ["Sha Tin"]}]
</code>```

I would like it to print like this:

```<code>[
{"name": "Chan Kun Kee",
"cuisine": ["Guang Dong", "Dai Pai Dong"],
"price-range": "$51-100",
"address": [22.3884, 114.1958],
"rating": 3.5,
"reviews": [216, 95, 38],
"district": "Shatin",
"url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
}
]
</code>```

答:
Other people have remarked on using pprint, but I would like to add that pprint prints the representation of the Python values in your dictionary. They are not always the same as their JSON counterparts, for example:

```<code>>>> from pprint import pprint
>>> d1 = {"value": None}
>>> pprint(d1)
{'value': None}
</code>```

(the correct JSON serialization here is {"value": null}

The better option, for these kinds of values, is to use json.dump or json.dumps. You can use the indent parameter to sort of make it print one line per element. Note though that this will also print each list element into their separate lines (so you don't exactly get one line per one JSON key):

```<code>>>> d2 = [
... {"name": "Chan Kun Kee",
... "cuisine": ["Guang Dong", "Dai Pai Dong"],
... "price-range": "$51-100",
... "address": [22.3884, 114.1958],
... "rating": 3.5,
... "reviews": [216, 95, 38],
... "district": "Shatin",
... "url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
... }
... ]
>>> print(json.dumps(d2, indent=2))
[
  {
    "name": "Chan Kun Kee",
    "cuisine": [
      "Guang Dong",
      "Dai Pai Dong"
    ],
    "price-range": "$51-100",
    "address": [
      22.3884,
      114.1958
    ],
    "rating": 3.5,
    "reviews": [
      216,
      95,
      38
    ],
    "district": "Shatin",
    "url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
  }
]
</code>```

But you're guaranteed to at least always get the correct JSON. Plus, you can also extend the behavior with your own JSON encoder. This allows you, for example, to serialize Python datetime objects into JSON strings.

Body:
I am writing a json file from information extracted from a url. How do I print each element of the dictionary on a separate line?

This is my current code:

dct=[{"name": name,
        "cuisine": cuisine,
        "price-range": price,
        "address": address,
        "rating": rating,
        "reviews": score,
        "district": district,
        "url": link
        }]

    with open('openrice_data.json', 'a') as file:
        file.write(json.dumps(dct))

For example, it currently prints like this:

[{"cuisine": ["Japanese", "Hot Pot", "Buffet"], "rating": [3.5], "address": [22.3825, 114.1901], "url": ["https://www.openrice.com/en/hongkong/r-wagyu-more-sha-tin-japanese-hot-pot-r172321"], "reviews": [35, 17, 8], "name": "Wagyu More", "price-range": ["$101-200"], "district": ["Sha Tin"]}]

I would like it to print like this:

[
{"name": "Chan Kun Kee",
"cuisine": ["Guang Dong", "Dai Pai Dong"],
"price-range": "$51-100",
"address": [22.3884, 114.1958],
"rating": 3.5,
"reviews": [216, 95, 38],
"district": "Shatin",
"url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
}
]

Body:
Other people have remarked on using pprint, but I would like to add that pprint prints the representation of the Python values in your dictionary. They are not always the same as their JSON counterparts, for example:

>>> from pprint import pprint
>>> d1 = {"value": None}
>>> pprint(d1)
{'value': None}

(the correct JSON serialization here is {"value": null}

The better option, for these kinds of values, is to use json.dump or json.dumps. You can use the indent parameter to sort of make it print one line per element. Note though that this will also print each list element into their separate lines (so you don't exactly get one line per one JSON key):

>>> d2 = [
... {"name": "Chan Kun Kee",
... "cuisine": ["Guang Dong", "Dai Pai Dong"],
... "price-range": "$51-100",
... "address": [22.3884, 114.1958],
... "rating": 3.5,
... "reviews": [216, 95, 38],
... "district": "Shatin",
... "url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
... }
... ]
>>> print(json.dumps(d2, indent=2))
[
  {
    "name": "Chan Kun Kee",
    "cuisine": [
      "Guang Dong",
      "Dai Pai Dong"
    ],
    "price-range": "$51-100",
    "address": [
      22.3884,
      114.1958
    ],
    "rating": 3.5,
    "reviews": [
      216,
      95,
      38
    ],
    "district": "Shatin",
    "url": "www.openrice.com/en/hongkong/r-chan-kun-kee-sha-tin-guangdong-r7918"
  }
]

But you're guaranteed to at least always get the correct JSON. Plus, you can also extend the behavior with your own JSON encoder. This allows you, for example, to serialize Python datetime objects into JSON strings.


问:
Fill Combo box from DB with first custom item
I Have a combo box in c# windows form which is being filled with Groups Names from SQL DB. While inserting new data user selects any group name which he/she want to make parent group if none selected new group would be simple not child. Here is what I want.

My expected combobox:

Here is my current code

```<code>private void fill_combobox(){
             main_class.sqlcmd.CommandText = "SELECT
            GroupID,GroupName FROM Groups";
            SqlDataReader sqlReader = main_class.sqlcmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("GroupID", typeof(int));
            dt.Columns.Add("GroupName", typeof(string));
            dt.Load(sqlReader);
            parent_group_combobox.ValueMember = "GroupID";
            parent_group_combobox.DisplayMember = "GroupName";
            parent_group_combobox.DataSource = dt;
            sqlReader.Close();
          }
</code>```

And my expected code is something thing like

```<code>private void fill_combobox(){
             main_class.sqlcmd.CommandText = "SELECT
            GroupID,GroupName FROM Groups";
            SqlDataReader sqlReader = main_class.sqlcmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("GroupID", typeof(int));
            dt.Columns.Add("GroupName", typeof(string));
            dt.Load(sqlReader);
    parent_group_combobox.Items.Insert(0,"--None--");
            parent_group_combobox.ValueMember = "GroupID";
            parent_group_combobox.DisplayMember = "GroupName";
            parent_group_combobox.DataSource = dt;
            sqlReader.Close();
          }
</code>```

答:
You can add "None" to the DataTable before loading the content from database:</p>

```<code>...
dt.Rows.Add(0, "None");
dt.Load(sqlReader);
...
</code>```

Body:
I Have a combo box in c# windows form which is being filled with Groups Names from SQL DB. While inserting new data user selects any group name which he/she want to make parent group if none selected new group would be simple not child. Here is what I want.

My expected combobox:

Here is my current code

private void fill_combobox(){
             main_class.sqlcmd.CommandText = "SELECT
            GroupID,GroupName FROM Groups";
            SqlDataReader sqlReader = main_class.sqlcmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("GroupID", typeof(int));
            dt.Columns.Add("GroupName", typeof(string));
            dt.Load(sqlReader);
            parent_group_combobox.ValueMember = "GroupID";
            parent_group_combobox.DisplayMember = "GroupName";
            parent_group_combobox.DataSource = dt;
            sqlReader.Close();
          }

And my expected code is something thing like

private void fill_combobox(){
             main_class.sqlcmd.CommandText = "SELECT
            GroupID,GroupName FROM Groups";
            SqlDataReader sqlReader = main_class.sqlcmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("GroupID", typeof(int));
            dt.Columns.Add("GroupName", typeof(string));
            dt.Load(sqlReader);
    parent_group_combobox.Items.Insert(0,"--None--");
            parent_group_combobox.ValueMember = "GroupID";
            parent_group_combobox.DisplayMember = "GroupName";
            parent_group_combobox.DataSource = dt;
            sqlReader.Close();
          }

Body:
You can add "None" to the DataTable before loading the content from database:

...
dt.Rows.Add(0, "None");
dt.Load(sqlReader);
...


问:
python - combining and interpolating 2 dataframe column and creating unique number list from it
I have this 2 integer column in my dataframe

```<code>from | to
----------
 1   |  4
 2   |  4
 3   |  6
</code>```

I want to combine them as such I am getting a list like this:
[1, 4, 2, 4, 3, 6]

Then I want to create a unique value from that list like this:
[1, 4, 2, 3, 6]

How do I do that?

For combining and interpolating the 2 dataframes, I tried this:

' '.join(df['from'].astype('str') + ' ' + df['to'].astype('str'))

But I have to convert them to string first, join all the string, then split it again. I am looking for more straightforward way to do it.

For finding unique values in a list, I tried:

list(set(non_unique_list))

But the resulting list is: [1,2,3,4,6] which is something that I am not looking for. I am looking for in particularly this order: [1, 4, 2, 3, 6]

答:
It looks like stack and unique are what you're looking for:

```<code>>>> import pandas as pd
>>> df = pd.DataFrame({'from': [1,2,3], 'to':[4,4,6]})
>>> df
   from  to
0     1   4
1     2   4
2     3   6
>>> df.stack()
0  from    1
   to      4
1  from    2
   to      4
2  from    3
   to      6
dtype: int64
>>> df.stack().unique()
array([1, 4, 2, 3, 6])
</code>```

Body:
I have this 2 integer column in my dataframe

from | to
----------
 1   |  4
 2   |  4
 3   |  6

I want to combine them as such I am getting a list like this:
[1, 4, 2, 4, 3, 6]

Then I want to create a unique value from that list like this:
[1, 4, 2, 3, 6]

How do I do that?

For combining and interpolating the 2 dataframes, I tried this:

' '.join(df['from'].astype('str') + ' ' + df['to'].astype('str'))

But I have to convert them to string first, join all the string, then split it again. I am looking for more straightforward way to do it.

For finding unique values in a list, I tried:

list(set(non_unique_list))

But the resulting list is: [1,2,3,4,6] which is something that I am not looking for. I am looking for in particularly this order: [1, 4, 2, 3, 6]

Body:
It looks like stack and unique are what you're looking for:

>>> import pandas as pd
>>> df = pd.DataFrame({'from': [1,2,3], 'to':[4,4,6]})
>>> df
   from  to
0     1   4
1     2   4
2     3   6
>>> df.stack()
0  from    1
   to      4
1  from    2
   to      4
2  from    3
   to      6
dtype: int64
>>> df.stack().unique()
array([1, 4, 2, 3, 6])


问:
How to get the previous date in angular?
Please help me getting the previous dates in angular 4.

```<code>currentdate: Date;
this.currentdate = new Date();
console.log(this.datePipe.transform(this.currentdate, 'yyyy-MM-dd'));
</code>```

Here I got the date as 2017-11-13.

Now I need to get 2 days before date..

答:
Try this

let dte = new Date();
dte.setDate(dte.getDate() - 2);
console.log(dte.toString());```

Body:
Please help me getting the previous dates in angular 4.

currentdate: Date;
this.currentdate = new Date();
console.log(this.datePipe.transform(this.currentdate, 'yyyy-MM-dd'));

Here I got the date as 2017-11-13.

Now I need to get 2 days before date..


答:
The problem was the return statement that you were assigning to results but not unpacking. Take a look at the following:

```<code>import random
import math

def stats(size):
    '''
    [9,20,15,9,11,19,2,4,16,8] -> MO = 11.30, SD = 6.07
    '''

    L=[random.randint(1,20) for _ in range(size)]
    total = sum(L)
    MO = total / size
    mathsum = sum((x-MO)**2 for x in L)
    sd = math.sqrt((1/(size-1))*mathsum)
    return L, '{:2.2f}'.format(MO), '{:2.2f}'.format(sd)

N=int(input('Give integer: '))
results = stats(N)
print('Number of integers: ', N)
print('List: ', results[0])
print('Average: ', results[1], end='\t')
print('Standard deviation: ', results[2])
</code>```

Note that variables defined inside functions cannot be accessed by the outside scope. The reverse is possible but not recommended (globals used in functions). Since you are returning more that 1 values, the results become a tuple that you can index to get your stuff.

The mistakes aside, the logic of your code was sound but too verbose. Python allows you to write shorter, neater code.

Title: Connect variables of the program with a function

Body:
My program has to take an integer N from the user (e.g. 5), creates a list of N integer random numbers from 1 up to 20 (e.g. [1,15,12,19,5]) and with the use of a function, calculates the average and the standard deviation of these numbers. My program so far is:

import random
import math

def stats(calculation):
    '''
    [9,20,15,9,11,19,2,4,16,8] -> MO = 11.30, SD = 6.07
    '''

    L=[]
    total = 0
    mathsum = 0

    for i in range(0,N,1):
        x=random.randint(1,20)
        L.append(x)

    for num in L:
        total += num

    MO = (total)/N

    for i in range(0,N,1):
        mathsum +=(L[i]-MO)**2

    sd = math.sqrt((1/(N-1))*mathsum)
    return N, L, '{:2.2f}'.format(MO), '{:2.2f}'.format(sd)

N=int(input('Give integer: '))
results = stats(N)
print('Number of integers: ', N)
print('List: ',L)
print('Average: ', MO, end='\t')
print('Standard deviation: ', sd)

It shows only the number of the List, but after that it gives error and cannot print the other three elements (L, MO, sd).

What is the problem?

Body:
The problem was the return statement that you were assigning to results but not unpacking. Take a look at the following:

import random
import math

def stats(size):
    '''
    [9,20,15,9,11,19,2,4,16,8] -> MO = 11.30, SD = 6.07
    '''

    L=[random.randint(1,20) for _ in range(size)]
    total = sum(L)
    MO = total / size
    mathsum = sum((x-MO)**2 for x in L)
    sd = math.sqrt((1/(size-1))*mathsum)
    return L, '{:2.2f}'.format(MO), '{:2.2f}'.format(sd)

N=int(input('Give integer: '))
results = stats(N)
print('Number of integers: ', N)
print('List: ', results[0])
print('Average: ', results[1], end='\t')
print('Standard deviation: ', results[2])

Note that variables defined inside functions cannot be accessed by the outside scope. The reverse is possible but not recommended (globals used in functions). Since you are returning more that 1 values, the results become a tuple that you can index to get your stuff.

The mistakes aside, the logic of your code was sound but too verbose. Python allows you to write shorter, neater code.


问:
js async/await return promise
Doing just a simple function:

```<code> async function doAsync() {
 return await "test"
 }

 console.log(doAsync())
</code>```

Output: Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

What could be wrong?

答:
async functions return a promise.  Always.  You must use .then() or await on that promise to get the value.

```<code>doAsync().then(val => {
    console.log(val);
});
</code>```

While async and await sometimes let you write more synchronous-looking code inside the function itself, they don't fundamentally change asynchronous operations into synchronous ones.

An async function still returns a promise and the only way to get its value is to use .then() or await on it.  If you're returning a value up the chain, you will eventually need to use .then() to get the value.

See the MDN description for an async function.  Here's a quote:

Return value

A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.

Title: js async/await return promise

Body:
Doing just a simple function:

 async function doAsync() {
 return await "test"
 }

 console.log(doAsync())

Output: Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

What could be wrong?

Body:
async functions return a promise.  Always.  You must use .then() or await on that promise to get the value.

doAsync().then(val => {
    console.log(val);
});

While async and await sometimes let you write more synchronous-looking code inside the function itself, they don't fundamentally change asynchronous operations into synchronous ones.

An async function still returns a promise and the only way to get its value is to use .then() or await on it.  If you're returning a value up the chain, you will eventually need to use .then() to get the value.

See the MDN description for an async function.  Here's a quote:

Return value

A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.


问:
Laravel: Check if variable is being passed from controller
I'm trying to check if variable is being passed from controller but isn't working, the controller function looks like here:

```<code>public function editClient($id)
    {
        $client = Client::find($id);
       // $client_project = DB::table('client_project')->where('client_id',$id)->first()->project_id;
        //$project = DB::table('projects')->where('id',$client_project)->first();
        $client_projects = Client::find($id)->projects;
        return view('cms.public.views.clients.editclient', ['client' => $client, 'client_projects' => $client_projects]);

    }
</code>```

In the client blade I show the projects of each one with this code:

```<code><h3 class="h3client h3clienteedit">Proyectos de {{$client->name}}</h3>

          @foreach ($client_projects as $project)

            <div class="col-md-3 col3projectofclient">
              <h4 class="h4traductiontitle"><a href="/admin/project/{{$project->id}}/edit" class="atraductiontitle">{{$project->title}}</a></h4>
              <a href="/admin/project/{{$project->id}}/edit"><img src="{{ asset('/storage/projects/'.$project->slug.'/header.jpg') }}" class="imgprojectoneditclient"></a>
            </div>

@endforeach
</code>```

But I only want to show it when have projects if not i don't want to show de .

I'm trying to do it with this code:

```<code>@if ( !empty($client_projects['slug']))

//code

@endif
</code>```

答:
pass the variable directly

```<code>@if (!$client_projects)

//code

@endif
</code>```

or

```<code>@if ($client_projects->count())

//code

@endif
</code>```

more info

Body:
I'm trying to check if variable is being passed from controller but isn't working, the controller function looks like here:

public function editClient($id)
    {
        $client = Client::find($id);
       // $client_project = DB::table('client_project')->where('client_id',$id)->first()->project_id;
        //$project = DB::table('projects')->where('id',$client_project)->first();
        $client_projects = Client::find($id)->projects;
        return view('cms.public.views.clients.editclient', ['client' => $client, 'client_projects' => $client_projects]);

    }

In the client blade I show the projects of each one with this code:

Proyectos de {{$client->name}}

          @foreach ($client_projects as $project)

id}}/edit" class="atraductiontitle">{{$project->title}}

              id}}/edit">slug.'/header.jpg') }}" class="imgprojectoneditclient">

@endforeach

But I only want to show it when have projects if not i don't want to show de .

I'm trying to do it with this code:

@if ( !empty($client_projects['slug']))

//code

@endif

Body:
pass the variable directly

@if (!$client_projects)

//code

@endif

or

@if ($client_projects->count())

//code

@endif

more info


答:
Not tested but perhaps you could try like below. The variable $paketi is being overwritten on each iteration in loop but you need to store it's records for all queries so declare an array before the outer loop and add contents from inner loop to it

```<code>$data=array();

foreach( $nazivPaketa as $paket ) {

    $stmt2 = "SELECT max(duzina) as duzina, visinaPaketa, sirinaPaketa, nazivPanela
        FROM `paneli_pakovanja_2017`
        WHERE idNaloga = $idNaloga AND nazivPanela = $paket";

    $q = $conn->query( $stmt2 );

    $paketi=array();

    while( $r=$q->fetch() ) {
        $paketi[] = array(
            'w' => $r['sirinaPaketa'],
            'h' => $r['visinaPaketa'],
            'd' => $r['duzina'],
            'q' => '1',
            'vr' => '1',
            'wg' => '0',
            'id' => $r['nazivPanela']
        );
    }
    $data[]=$paketi;
}

echo '```',print_r($data,1),'
';
```

<p>To get the other array added you could try:</p>

```$data['bins']=$truckTrailer; /* assuming `$truckTrailer` is an array */
```

Title: Forming multidimensional array

Body:
I am having trouble in forming multidimensional array.
I am receiving data from database, then I need to create array which will be sent over api to make packing.

First I get values from form

$idNaloga = $_GET['idNaloga'];
$duzina = $_GET['duzina'];
$sirina = $_GET['sirina'];
$visina = $_GET['visina'];

First I make query for trailer:

$truckTrailer = array(
    'w' => $sirina,
    'h' => $visina,
    'd' => $duzina,
    'max_wg' => '15000',
    'id' => $kamion1
);

Then I use those values to make query

$stmt = "SELECT DISTINCT(nazivPanela) as paket FROM `paneli_pakovanja_2017` WHERE idNaloga = $idNaloga";

$q = $conn->query($stmt);

$nazivPaketa = array();

while($r = $q -> fetch()){
    $nazivPaketa[] = $r['paket'];
}

Once I get names of packets, I make query for each packet. In this query I should get for each packet array that looks

array(
    'w' => '100',
    'h' => '90',
    'd' => '1350',
    'q' => '18',
    'vr' => '1',
    'wg' => '0',
    'id' => 'Paket'
),

But I dont, I get only one array from the query below, but I should get 7.

foreach($nazivPaketa as $paket) {

$stmt2 = "SELECT max(duzina) as duzina, visinaPaketa, sirinaPaketa, nazivPanela FROM `paneli_pakovanja_2017` WHERE idNaloga = $idNaloga AND nazivPanela = $paket";

$q = $conn -> query($stmt2);

while($r=$q->fetch()) {

    $paketi = array(
        'w' => $r['sirinaPaketa'],
        'h' => $r['visinaPaketa'],
        'd' => $r['duzina'],
        'q' => '1',
        'vr' => '1',
        'wg' => '0',
        'id' => $r['nazivPanela']
    );
}
}

At the end I need form array which will look like:

$data = array(

'bins' => array( // this array I have it is truck trailer

                array(
                        'w' => '250',
                        'h' => '360',
                        'd' => '1360',
                        'max_wg' => '15000',
                        'id' => '1'
                    )
            ),

'items' => array(  *// array I should get from $paketi
                array(
                        'w' => '100',
                        'h' => '90',
                        'd' => '1350',
                        'q' => '18',
                        'vr' => '1',
                        'wg' => '0',
                        'id' => 'Paket'
                    ),
                array(
                        'w' => '100',
                        'h' => '90',
                        'd' => '900',
                        'q' => '23',
                        'vr' => '1',
                        'wg' => '0',
                        'id' => 'Paket2'
                ),
                array(
                    'w' => '100',
                    'h' => '90',
                    'd' => '400',
                    'q' => '18',
                    'vr' => '1',
                    'wg' => '0',
                    'id' => 'Paket'
                )
            ),

Don't know am I using right way, but need some kind of assistance

Body:
Not tested but perhaps you could try like below. The variable $paketi is being overwritten on each iteration in loop but you need to store it's records for all queries so declare an array before the outer loop and add contents from inner loop to it

$data=array();

foreach( $nazivPaketa as $paket ) {

    $stmt2 = "SELECT max(duzina) as duzina, visinaPaketa, sirinaPaketa, nazivPanela
        FROM `paneli_pakovanja_2017`
        WHERE idNaloga = $idNaloga AND nazivPanela = $paket";

    $q = $conn->query( $stmt2 );

    $paketi=array();

    while( $r=$q->fetch() ) {
        $paketi[] = array(
            'w' => $r['sirinaPaketa'],
            'h' => $r['visinaPaketa'],
            'd' => $r['duzina'],
            'q' => '1',
            'vr' => '1',
            'wg' => '0',
            'id' => $r['nazivPanela']
        );
    }
    $data[]=$paketi;
}

echo '<pre>',print_r($data,1),'</div>';

To get the other array added you could try:

$data['bins']=$truckTrailer; /* assuming `$truckTrailer` is an array */


问:
to save docx as pdf in c# (.net) with policy label
i'm converting .docx files to .pdf with Microsoft.Office.Interop.Word library in C# (.Net Framework 4.6.2)

my code is:

```<code>    public static void DOCtoPDF(string docFullPath, string pdfFullPath)
    {
        Application appWord = new Application();
        var wordDocument = appWord.Documents.Open(docFullPath);

        wordDocument.SaveAs2(pdfFullPath, WdSaveFormat.wdFormatPDF);
        wordDocument.Close();
        appWord.Quit();
    }
</code>```

i'm taking this error while i am saving doc file:

how to solve this problem?

答:
As an alternative approach to Microsoft.Office.Interop.Word library, you may want to check out GemBox.Document library.

For example like this:

```<code>public static void DOCtoPDF(string docFullPath, string pdfFullPath)
{
    DocumentModel wordDocument = DocumentModel.Load(docFullPath);
    wordDocument.Save(pdfFullPath);
}
</code>```

Body:
i'm converting .docx files to .pdf with Microsoft.Office.Interop.Word library in C# (.Net Framework 4.6.2)

my code is:

    public static void DOCtoPDF(string docFullPath, string pdfFullPath)
    {
        Application appWord = new Application();
        var wordDocument = appWord.Documents.Open(docFullPath);

        wordDocument.SaveAs2(pdfFullPath, WdSaveFormat.wdFormatPDF);
        wordDocument.Close();
        appWord.Quit();
    }

i'm taking this error while i am saving doc file:

how to solve this problem?

Body:
As an alternative approach to Microsoft.Office.Interop.Word library, you may want to check out GemBox.Document library.

For example like this:

public static void DOCtoPDF(string docFullPath, string pdfFullPath)
{
    DocumentModel wordDocument = DocumentModel.Load(docFullPath);
    wordDocument.Save(pdfFullPath);
}


问:
Finding the longest palindrome within a string in Python
I'm trying to solve the Longest Palindromic Substring problem on LeetCode. The problem statement is:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

```<code>Input: "babad"

Output: "bab"
</code>```

Note: "aba" is also a valid answer.
  Example:

```<code>Input: "cbbd"

Output: "bb"
</code>```

I've come up with the following solution (including some test cases):

```<code>import pytest

class Solution:
    def longestPalindrome(self, s):
        candidate = ""
        longest = ""
        contains_palindrome = False
        for i, char in enumerate(s):
            if i == 0:
                candidate = char
            elif i == 1:
                if s[1] == s[0]:
                    candidate = self.get_palindrome(s, start=0, end=1)
            elif i >= 2:
                if char == s[i-1]:
                    candidate = self.get_palindrome(s, start=i-1, end=i)
                elif char == s[i-2]:
                    candidate = self.get_palindrome(s, start=i-2, end=i)
            if len(candidate) > len(longest):
                longest = candidate
        return longest

    @staticmethod
    def get_palindrome(s, start, end):
        palindrome = s[start:end+1]
        while end < len(s) - 1:
            if s[end+1] == s[start] and Solution.all_same(palindrome):
                end += 1
                palindrome += s[end]
            else:
                break
        while (start > 0) and (end < len(s) - 1):
            start -= 1
            end += 1
            if s[start] == s[end]:
                palindrome = s[start] + palindrome + s[end]
            else:
                break
        return palindrome

    @staticmethod
    def all_same(items):
        return all(item == items[0] for item in items)

def test_1():
    assert Solution().longestPalindrome("babad") == "bab"

def test_2():
    assert Solution().longestPalindrome("cbbd") == "bb"

def test_3():
    assert Solution().longestPalindrome("abba") == "abba"

def test_4():
    assert Solution().longestPalindrome("a") == "a"

def test_5():
    assert Solution().longestPalindrome("ccc") == "ccc"

def test_6():
    assert Solution().longestPalindrome("aaaa") == "aaaa"

def test_7():
    assert Solution().longestPalindrome("aaabaaaa") == "aaabaaa"

if __name__ == "__main__":
    pytest.main([__file__])
</code>```

The problem is that I get a "time limit exceeded" error:

My understanding is that the time complexity of this algorithm is O(n^2), since for every character it checks for a palindrome which could be up to n characters long. In LeetCode's solutions there are also O(n^2) algorithms (in Java).

I'm guessing that the time limit is a bit too stringent for Python, which is slower than Java. Or am I missing something and is the time complexity of my solution actually greater than O(n^2)?

答:
The test string that you failed on seems to consist of a's only. That's the worst case and it is actually O(n³) rather than O(n²), because there's another hidden loop in all_same. (At first, I also thought that the slice operator [:] on strings would do a copy, but that's not true.)

You need to call all_same, because you distinguish the cases "aa" and "aba" in your main function. But you don't need to do that in a loop, because you will be adding only the same letter over and oer in the first while loop in get_palindrome. A quick fix would therefore be to test whether all characters are the same only once:

```<code>    if Solution.all_same(palindrome):
        while end < len(s) - 1:
            if s[end+1] == s[start]:
                end += 1
                palindrome += s[end]
            else:
                break
</code>```

Now all_same os run on two- or three-letter strings and will be fast.

A better solution wouldn't require all_same at all. Why do you pass "aba" to the get_palindrome when you could just pass "b" and let that function do the rest of the work:

```<code>        elif i >= 2:
            if char == s[i-1]:
                candidate = self.get_palindrome(s, start=i-1, end=i)
            else:
                candidate = self.get_palindrome(s, start=i, end=i)
</code>```

Overall, the code looks rather untidy with all the breaks and unnecessary case distinctions. And why keep indices and palindrome as separate entities in get_palindrome, which you must keep in sync?

Here's a version that is tidier in my opinion:

```<code>class Solution:
    def longestPalindrome(self, s):
        longest = ""

        for i, _ in enumerate(s):
            candidate = self.get_palindrome(s, start = i, end = i)

            if len(candidate) > len(longest):
                longest = candidate

        return longest

    @staticmethod
    def get_palindrome(s, start, end):
        while end + 1 < len(s) and s[end+1] == s[start]:
            end += 1

        while start > 0 and end + 1 < len(s) and s[start - 1] == s[end + 1]:
            start -= 1
            end += 1

        return s[start:end + 1]
</code>```

Even so, there's room for improvement: For the string "aaaa", the code will still consider "aaaa", "aaa", "aa" and "a". The first while in get_palindrome will go all the way, but without chance to find a better hit. We can improve this by finding stretches of the same letter already in the main function:

```<code>class Solution:
    def longestPalindrome(self, s):
        longest = ""
        i = 0
        l = len(s)

        while i < l:
            end = i

            while end + 1 < l and s[end + 1] == s[i]:
                end += 1

            candidate = self.get_palindrome(s, i, end)

            if len(candidate) > len(longest):
                longest = candidate

            i = end + 1

        return longest

    @staticmethod
    def get_palindrome(s, start, end):
        while start > 0 and end + 1 < len(s) and s[start - 1] == s[end + 1]:
            start -= 1
            end += 1

        return s[start:end + 1]
</code>```

This will still not be ideal on strings like "abababab", but should be fast enough in your case.

Body:
I'm trying to solve the Longest Palindromic Substring problem on LeetCode. The problem statement is:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.
  Example:

Input: "cbbd"

Output: "bb"

I've come up with the following solution (including some test cases):

import pytest

class Solution:
    def longestPalindrome(self, s):
        candidate = ""
        longest = ""
        contains_palindrome = False
        for i, char in enumerate(s):
            if i == 0:
                candidate = char
            elif i == 1:
                if s[1] == s[0]:
                    candidate = self.get_palindrome(s, start=0, end=1)
            elif i >= 2:
                if char == s[i-1]:
                    candidate = self.get_palindrome(s, start=i-1, end=i)
                elif char == s[i-2]:
                    candidate = self.get_palindrome(s, start=i-2, end=i)
            if len(candidate) > len(longest):
                longest = candidate
        return longest

    @staticmethod
    def get_palindrome(s, start, end):
        palindrome = s[start:end+1]
        while end < len(s) - 1:
            if s[end+1] == s[start] and Solution.all_same(palindrome):
                end += 1
                palindrome += s[end]
            else:
                break
        while (start > 0) and (end < len(s) - 1):
            start -= 1
            end += 1
            if s[start] == s[end]:
                palindrome = s[start] + palindrome + s[end]
            else:
                break
        return palindrome

    @staticmethod
    def all_same(items):
        return all(item == items[0] for item in items)

def test_1():
    assert Solution().longestPalindrome("babad") == "bab"

def test_2():
    assert Solution().longestPalindrome("cbbd") == "bb"

def test_3():
    assert Solution().longestPalindrome("abba") == "abba"

def test_4():
    assert Solution().longestPalindrome("a") == "a"

def test_5():
    assert Solution().longestPalindrome("ccc") == "ccc"

def test_6():
    assert Solution().longestPalindrome("aaaa") == "aaaa"

def test_7():
    assert Solution().longestPalindrome("aaabaaaa") == "aaabaaa"

if __name__ == "__main__":
    pytest.main([__file__])

The problem is that I get a "time limit exceeded" error:

My understanding is that the time complexity of this algorithm is O(n^2), since for every character it checks for a palindrome which could be up to n characters long. In LeetCode's solutions there are also O(n^2) algorithms (in Java).

I'm guessing that the time limit is a bit too stringent for Python, which is slower than Java. Or am I missing something and is the time complexity of my solution actually greater than O(n^2)?

Body:
The test string that you failed on seems to consist of a's only. That's the worst case and it is actually O(n³) rather than O(n²), because there's another hidden loop in all_same. (At first, I also thought that the slice operator [:] on strings would do a copy, but that's not true.)

You need to call all_same, because you distinguish the cases "aa" and "aba" in your main function. But you don't need to do that in a loop, because you will be adding only the same letter over and oer in the first while loop in get_palindrome. A quick fix would therefore be to test whether all characters are the same only once:

    if Solution.all_same(palindrome):
        while end < len(s) - 1:
            if s[end+1] == s[start]:
                end += 1
                palindrome += s[end]
            else:
                break

Now all_same os run on two- or three-letter strings and will be fast.

A better solution wouldn't require all_same at all. Why do you pass "aba" to the get_palindrome when you could just pass "b" and let that function do the rest of the work:

        elif i >= 2:
            if char == s[i-1]:
                candidate = self.get_palindrome(s, start=i-1, end=i)
            else:
                candidate = self.get_palindrome(s, start=i, end=i)

Overall, the code looks rather untidy with all the breaks and unnecessary case distinctions. And why keep indices and palindrome as separate entities in get_palindrome, which you must keep in sync?

Here's a version that is tidier in my opinion:

class Solution:
    def longestPalindrome(self, s):
        longest = ""

        for i, _ in enumerate(s):
            candidate = self.get_palindrome(s, start = i, end = i)

            if len(candidate) > len(longest):
                longest = candidate

        return longest

    @staticmethod
    def get_palindrome(s, start, end):
        while end + 1 < len(s) and s[end+1] == s[start]:
            end += 1

        while start > 0 and end + 1 < len(s) and s[start - 1] == s[end + 1]:
            start -= 1
            end += 1

        return s[start:end + 1]

Even so, there's room for improvement: For the string "aaaa", the code will still consider "aaaa", "aaa", "aa" and "a". The first while in get_palindrome will go all the way, but without chance to find a better hit. We can improve this by finding stretches of the same letter already in the main function:

class Solution:
    def longestPalindrome(self, s):
        longest = ""
        i = 0
        l = len(s)

        while i < l:
            end = i

            while end + 1 < l and s[end + 1] == s[i]:
                end += 1

            candidate = self.get_palindrome(s, i, end)

            if len(candidate) > len(longest):
                longest = candidate

            i = end + 1

        return longest

    @staticmethod
    def get_palindrome(s, start, end):
        while start > 0 and end + 1 < len(s) and s[start - 1] == s[end + 1]:
            start -= 1
            end += 1

        return s[start:end + 1]

This will still not be ideal on strings like "abababab", but should be fast enough in your case.


问:
boost::multiprecision::pow with two cpp_int values
Is there a way to use boost::multiprecision::pow with two cpp_int values as the parameters? All I can find in the documentation has the parameters of type cpp_int for the base and int for the exponent. This seems very limiting.</p>

答: You may use boost::multiprecision::float and corresponding boost::multi precision::pow implementations.</p>


问:
Ionic 3. Unexpected token <
i've recently updated ionic to version 3.9.2 but an error occur when run "ionic cordova run android --device" or when i use Ionic DevApp.

When i execute the command on my smartphone Huawaei with android 7.0 all work perfectly, but i obtain error when run on my tablet samsung with android 4.4.4

Running "ionic doctor check" no issues detected.

The error is "Unexpected token <", no other details.

This is my package.json

```<code>"scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/animations": "5.0.0",
    "@angular/common": "5.0.0",
    "@angular/compiler": "5.0.0",
    "@angular/compiler-cli": "5.0.0",
    "@angular/core": "5.0.0",
    "@angular/forms": "5.0.0",
    "@angular/http": "5.0.0",
    "@angular/platform-browser": "5.0.0",
    "@angular/platform-browser-dynamic": "5.0.0",
    "@ionic-native/core": "4.4.0",
    "@ionic-native/email-composer": "4.4.0",
    "@ionic-native/facebook": "4.4.0",
    "@ionic-native/google-plus": "4.4.0",
    "@ionic-native/http": "4.4.0",
    "@ionic-native/launch-navigator": "4.4.0",
    "@ionic-native/onesignal": "4.4.0",
    "@ionic-native/splash-screen": "4.4.0",
    "@ionic-native/status-bar": "4.4.0",
    "@ionic-native/twitter-connect": "4.4.0",
    "@ionic/storage": "2.1.3",
    "@ngx-translate/core": "^8.0.0",
    "@ngx-translate/http-loader": "^2.0.0",
    "android-versions": "^1.2.1",
    "cordova-android": "^6.2.3",
    "cordova-ios": "^4.5.1",
    "cordova-plugin-actionsheet": "^2.3.3",
    "cordova-plugin-advanced-http": "^1.6.1",
    "cordova-plugin-compat": "^1.2.0",
    "cordova-plugin-device": "^1.1.4",
    "cordova-plugin-dialogs": "^1.3.3",
    "cordova-plugin-email-composer": "^0.8.11",
    "cordova-plugin-facebook4": "^1.9.1",
    "cordova-plugin-file": "^4.3.3",
    "cordova-plugin-googleplus": "^5.1.1",
    "cordova-plugin-ionic-webview": "^1.1.14",
    "cordova-plugin-splashscreen": "^4.0.3",
    "cordova-plugin-statusbar": "git+https://github.com/apache/cordova-plugin-statusbar.git",
    "cordova-plugin-whitelist": "^1.3.1",
    "cordova-sqlite-storage": "^2.0.4",
    "ionic-angular": "^3.9.2",
    "ionic-plugin-keyboard": "^2.2.1",
    "ionicons": "3.0.0",
    "onesignal-cordova-plugin": "^2.2.2",
    "rxjs": "5.5.2",
    "sw-toolbox": "3.6.0",
    "twitter-connect-plugin": "git+https://github.com/chroa/twitter-connect-plugin.git",
    "uk.co.workingedge.phonegap.plugin.launchnavigator": "^4.0.5",
    "web-animations-js": "^2.3.1",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "@ionic/app-scripts": "^3.1.0",
    "typescript": "2.4.2"
  },
  "description": "An Ionic project",
  "cordova": {
    "platforms": [
      "android",
      "ios"
    ],
    "plugins": {
      "cordova-plugin-device": {},
      "cordova-plugin-ionic-webview": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-statusbar": {},
      "cordova-plugin-whitelist": {},
      "ionic-plugin-keyboard": {},
      "uk.co.workingedge.phonegap.plugin.launchnavigator": {},
      "cordova-plugin-advanced-http": {},
      "cordova-sqlite-storage": {},
      "onesignal-cordova-plugin": {},
      "twitter-connect-plugin": {
        "FABRIC_KEY": "xxxxxxxxxxxxxxxxxxx",
        "TWITTER_KEY": "xxxxxxxxxxx",
        "TWITTER_SECRET": "xxxxxxxxxxxxxx"
      },
      "cordova-plugin-email-composer": {},
      "cordova-plugin-facebook4": {
        "APP_ID": "xxxxxxxxxxxxxxxx",
        "APP_NAME": "xxxxxxxxxx"
      },
      "cordova-plugin-googleplus": {
        "REVERSED_CLIENT_ID": "xxxxxxxxxx"
      }
    }
  }
</code>```

This is my system info

```<code>Ionic App Scripts: 3.1.0
Angular Core: 5.0.0
Angular Compiler CLI: 5.0.0
Node: 6.11.4
OS Platform: macOS Sierra
Navigator Platform: MacIntel
User Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:56.0) Gecko/20100101 Firefox/56.0
</code>```

This is my config.xml

```<code><widget id="XXXXX" version="14.0.2" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>xxxxxxx</name>
    <description>xxxxx</description>
    <author email="xxxxxxx" href="xxxxxxxxxxxx">xxxxxxxxx</author>
    <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <preference name="ScrollEnabled" value="false" />
    <preference name="android-minSdkVersion" value="16" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="FadeSplashScreenDuration" value="300" />
    <preference name="SplashShowOnlyFirstTime" value="false" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="3000" />
    <preference name="AutoHideSplashScreen" value="false" />
    <preference name="orientation" value="portrait" />
    <platform name="android">
        <allow-intent href="market:*" />
        <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png" />
        <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png" />
        <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png" />
        <icon density="xhdpi" src="resources/android/icon/drawable-xhdpi-icon.png" />
        <icon density="xxhdpi" src="resources/android/icon/drawable-xxhdpi-icon.png" />
        <icon density="xxxhdpi" src="resources/android/icon/drawable-xxxhdpi-icon.png" />
        <splash density="land-ldpi" src="resources/android/splash/drawable-land-ldpi-screen.png" />
        <splash density="land-mdpi" src="resources/android/splash/drawable-land-mdpi-screen.png" />
        <splash density="land-hdpi" src="resources/android/splash/drawable-land-hdpi-screen.png" />
        <splash density="land-xhdpi" src="resources/android/splash/drawable-land-xhdpi-screen.png" />
        <splash density="land-xxhdpi" src="resources/android/splash/drawable-land-xxhdpi-screen.png" />
        <splash density="land-xxxhdpi" src="resources/android/splash/drawable-land-xxxhdpi-screen.png" />
        <splash density="port-ldpi" src="resources/android/splash/drawable-port-ldpi-screen.png" />
        <splash density="port-mdpi" src="resources/android/splash/drawable-port-mdpi-screen.png" />
        <splash density="port-hdpi" src="resources/android/splash/drawable-port-hdpi-screen.png" />
        <splash density="port-xhdpi" src="resources/android/splash/drawable-port-xhdpi-screen.png" />
        <splash density="port-xxhdpi" src="resources/android/splash/drawable-port-xxhdpi-screen.png" />
        <splash density="port-xxxhdpi" src="resources/android/splash/drawable-port-xxxhdpi-screen.png" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
        <preference name="deployment-target" value="7.0" />
        <icon height="57" src="resources/ios/icon/icon.png" width="57" />
        <icon height="114" src="resources/ios/icon/icon@2x.png" width="114" />
        <icon height="40" src="resources/ios/icon/icon-40.png" width="40" />
        <icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" />
        <icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" />
        <icon height="50" src="resources/ios/icon/icon-50.png" width="50" />
        <icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" />
        <icon height="60" src="resources/ios/icon/icon-60.png" width="60" />
        <icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" />
        <icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" />
        <icon height="72" src="resources/ios/icon/icon-72.png" width="72" />
        <icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" />
        <icon height="76" src="resources/ios/icon/icon-76.png" width="76" />
        <icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" />
        <icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" />
        <icon height="29" src="resources/ios/icon/icon-small.png" width="29" />
        <icon height="58" src="resources/ios/icon/icon-small@2x.png" width="58" />
        <icon height="87" src="resources/ios/icon/icon-small@3x.png" width="87" />
        <splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" />
        <splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" />
        <splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" />
        <splash height="1242" src="resources/ios/splash/Default-Landscape-736h.png" width="2208" />
        <splash height="1536" src="resources/ios/splash/Default-Landscape@2x~ipad.png" width="2048" />
        <splash height="2048" src="resources/ios/splash/Default-Landscape@~ipadpro.png" width="2732" />
        <splash height="768" src="resources/ios/splash/Default-Landscape~ipad.png" width="1024" />
        <splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" />
        <splash height="2732" src="resources/ios/splash/Default-Portrait@~ipadpro.png" width="2048" />
        <splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" />
        <splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" />
        <splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" />
        <splash height="2732" src="resources/ios/splash/Default@2x~universal~anyany.png" width="2732" />
    </platform>
    <allow-navigation href="http://192.168.1.6:8100" />
    <engine name="android" spec="^6.2.3" />
    <engine name="ios" spec="^4.5.1" />
    <plugin name="cordova-plugin-device" spec="^1.1.4" />
    <plugin name="cordova-plugin-ionic-webview" spec="^1.1.14" />
    <plugin name="cordova-plugin-splashscreen" spec="^4.0.3" />
    <plugin name="cordova-plugin-statusbar" spec="git+https://github.com/apache/cordova-plugin-statusbar.git" />
    <plugin name="cordova-plugin-whitelist" spec="^1.3.1" />
    <plugin name="ionic-plugin-keyboard" spec="^2.2.1" />
    <plugin name="uk.co.workingedge.phonegap.plugin.launchnavigator" spec="^4.0.5" />
    <plugin name="cordova-plugin-advanced-http" spec="^1.6.1" />
    <plugin name="cordova-sqlite-storage" spec="^2.0.4" />
    <plugin name="onesignal-cordova-plugin" spec="^2.2.2" />
    <plugin name="twitter-connect-plugin" spec="git+https://github.com/chroa/twitter-connect-plugin.git">
        <variable name="FABRIC_KEY" value="xxxxxxxxx" />
        <variable name="TWITTER_KEY" value="xxxxxxxx" />
        <variable name="TWITTER_SECRET" value="xxxxxxxxxxxxx" />
    </plugin>
    <plugin name="cordova-plugin-email-composer" spec="^0.8.11" />
    <plugin name="cordova-plugin-facebook4" spec="^1.9.1">
        <variable name="APP_ID" value="xxxxxxxxxxx" />
        <variable name="APP_NAME" value="xxxxxxxxxxx" />
    </plugin>
    <plugin name="cordova-plugin-googleplus" spec="^5.1.1">
        <variable name="REVERSED_CLIENT_ID" value="xxxxxxxxxxxxxxxxxxx" />
    </plugin>
</widget>
</code>```

If i inspect my tablet device in console i see that error refer to a row in main.js This is the row

```<code>MyApp = __decorate([
        Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({template:/*ion-inline-start:"/path/src/app/app.html"*/`<ion-menu [content]="content" persistent>\n\n  <ion-content padding-top class="menu-content">\n\n    <button ion-button icon-only menuToggle float-left clear color="white">\n      <ion-icon name="close"></ion-icon>\n    </button>\n    <div class="imglogo" text-center no-padding>\n      <img src="assets/img/icona-app-210gr.png">\n    </div>\n    <ion-list class="menulist" no-lines inset>\n      <button ion-item *ngFor="let p of pages" (click)="openPage(p)" detail-none text-center>\n        <strong class="bebas" translate>{{p.title}}</strong>\n      </button>\n\n      <button ion-item (click)="flagTapped(\'it\')" detail-none text-center>\n        <strong class="bebas" translate>{{\'LANG_ITALIAN\'}}</strong>\n      </button>\n      <button ion-item (click)="flagTapped(\'en\')" detail-none text-center>\n        <strong class="bebas" translate>{{\'LANG_ENGLISH\'}}</strong>\n      </button>\n\n      <a ion-item href="xxxxxxxxxxxx" detail-none text-center>\n        <strong class="bebas" translate>{{\'LANG_PRIVACY\'}}</strong>\n      </a>\n    </ion-list>\n    <button ion-button menuToggle clear color="white" float-right icon-end (click)="logout()">\n        <span translate>{{\'LANG_LOGOUT\'}}</span>\n      <ion-icon name="log-out"></ion-icon>\n    </button>\n  </ion-content>\n\n</ion-menu>\n\n<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>\n`/*ion-inline-end:"/path/src/app/app.html"*/
        })
</code>```

I don't understend the error. In phone all is ok, ma in tablet no. It's a Ionic bug or a my error?

Thank you

UPDATE 13/11/2017
New investigation: the problem is on device with android version <= 4.4.4 either smartphone and tablet.
But Ionic 3 does not natively support android 4.4+?

UPDATE 13/11/2017 #2
Problem solved. I've installed crosswalk plugin and not all work

答:
android 7.0 supports es6 (es2015) and android 4.4.4 probably doesn't - I had a somewhat similar problem because autocomplete mistakenly imported one of classes from ionic-angular es2015

I had import { Slides } from 'ionic-angular/es2015' instead of import { Slides } from 'ionic-angular';

Title: Ionic 3. Unexpected token <

Body:
i've recently updated ionic to version 3.9.2 but an error occur when run "ionic cordova run android --device" or when i use Ionic DevApp.

When i execute the command on my smartphone Huawaei with android 7.0 all work perfectly, but i obtain error when run on my tablet samsung with android 4.4.4

Running "ionic doctor check" no issues detected.

The error is "Unexpected token <", no other details.

This is my package.json

"scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/animations": "5.0.0",
    "@angular/common": "5.0.0",
    "@angular/compiler": "5.0.0",
    "@angular/compiler-cli": "5.0.0",
    "@angular/core": "5.0.0",
    "@angular/forms": "5.0.0",
    "@angular/http": "5.0.0",
    "@angular/platform-browser": "5.0.0",
    "@angular/platform-browser-dynamic": "5.0.0",
    "@ionic-native/core": "4.4.0",
    "@ionic-native/email-composer": "4.4.0",
    "@ionic-native/facebook": "4.4.0",
    "@ionic-native/google-plus": "4.4.0",
    "@ionic-native/http": "4.4.0",
    "@ionic-native/launch-navigator": "4.4.0",
    "@ionic-native/onesignal": "4.4.0",
    "@ionic-native/splash-screen": "4.4.0",
    "@ionic-native/status-bar": "4.4.0",
    "@ionic-native/twitter-connect": "4.4.0",
    "@ionic/storage": "2.1.3",
    "@ngx-translate/core": "^8.0.0",
    "@ngx-translate/http-loader": "^2.0.0",
    "android-versions": "^1.2.1",
    "cordova-android": "^6.2.3",
    "cordova-ios": "^4.5.1",
    "cordova-plugin-actionsheet": "^2.3.3",
    "cordova-plugin-advanced-http": "^1.6.1",
    "cordova-plugin-compat": "^1.2.0",
    "cordova-plugin-device": "^1.1.4",
    "cordova-plugin-dialogs": "^1.3.3",
    "cordova-plugin-email-composer": "^0.8.11",
    "cordova-plugin-facebook4": "^1.9.1",
    "cordova-plugin-file": "^4.3.3",
    "cordova-plugin-googleplus": "^5.1.1",
    "cordova-plugin-ionic-webview": "^1.1.14",
    "cordova-plugin-splashscreen": "^4.0.3",
    "cordova-plugin-statusbar": "git+https://github.com/apache/cordova-plugin-statusbar.git",
    "cordova-plugin-whitelist": "^1.3.1",
    "cordova-sqlite-storage": "^2.0.4",
    "ionic-angular": "^3.9.2",
    "ionic-plugin-keyboard": "^2.2.1",
    "ionicons": "3.0.0",
    "onesignal-cordova-plugin": "^2.2.2",
    "rxjs": "5.5.2",
    "sw-toolbox": "3.6.0",
    "twitter-connect-plugin": "git+https://github.com/chroa/twitter-connect-plugin.git",
    "uk.co.workingedge.phonegap.plugin.launchnavigator": "^4.0.5",
    "web-animations-js": "^2.3.1",
    "zone.js": "0.8.18"
  },
  "devDependencies": {
    "@ionic/app-scripts": "^3.1.0",
    "typescript": "2.4.2"
  },
  "description": "An Ionic project",
  "cordova": {
    "platforms": [
      "android",
      "ios"
    ],
    "plugins": {
      "cordova-plugin-device": {},
      "cordova-plugin-ionic-webview": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-statusbar": {},
      "cordova-plugin-whitelist": {},
      "ionic-plugin-keyboard": {},
      "uk.co.workingedge.phonegap.plugin.launchnavigator": {},
      "cordova-plugin-advanced-http": {},
      "cordova-sqlite-storage": {},
      "onesignal-cordova-plugin": {},
      "twitter-connect-plugin": {
        "FABRIC_KEY": "xxxxxxxxxxxxxxxxxxx",
        "TWITTER_KEY": "xxxxxxxxxxx",
        "TWITTER_SECRET": "xxxxxxxxxxxxxx"
      },
      "cordova-plugin-email-composer": {},
      "cordova-plugin-facebook4": {
        "APP_ID": "xxxxxxxxxxxxxxxx",
        "APP_NAME": "xxxxxxxxxx"
      },
      "cordova-plugin-googleplus": {
        "REVERSED_CLIENT_ID": "xxxxxxxxxx"
      }
    }
  }

This is my system info

Ionic App Scripts: 3.1.0
Angular Core: 5.0.0
Angular Compiler CLI: 5.0.0
Node: 6.11.4
OS Platform: macOS Sierra
Navigator Platform: MacIntel
User Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:56.0) Gecko/20100101 Firefox/56.0

This is my config.xml

<widget id="XXXXX" version="14.0.2" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>xxxxxxx</name>
    <description>xxxxx</description>
    <author email="xxxxxxx" href="xxxxxxxxxxxx">xxxxxxxxx</author>
    <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <preference name="ScrollEnabled" value="false" />
    <preference name="android-minSdkVersion" value="16" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="FadeSplashScreenDuration" value="300" />
    <preference name="SplashShowOnlyFirstTime" value="false" />
    <preference name="SplashScreen" value="screen" />
    <preference name="SplashScreenDelay" value="3000" />
    <preference name="AutoHideSplashScreen" value="false" />
    <preference name="orientation" value="portrait" />
    <platform name="android">
        <allow-intent href="market:*" />
        <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png" />
        <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png" />
        <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png" />
        <icon density="xhdpi" src="resources/android/icon/drawable-xhdpi-icon.png" />
        <icon density="xxhdpi" src="resources/android/icon/drawable-xxhdpi-icon.png" />
        <icon density="xxxhdpi" src="resources/android/icon/drawable-xxxhdpi-icon.png" />
        <splash density="land-ldpi" src="resources/android/splash/drawable-land-ldpi-screen.png" />
        <splash density="land-mdpi" src="resources/android/splash/drawable-land-mdpi-screen.png" />
        <splash density="land-hdpi" src="resources/android/splash/drawable-land-hdpi-screen.png" />
        <splash density="land-xhdpi" src="resources/android/splash/drawable-land-xhdpi-screen.png" />
        <splash density="land-xxhdpi" src="resources/android/splash/drawable-land-xxhdpi-screen.png" />
        <splash density="land-xxxhdpi" src="resources/android/splash/drawable-land-xxxhdpi-screen.png" />
        <splash density="port-ldpi" src="resources/android/splash/drawable-port-ldpi-screen.png" />
        <splash density="port-mdpi" src="resources/android/splash/drawable-port-mdpi-screen.png" />
        <splash density="port-hdpi" src="resources/android/splash/drawable-port-hdpi-screen.png" />
        <splash density="port-xhdpi" src="resources/android/splash/drawable-port-xhdpi-screen.png" />
        <splash density="port-xxhdpi" src="resources/android/splash/drawable-port-xxhdpi-screen.png" />
        <splash density="port-xxxhdpi" src="resources/android/splash/drawable-port-xxxhdpi-screen.png" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
        <preference name="deployment-target" value="7.0" />
        <icon height="57" src="resources/ios/icon/icon.png" width="57" />
        <icon height="114" src="resources/ios/icon/icon@2x.png" width="114" />
        <icon height="40" src="resources/ios/icon/icon-40.png" width="40" />
        <icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" />
        <icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" />
        <icon height="50" src="resources/ios/icon/icon-50.png" width="50" />
        <icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" />
        <icon height="60" src="resources/ios/icon/icon-60.png" width="60" />
        <icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" />
        <icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" />
        <icon height="72" src="resources/ios/icon/icon-72.png" width="72" />
        <icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" />
        <icon height="76" src="resources/ios/icon/icon-76.png" width="76" />
        <icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" />
        <icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" />
        <icon height="29" src="resources/ios/icon/icon-small.png" width="29" />
        <icon height="58" src="resources/ios/icon/icon-small@2x.png" width="58" />
        <icon height="87" src="resources/ios/icon/icon-small@3x.png" width="87" />
        <splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" />
        <splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" />
        <splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" />
        <splash height="1242" src="resources/ios/splash/Default-Landscape-736h.png" width="2208" />
        <splash height="1536" src="resources/ios/splash/Default-Landscape@2x~ipad.png" width="2048" />
        <splash height="2048" src="resources/ios/splash/Default-Landscape@~ipadpro.png" width="2732" />
        <splash height="768" src="resources/ios/splash/Default-Landscape~ipad.png" width="1024" />
        <splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" />
        <splash height="2732" src="resources/ios/splash/Default-Portrait@~ipadpro.png" width="2048" />
        <splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" />
        <splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" />
        <splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" />
        <splash height="2732" src="resources/ios/splash/Default@2x~universal~anyany.png" width="2732" />
    </platform>
    <allow-navigation href="http://192.168.1.6:8100" />
    <engine name="android" spec="^6.2.3" />
    <engine name="ios" spec="^4.5.1" />
    <plugin name="cordova-plugin-device" spec="^1.1.4" />
    <plugin name="cordova-plugin-ionic-webview" spec="^1.1.14" />
    <plugin name="cordova-plugin-splashscreen" spec="^4.0.3" />
    <plugin name="cordova-plugin-statusbar" spec="git+https://github.com/apache/cordova-plugin-statusbar.git" />
    <plugin name="cordova-plugin-whitelist" spec="^1.3.1" />
    <plugin name="ionic-plugin-keyboard" spec="^2.2.1" />
    <plugin name="uk.co.workingedge.phonegap.plugin.launchnavigator" spec="^4.0.5" />
    <plugin name="cordova-plugin-advanced-http" spec="^1.6.1" />
    <plugin name="cordova-sqlite-storage" spec="^2.0.4" />
    <plugin name="onesignal-cordova-plugin" spec="^2.2.2" />
    <plugin name="twitter-connect-plugin" spec="git+https://github.com/chroa/twitter-connect-plugin.git">
        <variable name="FABRIC_KEY" value="xxxxxxxxx" />
        <variable name="TWITTER_KEY" value="xxxxxxxx" />
        <variable name="TWITTER_SECRET" value="xxxxxxxxxxxxx" />
    </plugin>
    <plugin name="cordova-plugin-email-composer" spec="^0.8.11" />
    <plugin name="cordova-plugin-facebook4" spec="^1.9.1">
        <variable name="APP_ID" value="xxxxxxxxxxx" />
        <variable name="APP_NAME" value="xxxxxxxxxxx" />
    </plugin>
    <plugin name="cordova-plugin-googleplus" spec="^5.1.1">
        <variable name="REVERSED_CLIENT_ID" value="xxxxxxxxxxxxxxxxxxx" />
    </plugin>
</widget>

If i inspect my tablet device in console i see that error refer to a row in main.js This is the row

MyApp = __decorate([
        Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({template:/*ion-inline-start:"/path/src/app/app.html"*/`<ion-menu [content]="content" persistent>\n\n  <ion-content padding-top class="menu-content">\n\n    <button ion-button icon-only menuToggle float-left clear color="white">\n      <ion-icon name="close"></ion-icon>\n    </button>\n
\n      \n
\n    <ion-list class="menulist" no-lines inset>\n      <button ion-item *ngFor="let p of pages" (click)="openPage(p)" detail-none text-center>\n        {{p.title}}\n      </button>\n\n      <button ion-item (click)="flagTapped(\'it\')" detail-none text-center>\n        {{\'LANG_ITALIAN\'}}\n      </button>\n      <button ion-item (click)="flagTapped(\'en\')" detail-none text-center>\n        {{\'LANG_ENGLISH\'}}\n      </button>\n\n      \n        {{\'LANG_PRIVACY\'}}\n      \n    </ion-list>\n    <button ion-button menuToggle clear color="white" float-right icon-end (click)="logout()">\n        {{\'LANG_LOGOUT\'}}\n      <ion-icon name="log-out"></ion-icon>\n    </button>\n  </ion-content>\n\n</ion-menu>\n\n<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>\n`/*ion-inline-end:"/path/src/app/app.html"*/
        })

I don't understend the error. In phone all is ok, ma in tablet no. It's a Ionic bug or a my error?

Thank you

UPDATE 13/11/2017
New investigation: the problem is on device with android version <= 4.4.4 either smartphone and tablet.
But Ionic 3 does not natively support android 4.4+?

UPDATE 13/11/2017 #2
Problem solved. I've installed crosswalk plugin and not all work


答:
@addicted

You're extremely close to what you want to achieve. Once you achieve the non_unique_list of items by joining the dataframe columns, you can take this list and get the resulting order by doing the following

```<code>final_order_list = [non_unique_list[i] for i in range(len(non_unique_list)) if i == non_unique_list.index(non_unique_list[i])]
</code>```

The final result looks as follows:

```<code>>>> final_order_list
['1', '4', '2', '3', '6']
</code>```

Title: python - combining and interpolating 2 dataframe column and creating unique number list from it

Body:
@addicted

You're extremely close to what you want to achieve. Once you achieve the non_unique_list of items by joining the dataframe columns, you can take this list and get the resulting order by doing the following

final_order_list = [non_unique_list[i] for i in range(len(non_unique_list)) if i == non_unique_list.index(non_unique_list[i])]

The final result looks as follows:

>>> final_order_list
['1', '4', '2', '3', '6']