问:
Need to show/hide a dropdown after checking/unchecking a checkbox in angular 4
I have a specific requirement in Angular4.
I need to display a dropdown after selecting/checking a checkbox and if I uncheck the checkbox then dropdown will hide.
Below is the code of the checkbox.

```<code>    <div *ngIf="item.showOperationField">
        <p-checkbox
            value ="inflationaryImpactCheck"
            label="Save for Inflationary Impact"
            name = "calculationSaveInflation"
            [(ngModel)]="item.inflationaryImpact"
            pTooltip="Check the Inflationary Impact box to map this calculation to an index for Inflationary Pressure calculation.">
        </p-checkbox>
    </div>
</code>```

After clicking/unclicking the checkbox

```<code>    <div *ngIf="item.showOperationField">
        <p-dropdown
            [style]="{'width':'200px'}"
            [options]="inflation"
            name = "calculationInflation"
            [(ngModel)]="item.selectedInflation">
        </p-dropdown>
    </div>
</code>```

Please help me and let me know how to do this

答:
You should check if checkbox is checked or not and depending on that setting the value of ngIf for your dropdown to true or false.
To check if checkbox is checked:
check checkbox

In the change event you should set the value for ngIf.
I hope you understood :).

Body:
I have a specific requirement in Angular4.
I need to display a dropdown after selecting/checking a checkbox and if I uncheck the checkbox then dropdown will hide.
Below is the code of the checkbox.

After clicking/unclicking the checkbox

Please help me and let me know how to do this


来源: stackexchange

问:
VSTS Release Management for Nuget Package with Hosted Linux Preview using dotnet
Is it possible to setup a release management task that works for the Hosted Linux Preview Agent that pushes a nuget package using dotnet push?

I've got a Build process that creates the nuget package and publishes it as an artifact.  So far I've got this, which works when I use the Hosted VS2017 Agent.

The error i'm getting is:

```<code>2017-11-16T09:08:37.3084270Z ##[section]Starting: dotnet push
2017-11-16T09:08:37.3413530Z ==============================================================================
2017-11-16T09:08:37.3426100Z Task         : .NET Core
2017-11-16T09:08:37.3439540Z Description  : Build, test, package, or publish a dotnet application, or run a custom dotnet command. For package commands, supports NuGet.org and authenticated feeds like Package Management and MyGet.
2017-11-16T09:08:37.3451740Z Version      : 2.1.8
2017-11-16T09:08:37.3464910Z Author       : Microsoft Corporation
2017-11-16T09:08:37.3477740Z Help         : [More Information](https://go.microsoft.com/fwlink/?linkid=832194)
2017-11-16T09:08:37.3491430Z ==============================================================================
2017-11-16T09:08:40.3181020Z ##[error]No packages matched the search pattern.
2017-11-16T09:08:40.3305430Z ##[section]Finishing: dotnet push
</code>```

I'm wondering if there is a difference between the agents on how they pattern match file names.

答:
So it turns out that backslashes and forward slashes are pretty important.

I changed the Path to NuGet package(s) to publish to use forward slashes $(System.DefaultWorkingDirectory)/**/*.nupkg

And what do you know, it works :D

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to setup a release management task that works for the Hosted Linux Preview Agent that pushes a nuget package using dotnet push?

I've got a Build process that creates the nuget package and publishes it as an artifact.  So far I've got this, which works when I use the Hosted VS2017 Agent.

The error i'm getting is:

2017-11-16T09:08:37.3084270Z ##[section]Starting: dotnet push
2017-11-16T09:08:37.3413530Z ==============================================================================
2017-11-16T09:08:37.3426100Z Task         : .NET Core
2017-11-16T09:08:37.3439540Z Description  : Build, test, package, or publish a dotnet application, or run a custom dotnet command. For package commands, supports NuGet.org and authenticated feeds like Package Management and MyGet.
2017-11-16T09:08:37.3451740Z Version      : 2.1.8
2017-11-16T09:08:37.3464910Z Author       : Microsoft Corporation
2017-11-16T09:08:37.3477740Z Help         : [More Information](https://go.microsoft.com/fwlink/?linkid=832194)
2017-11-16T09:08:37.3491430Z ==============================================================================
2017-11-16T09:08:40.3181020Z ##[error]No packages matched the search pattern.
2017-11-16T09:08:40.3305430Z ##[section]Finishing: dotnet push

I'm wondering if there is a difference between the agents on how they pattern match file names.


问:
MySQL Select User id based on multiple AND conditions on same table
I want to select a userid from a single table based on multiple and condition.

```<code>UserID   FieldID  Value
-----------------------------------
1        51         Yes
1        6          Dog
2        6          Cat
1        68         TX
1        69         78701
2        68         LA
</code>```

What I'm trying to get in simple words:

if user search for texas or 78701,
Select userId where (68 = TX OR 69=78701) AND (51=yes) AND (6=Dog)

This should return user id 1.

This is what I tried, but returns null.

```<code>SELECT user_id FROM `metadata`
WHERE ( (`field_id` = '68' AND value LIKE '%TX%')
   OR (`field_id` = '69' AND value LIKE '%78701%') )
   AND `field_id` = '51' AND value = 'Yes'
   AND `field_id` = '6' AND value = 'Dog'
</code>```

答:
You can use GROUP BY with a HAVING clause that makes use of multiple conditional aggregates:

```<code>SELECT UserID
FROM metadata
GROUP BY UserID
HAVING SUM(field_id = '68' AND value LIKE '%TX%' OR
           field_id = '69' AND value LIKE '%78701%') >= 1

       AND

       SUM(field_id = '51' AND value = 'Yes') >= 1

       AND

       SUM(field_id = '6' AND value = 'Dog') >= 1
</code>```

Demo here

Explanation: In MysQL a boolean expression, like

```<code>field_id = '51' AND value = 'Yes'
</code>```

returns 1 when true, 0 when false.

Also, each predicate of HAVING clause is applied to the whole group of records, as defined by GROUP BY.

Hence, predicate:

```<code>SUM(field_id = '51' AND value = 'Yes') >= 1
</code>```

is like saying: return only those UserID groups having at least one (>=1) record with

```<code>field_id = '51' AND value = 'Yes' -> true
</code>```

Body:
I want to select a userid from a single table based on multiple and condition.

UserID   FieldID  Value
-----------------------------------
1        51         Yes
1        6          Dog
2        6          Cat
1        68         TX
1        69         78701
2        68         LA

What I'm trying to get in simple words:

if user search for texas or 78701,
Select userId where (68 = TX OR 69=78701) AND (51=yes) AND (6=Dog)

This should return user id 1.

This is what I tried, but returns null.

SELECT user_id FROM `metadata`
WHERE ( (`field_id` = '68' AND value LIKE '%TX%')
   OR (`field_id` = '69' AND value LIKE '%78701%') )
   AND `field_id` = '51' AND value = 'Yes'
   AND `field_id` = '6' AND value = 'Dog'

Body:
You can use GROUP BY with a HAVING clause that makes use of multiple conditional aggregates:

SELECT UserID
FROM metadata
GROUP BY UserID
HAVING SUM(field_id = '68' AND value LIKE '%TX%' OR
           field_id = '69' AND value LIKE '%78701%') >= 1

       AND

       SUM(field_id = '51' AND value = 'Yes') >= 1

       AND

       SUM(field_id = '6' AND value = 'Dog') >= 1

Demo here

Explanation: In MysQL a boolean expression, like

field_id = '51' AND value = 'Yes'

returns 1 when true, 0 when false.

Also, each predicate of HAVING clause is applied to the whole group of records, as defined by GROUP BY.

Hence, predicate:

SUM(field_id = '51' AND value = 'Yes') >= 1

is like saying: return only those UserID groups having at least one (>=1) record with

field_id = '51' AND value = 'Yes' -> true


问:
onSelect event datepicker triggers change of minTime value in timepicker
When "today" is selected in datepicker, the minTime of timepicker is = current time, and if the select date is not today, the minTime of timepicker is = "12:00am". But the minTime value (below) is never being triggered (I guess) when I tried to select different date. The console.log() shows the if statement is working fine thou.

var selection = jQuery("input#ezfc_element-15-child.ezfc-element-timepicker").data("settings");
var today = localdate.toLocaleDateString("en-US");
setTimeout(function(){
    jQuery( ".ezfc-element-datepicker" ).datepicker({
        minDate: new Date(today),
        defaultDate: new Date(today),
        onSelect: function(dateText) {
            var ds_milliseconds = Date.parse(dateText);
            var t_milliseconds = Date.parse(today);
            if (t_milliseconds == ds_milliseconds) {
                selection['minTime'] = minTime;
                console.log ("minTime");
            } else {
                selection['minTime'] = "12:00am" ;
                console.log("12:00am");
            }
        }
     });

 }, 3000);
```

答:
Have you tried opening your browser console, selection is not a valid usage, replace your if else section with below code</p>

```<code>if (t_milliseconds == ds_milliseconds) {
    $(this).datepicker('option', 'minTime', minTime);
    console.log ("minTime");
} else {
    $(this).datepicker('option', 'minTime', "12:00am");
    console.log("12:00am");
}
</code>```

Body:
Have you tried opening your browser console, selection is not a valid usage, replace your if else section with below code

if (t_milliseconds == ds_milliseconds) {
    $(this).datepicker('option', 'minTime', minTime);
    console.log ("minTime");
} else {
    $(this).datepicker('option', 'minTime', "12:00am");
    console.log("12:00am");
}


问:
How to transform Scala collection of Option[X] to collection of X
I'm starting to explore Scala, and one of the things I'm intrigued by is the Option type and the promise of being able to eliminate null related errors.

However I haven't been able to work out how to transform a list (or other collection) of, say, Option[String], to a collection of String (obviously filtering out any values that are None).

In other words, how do I get from this:

```<code>List[Option[Int]] = List(Some(1))
</code>```

... to this:

```<code>List[Int] = List(1)
</code>```

I'm using Scala 2.8 if that has any impact on the answer.

答:
For educational purposes, you might like some alternatives:

```<code>scala> val list1 = List(Some(1), None, Some(2))
list1: List[Option[Int]] = List(Some(1), None, Some(2))

scala> list1 flatten
res0: List[Int] = List(1, 2)

// Expanded to show the implicit parameter
scala> list1.flatten(Option.option2Iterable)
res1: List[Int] = List(1, 2)

scala> list1 flatMap (x => x)
res2: List[Int] = List(1, 2)

scala> list1 flatMap Option.option2Iterable
res3: List[Int] = List(1, 2)

// collect is a simultaneous map + filter
scala> list1 collect { case Some(x) => x }
res4: List[Int] = List(1, 2)
</code>```

With Scalaz, you can perform a slightly different operation called sequence, that returns Option[List[Int]].

```<code>scala> import scalaz._; import Scalaz._
import scalaz._
import Scalaz._

scala> val list1: List[Option[Int]] = List(Some(1), None, Some(2))
list1: List[Option[Int]] = List(Some(1), None, Some(2))

scala> list1.sequence
res1: Option[List[Int]] = None

scala> val list2: List[Option[Int]] = List(Some(1), Some(2))
list2: List[Option[Int]] = List(Some(1), Some(2))

scala> list2.sequence
res2: Option[List[Int]] = Some(List(1, 2))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm starting to explore Scala, and one of the things I'm intrigued by is the Option type and the promise of being able to eliminate null related errors.

However I haven't been able to work out how to transform a list (or other collection) of, say, Option[String], to a collection of String (obviously filtering out any values that are None).

In other words, how do I get from this:

List[Option[Int]] = List(Some(1))

... to this:

List[Int] = List(1)

I'm using Scala 2.8 if that has any impact on the answer.

Body:
For educational purposes, you might like some alternatives:

scala> val list1 = List(Some(1), None, Some(2))
list1: List[Option[Int]] = List(Some(1), None, Some(2))

scala> list1 flatten
res0: List[Int] = List(1, 2)

// Expanded to show the implicit parameter
scala> list1.flatten(Option.option2Iterable)
res1: List[Int] = List(1, 2)

scala> list1 flatMap (x => x)
res2: List[Int] = List(1, 2)

scala> list1 flatMap Option.option2Iterable
res3: List[Int] = List(1, 2)

// collect is a simultaneous map + filter
scala> list1 collect { case Some(x) => x }
res4: List[Int] = List(1, 2)

With Scalaz, you can perform a slightly different operation called sequence, that returns Option[List[Int]].

scala> import scalaz._; import Scalaz._
import scalaz._
import Scalaz._

scala> val list1: List[Option[Int]] = List(Some(1), None, Some(2))
list1: List[Option[Int]] = List(Some(1), None, Some(2))

scala> list1.sequence
res1: Option[List[Int]] = None

scala> val list2: List[Option[Int]] = List(Some(1), Some(2))
list2: List[Option[Int]] = List(Some(1), Some(2))

scala> list2.sequence
res2: Option[List[Int]] = Some(List(1, 2))


问:
Exception when call PyModule_GetDict() with a specific python import
I want manage a LCD from my C code doing calls to python. I'm newbie in that.
My python app works perfectly with LCD. No problems with libraries that are used in my python code. Python2.7
My problem ocurrs when I call to PyModule_GetDict function. If I added a specific library import into python file, my C program crash.
The library is Adafruit_ILI9341, and if I not import it, the C program runs correct.

Is it possible that there are incompatible libraries with Python interpeter?
How I can debug this problem?

Thanks a lot!

This is my C code:

```<code>// Set PYTHONPATH TO working directory
setenv("PYTHONPATH",".",1);

PyObject *pName, *pModule, *pDict, *pFunc, *presult;
// Initialize the Python Interpreter
Py_Initialize();

// Build the name object
pName = PyString_FromString((char*)"lcd");

// Load the module object
pModule = PyImport_Import(pName);

// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);

// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, (char*)"initLCD");

if (PyCallable_Check(pFunc)) {
    printf("Let's give this a shot!\n");
    presult=PyObject_CallObject(pFunc,NULL);
    PyErr_Print();
} else {
    PyErr_Print();
}
printf("Result is %d\n",PyInt_AsLong(presult));

// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);

// Finish the Python Interpreter
Py_Finalize();
</code>```

and this is the python code:

```<code>from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import os
import threading
from threading import Timer

import Adafruit_ILI9341 as ADAFRUIT_TFT
import Adafruit_GPIO as GPIO
import Adafruit_GPIO.SPI as SPI
import RPi.GPIO as LCD_GPIO

import time
import locale

def iniciaDisplay():
    LCD_GPIO.setwarnings(False)
    LCD_GPIO.setmode(LCD_GPIO.BCM)
    LCD_GPIO.setup(5, LCD_GPIO.OUT)
    p = LCD_GPIO.PWM(5, 100)
    p.start(1)
    DC = 24
    RST = 25
    SPI_PORT = 0
    SPI_DEVICE = 0

    disp = ADAFRUIT_TFT.ILI9341(DC, rst=RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=64000000))
    disp.begin()
    disp.clear()
    disp.display(getLogo(0))

    return 0
</code>```

EDIT:

Following the advices of @BlackJack I added the NULL check and PyErr_Print and I saw why it fails. The problem is caused by a _io library import.

This is the output checking NULL values and PyErr_Print:

```<code>Traceback (most recent call last):
  File "/home/pi/pruebas/DESFIREXip32/tft.py", line 18, in <module>
    import Adafruit_ILI9341 as ADAFRUIT_TFT
  File "build/bdist.linux-armv7l/egg/Adafruit_ILI9341/__init__.py", line 21, in <module>
  File "build/bdist.linux-armv7l/egg/Adafruit_ILI9341/ILI9341.py", line 23, in <module>
  File "/usr/lib/python2.7/dist-packages/numpy/__init__.py", line 153, in <module>
    from . import add_newdocs
  File "/usr/lib/python2.7/dist-packages/numpy/add_newdocs.py", line 13, in <module>
    from numpy.lib import add_newdoc
  File "/usr/lib/python2.7/dist-packages/numpy/lib/__init__.py", line 22, in <module>
    from .npyio import *
  File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 4, in <module>
    from . import format
  File "/usr/lib/python2.7/dist-packages/numpy/lib/format.py", line 141, in <module>
    import io
  File "/usr/lib/python2.7/io.py", line 51, in <module>
    import _io
SystemError: _PyImport_FixupExtension: module _io not loaded
</code>```

I think this error should treat it in a new thread.

答:
I see at least five problems, with all but two being not checking for NULL values.

You are not checking the return value of PyImport_Import().  If there is a problem/exception while importing the lcd module your code continues as if nothing happened.

Also the return value of PyDict_GetItemString() isn't really checked against NULL.  PyCallable_Check() is applied, but it is somewhat redundant because PyObject_CallObject() already checks if the argument is callable.

Of course you are not checking the return value of PyObject_CallObject() if it is NULL.

PyErr_Print() is potentially called even when there is no error/exception which the documentation clearly states will cause a fatal error.

Finally PyInt_AsLong() is called with a potentially uninitialized presult pointer.  And given the example code it is definately uninitialized because the Python code contains no initLCD() so pFunc is NULL and presult never gets assigned a value.

So you better initialize each pointer to NULL and check each and every return value.

```<code>PyObject *pName = NULL;
PyObject *pModule = NULL;
PyObject *pFunc = NULL;
PyObject *presult = NULL;

setenv("PYTHONPATH", ".", 1);
Py_Initialize();

if ((pName = PyString_FromString("lcd"))) {
    if ((pModule = PyImport_Import(pName))) {
        if ((pFunc = PyObject_GetAttrString(pModule, "initLCD"))) {
            if ((presult = PyObject_CallObject(pFunc, NULL))) {
                printf("Result is %d\n", (int) PyInt_AsLong(presult));
            }
        }
    }
}
if (PyErr_Occurred()) PyErr_Print();

Py_XDECREF(presult);
Py_XDECREF(pFunc);
Py_XDECREF(pModule);
Py_XDECREF(pName);

Py_Finalize();
</code>```

Body:
I want manage a LCD from my C code doing calls to python. I'm newbie in that.
My python app works perfectly with LCD. No problems with libraries that are used in my python code. Python2.7
My problem ocurrs when I call to PyModule_GetDict function. If I added a specific library import into python file, my C program crash.
The library is Adafruit_ILI9341, and if I not import it, the C program runs correct.

Is it possible that there are incompatible libraries with Python interpeter?
How I can debug this problem?

Thanks a lot!

This is my C code:

// Set PYTHONPATH TO working directory
setenv("PYTHONPATH",".",1);

PyObject *pName, *pModule, *pDict, *pFunc, *presult;
// Initialize the Python Interpreter
Py_Initialize();

// Build the name object
pName = PyString_FromString((char*)"lcd");

// Load the module object
pModule = PyImport_Import(pName);

// pDict is a borrowed reference
pDict = PyModule_GetDict(pModule);

// pFunc is also a borrowed reference
pFunc = PyDict_GetItemString(pDict, (char*)"initLCD");

if (PyCallable_Check(pFunc)) {
    printf("Let's give this a shot!\n");
    presult=PyObject_CallObject(pFunc,NULL);
    PyErr_Print();
} else {
    PyErr_Print();
}
printf("Result is %d\n",PyInt_AsLong(presult));

// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);

// Finish the Python Interpreter
Py_Finalize();

and this is the python code:

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import os
import threading
from threading import Timer

import Adafruit_ILI9341 as ADAFRUIT_TFT
import Adafruit_GPIO as GPIO
import Adafruit_GPIO.SPI as SPI
import RPi.GPIO as LCD_GPIO

import time
import locale

def iniciaDisplay():
    LCD_GPIO.setwarnings(False)
    LCD_GPIO.setmode(LCD_GPIO.BCM)
    LCD_GPIO.setup(5, LCD_GPIO.OUT)
    p = LCD_GPIO.PWM(5, 100)
    p.start(1)
    DC = 24
    RST = 25
    SPI_PORT = 0
    SPI_DEVICE = 0

    disp = ADAFRUIT_TFT.ILI9341(DC, rst=RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=64000000))
    disp.begin()
    disp.clear()
    disp.display(getLogo(0))

    return 0

EDIT:

Following the advices of @BlackJack I added the NULL check and PyErr_Print and I saw why it fails. The problem is caused by a _io library import.

This is the output checking NULL values and PyErr_Print:

Traceback (most recent call last):
  File "/home/pi/pruebas/DESFIREXip32/tft.py", line 18, in <module>
    import Adafruit_ILI9341 as ADAFRUIT_TFT
  File "build/bdist.linux-armv7l/egg/Adafruit_ILI9341/__init__.py", line 21, in <module>
  File "build/bdist.linux-armv7l/egg/Adafruit_ILI9341/ILI9341.py", line 23, in <module>
  File "/usr/lib/python2.7/dist-packages/numpy/__init__.py", line 153, in <module>
    from . import add_newdocs
  File "/usr/lib/python2.7/dist-packages/numpy/add_newdocs.py", line 13, in <module>
    from numpy.lib import add_newdoc
  File "/usr/lib/python2.7/dist-packages/numpy/lib/__init__.py", line 22, in <module>
    from .npyio import *
  File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 4, in <module>
    from . import format
  File "/usr/lib/python2.7/dist-packages/numpy/lib/format.py", line 141, in <module>
    import io
  File "/usr/lib/python2.7/io.py", line 51, in <module>
    import _io
SystemError: _PyImport_FixupExtension: module _io not loaded

I think this error should treat it in a new thread.

Body:
I see at least five problems, with all but two being not checking for NULL values.

You are not checking the return value of PyImport_Import().  If there is a problem/exception while importing the lcd module your code continues as if nothing happened.

Also the return value of PyDict_GetItemString() isn't really checked against NULL.  PyCallable_Check() is applied, but it is somewhat redundant because PyObject_CallObject() already checks if the argument is callable.

Of course you are not checking the return value of PyObject_CallObject() if it is NULL.

PyErr_Print() is potentially called even when there is no error/exception which the documentation clearly states will cause a fatal error.

Finally PyInt_AsLong() is called with a potentially uninitialized presult pointer.  And given the example code it is definately uninitialized because the Python code contains no initLCD() so pFunc is NULL and presult never gets assigned a value.

So you better initialize each pointer to NULL and check each and every return value.

PyObject *pName = NULL;
PyObject *pModule = NULL;
PyObject *pFunc = NULL;
PyObject *presult = NULL;

setenv("PYTHONPATH", ".", 1);
Py_Initialize();

if ((pName = PyString_FromString("lcd"))) {
    if ((pModule = PyImport_Import(pName))) {
        if ((pFunc = PyObject_GetAttrString(pModule, "initLCD"))) {
            if ((presult = PyObject_CallObject(pFunc, NULL))) {
                printf("Result is %d\n", (int) PyInt_AsLong(presult));
            }
        }
    }
}
if (PyErr_Occurred()) PyErr_Print();

Py_XDECREF(presult);
Py_XDECREF(pFunc);
Py_XDECREF(pModule);
Py_XDECREF(pName);

Py_Finalize();


问:
How to remove default context menu in Edit Text?
I am using EditText in my Android application. When i long press on the EditText, i want to remove/hide all the default context menu like Copy,Cut,Select All etc. Only paste menu should be shown. I have tried with the solution in the below link, but along with Paste, SelectAll option is also showing. How can i remove it.

EditText: Disable Paste/Replace menu pop-up on Text Selection Handler click event

答:
```<code>EditText yourEditText = (EditText) findViewById(R.id.your_edit_text);
yourEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback()
{
    @Override
    public boolean onCreateActionMode(ActionMode actionMode, Menu menu)
    {
        return false;
    }
    @Override
    public boolean onPrepareActionMode(ActionMode actionMode, Menu menu)
    {
        return false;
    }
    @Override
    public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem)
    {
        return false;
    }
    @Override
    public void onDestroyActionMode(ActionMode actionMode)
    {
        // Do your stuff here when you destroy
    }
    });
}
</code>```

In your xml file, add following line to your respective editText:

```<code>android:textIsSelectable="false"
</code>```

For further operations you can use that library:

https://github.com/neopixl/PixlUI

Body:
EditText yourEditText = (EditText) findViewById(R.id.your_edit_text);
yourEditText.setCustomSelectionActionModeCallback(new ActionMode.Callback()
{
    @Override
    public boolean onCreateActionMode(ActionMode actionMode, Menu menu)
    {
        return false;
    }
    @Override
    public boolean onPrepareActionMode(ActionMode actionMode, Menu menu)
    {
        return false;
    }
    @Override
    public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem)
    {
        return false;
    }
    @Override
    public void onDestroyActionMode(ActionMode actionMode)
    {
        // Do your stuff here when you destroy
    }
    });
}

In your xml file, add following line to your respective editText:

android:textIsSelectable="false"

For further operations you can use that library:

https://github.com/neopixl/PixlUI


问:
Nodejs, email send using Nodemailer using Bluehost SMTP not being delivered, no error
I am trying to send email from my Nodejs application. I'm using the package Nodemailer for this. Here's the code I use for sending email;

```<code>let smtpTransport = nodemailer.createTransport({
   host: "box***.bluehost.com",
   port: 465,
   secure: true,
   auth: {
     user: <noreply@mydomain.com>,
     pass: <password>
   }
});

let sendResetPasswordEmail = (user, token) => {
   let mailOptions = {
       to : user.workEmail,
       subject : "Reset your password",
       text : _generateResetPasswordEmail(user, token)
   }

   smtpTransport.sendMail(mailOptions, (error, response) => {
       if(error){
           console.error(error);
       } else {
           console.log("Message sent: " + response.message);
           console.log(response);
       }
   });
}
</code>```

In the callback of smtpTransport.sendMail function, error is null and this is the response I get

```<code>{
   accepted: [ 'toemail@somedomain.com' ],
   rejected: [],
   response: '250 OK id=short-hyphenated-alpha-numeric-id>',
   envelope: { from: '', to: [ 'toemail@somedomain.com' ] },
   messageId: '<long-hyphenated-alpha-numeric-id@my-machine-name>'
}
</code>```

Everything seems fine in the response, status code is 250, but toemail@somedomain.com simply won't receive this email. Also, I can't find it in my bluehost email dashboard's 'Sent' list. What could be going wrong.

答:
I encountered same problems. I was able to solve this by adding the name property on the createTransport object. name: "mail.yourdomain". If you do not see email, check spam folder. This was gotten from https://github.com/nodemailer/nodemailer/issues/677
I hope this helps. </p>

Body:
I am trying to send email from my Nodejs application. I'm using the package Nodemailer for this. Here's the code I use for sending email;

let smtpTransport = nodemailer.createTransport({
   host: "box***.bluehost.com",
   port: 465,
   secure: true,
   auth: {
     user: <noreply@mydomain.com>,
     pass: <password>
   }
});

let sendResetPasswordEmail = (user, token) => {
   let mailOptions = {
       to : user.workEmail,
       subject : "Reset your password",
       text : _generateResetPasswordEmail(user, token)
   }

   smtpTransport.sendMail(mailOptions, (error, response) => {
       if(error){
           console.error(error);
       } else {
           console.log("Message sent: " + response.message);
           console.log(response);
       }
   });
}

In the callback of smtpTransport.sendMail function, error is null and this is the response I get

{
   accepted: [ 'toemail@somedomain.com' ],
   rejected: [],
   response: '250 OK id=short-hyphenated-alpha-numeric-id>',
   envelope: { from: '', to: [ 'toemail@somedomain.com' ] },
   messageId: '<long-hyphenated-alpha-numeric-id@my-machine-name>'
}

Everything seems fine in the response, status code is 250, but toemail@somedomain.com simply won't receive this email. Also, I can't find it in my bluehost email dashboard's 'Sent' list. What could be going wrong.


问:
I want access span for hide & show purpose with class name & id name which will start with?
I want to access a span with a specific class and id (the id will start with specific pattern)

```<code><span id='asd111' class="demo"></span>
<span id='asd122' class="demo"></span>
<span id='asd133' class="demo"></span>
<span id='asd144' class="demo"></span>
</code>```

Now I want to hide/show above spans using single jQuery statement. How can do this? All span id start with common asd1 pattern.

Please give me idea as soon as possible.

*i have just given example in this code.. those spans are coming dynamically in my code in different nested divs, so i want hide those with those id pattern & class name???

答:
I'd recommend you to take a look at basic jQuery selectors(https://api.jquery.com/category/selectors/). </p>

<p>If you want to hide the span with specific ID and class name, there is a code that hides span with ID asd111 and class demo: </p>

```<code>$('#asd111.demo').hide();
</code>```

Body:
I want to access a span with a specific class and id (the id will start with specific pattern)

Now I want to hide/show above spans using single jQuery statement. How can do this? All span id start with common asd1 pattern.

Please give me idea as soon as possible.

*i have just given example in this code.. those spans are coming dynamically in my code in different nested divs, so i want hide those with those id pattern & class name???

Body:
I'd recommend you to take a look at basic jQuery selectors(https://api.jquery.com/category/selectors/).

If you want to hide the span with specific ID and class name, there is a code that hides span with ID asd111 and class demo:

$('#asd111.demo').hide();


问:
Get value from Date picker
I want to get the value from JavaFX datepicker and store the value as Date Object:

```<code>final DatePicker datePicker = new DatePicker(LocalDate.now());
Date date = datePicker.getValue();
grid.add(datePicker, 1, 9);
</code>```

Can you tell me how I can convert LocalDate to Date?

答:
LeonidasCZ answer is not 100% correct: java.util.Date months range is from 0 to 11, but Calendar.getInstance() is from 1 to 12, so you can do this:

```<code>LocalDate ld = datePicker.getValue();
Calendar c =  Calendar.getInstance();
c.set(ld.getYear(), ld.getMonthValue() - 1, ld.getDayOfMonth());
Date date = c.getTime();
</code>```

If you want to add hours, mins, seconds too:

```<code>LocalDate ld = datePicker.getValue();
Calendar c =  Calendar.getInstance();
c.set(ld.getYear(), ld.getMonthValue() - 1, ld.getDayOfMonth(), hours, minutes, seconds);
Date date = c.getTime();
</code>```

Title: Get value from Date picker

Body:
I want to get the value from JavaFX datepicker and store the value as Date Object:

final DatePicker datePicker = new DatePicker(LocalDate.now());
Date date = datePicker.getValue();
grid.add(datePicker, 1, 9);

Can you tell me how I can convert LocalDate to Date?

Body:
LeonidasCZ answer is not 100% correct: java.util.Date months range is from 0 to 11, but Calendar.getInstance() is from 1 to 12, so you can do this:

LocalDate ld = datePicker.getValue();
Calendar c =  Calendar.getInstance();
c.set(ld.getYear(), ld.getMonthValue() - 1, ld.getDayOfMonth());
Date date = c.getTime();

If you want to add hours, mins, seconds too:

LocalDate ld = datePicker.getValue();
Calendar c =  Calendar.getInstance();
c.set(ld.getYear(), ld.getMonthValue() - 1, ld.getDayOfMonth(), hours, minutes, seconds);
Date date = c.getTime();


问:
Child Model Validation using Parent Model Values. Fluent Validation. MVC4
Below is a simplified version of my problem.

I can not flatten the model. There is a List of "children" that I need to validate a birthday.

I can not seem to reference the date in the Parent class and was wondering how this is done in Fluent Validation?

Model

```<code>[Validator(typeof(ParentValidator))]
public class Parent
{
    public string Name { get; set; }
    public DateTime Birthdate { get; set; }

    public List<Child> Children { get; set; }
}

public class Child
{
    public string ChildProperty{ get; set; }
    public DateTime Birthdate { get; set; }
}
</code>```

Validator

```<code>public class ParentValidator : AbstractValidator<Parent>
{
    public ParentValidator()
    {
         RuleFor(model => model.Name).NotEmpty();
         RuleForEach(model => model.Children).SetValidator(new ChildValidator());
    }
}

public class ChildValidator : AbstractValidator<Child>
{
    public ChildValidator()
    {
        RuleFor(model => model.ChildProperty).NotEmpty();
        //Compare birthday to make sure date is < Parents birthday
    }
}
</code>```

答:
Nowadays the answer by @johnny-5 can be simplified even further by using the SetCollectionValidator extension method and passing the parent object to the child validator:

public class ParentValidator : AbstractValidator<Parent>
{
    public ParentValidator()
    {
         RuleFor(model => model.Name).NotEmpty();
         RuleFor(model => model.Children)
             .SetCollectionValidator(model => new ChildValidator(model))
    }
}

public class ChildValidator : AbstractValidator<Child>
{
    public ChildValidator(Parent parent)
    {
        RuleFor(model => model.ChildProperty).NotEmpty();
        RuleFor(model => model.Birthday).Must(birthday => parent.Birthday < birthday);
    }
}
```

Body:
Below is a simplified version of my problem.

I can not flatten the model. There is a List of "children" that I need to validate a birthday.

I can not seem to reference the date in the Parent class and was wondering how this is done in Fluent Validation?

Model

[Validator(typeof(ParentValidator))]
public class Parent
{
    public string Name { get; set; }
    public DateTime Birthdate { get; set; }

    public List<Child> Children { get; set; }
}

public class Child
{
    public string ChildProperty{ get; set; }
    public DateTime Birthdate { get; set; }
}

Validator

public class ParentValidator : AbstractValidator<Parent>
{
    public ParentValidator()
    {
         RuleFor(model => model.Name).NotEmpty();
         RuleForEach(model => model.Children).SetValidator(new ChildValidator());
    }
}

public class ChildValidator : AbstractValidator<Child>
{
    public ChildValidator()
    {
        RuleFor(model => model.ChildProperty).NotEmpty();
        //Compare birthday to make sure date is < Parents birthday
    }
}


问:
asyncfileupload postback
I am using Asyncfileupload AJAX control, and want to know if there is anyway for me to automatically reload/refresh the current page after the file upload?

The whole thing loads in an iframe so not sure how to do this.

Thanks
Behrouz

答: According to the documentation the OnClientUploadComplete callback javascript function will be executed when the file upload completes. So you could register for this event and refresh the current page using window.location.reload();.

Title: asyncfileupload postback


问:
save string to a date field in sql server
I have the following string that I need to save to a sql server database column that has a date datatype.

'2017-05-25T00:00:00'

Can I use cast within a insert script to save this value and is this the best way?

答:
yes You can insert the value like this

```<code>INSERT INTO YourTable(ColumnName)
SELECT CAST(StringFiled AS DATETIME)
</code>```

You Can cast it as Date,DateTime or any other Date type you need

Body:
yes You can insert the value like this

INSERT INTO YourTable(ColumnName)
SELECT CAST(StringFiled AS DATETIME)

You Can cast it as Date,DateTime or any other Date type you need


问:
Selecting arrays with specific element values
This is driving me nuts, I've been trying to figure out how to do this one thing for hours now.

What I want to do is select all array items that have a specific value. This is easiest to explain by example:

I have an array, called media[]. It holds ALL of the media in my media gallery. It has two properties of note: path and gallery, or media[x][0] and media[x][1].

I want to select all media objects that belong in a certain gallery, and then add them to that gallery. That's where I'm struggling and it's driving me mad.

Here are my fumbled attempts at trying to do this... this is some seriously messy code (and mostly pointless), I'm just providing it so you can get a sense of how clueless I am about this. Please note that NONE of the code I have right now actually tries to do anything; everything I've done so far ends up as a broken for or while loop that either does nothing or crashes Chrome.

```<code>// this function is meant to return an array of all media items
// that belong in a certain gallery... didn't get that far because
// the loops tripped me up
function getTheMedia (galNum) {
    var output = [];
    for (var i = 0; i < media.length; ++i) {
        // I tried using an if statement here to check if the
        // media[i][1] == galNum, and if so, add it to the output
        // but that didn't work
        output.push(media[i]);
    }
    return output;
}

// this function was actually my first attempt but I kept running into
// the same issue as above
function fillGal () {
    /*
    var output = [];
    for (var i = 0; i < Gallery.length; ++i) {
        output.push(Gallery[i]);
    }
    */
    var output = [];
    var i = 0;
    while (i < media.length) {
        output.push(i);
        i++;
    }
    console.log(output);
}
</code>```

Seeing as I'm kind of burnt out and frustrating with running in circles (...loops? aha...), all I'm really looking for is a way to select only those specific array items as specified above. Everything else (adding them to the Gallery, etc) I can figure out myself.

Otherwise I'm just going to have to go back to the old way: define separate media[]arrays for each "gallery" (mediaThisGallery, mediaThatGallery, etc), and then combine them all at the end to get "allMedia". Only reason I don't want to do that is because I want to be able to change which gallery a media item belongs to... this HAS to be possible, right?

Thanks in advance! Sorry for the scatter-brainedness. I also apologize if the title is a bit off.

EDIT:

```<code>var media = [];

media[0] = ['0.png', 0, 'index'];
media[1] = ['0.png', 0];

media[2] = ['new/316.png', 1, "316"];
media[3] = ['new/kitties.jpg', 1, "D'aww kitties!!"];
media[4] = ['new/home.jpg', 1, "\"I'm Going Home\""];
media[5] = ['new/3.mp4', 1, "Crucible Carnage"];
media[6] = ['new/942.jpg', 1, "this is straight for testing purposes like omg long ass title lol"];
media[7] = ['new/boom.mp4', 1, "Maximum Efficiency"];
media[8] = ['new/42.jpg', 1, "Moo"];

// this is only included as a quick fix so my working code doesn't break
// as my "production" code is using multiple arrays; Media is used
// to store only the selected array (current Gallery)
// in other words, ignore this
var Media = [];
Media = media;

var Gallery = [];
Gallery[0] = [mediaRoot, "index", media ];
Gallery[1] = [mediaRoot, "new", Media ];
</code>```

It's pretty arbitrary atm.

Note that the main reason I'm converting from multiple arrays to a single array is that eventually, I plan to expand this app and I thought it made more sense to store ALL media in a single "database".

答:
Javascript arrays have a filter function, like so:

console.log([0,1,2,3,4,5,6,7,8,9,10].filter(v=>v!==0))```

The above example remove all the '0' from the array.
I think it can be helpful in your case.

More information in: https://www.w3schools.com/jsref/jsref_filter.asp

Body:
This is driving me nuts, I've been trying to figure out how to do this one thing for hours now.

What I want to do is select all array items that have a specific value. This is easiest to explain by example:

I have an array, called media[]. It holds ALL of the media in my media gallery. It has two properties of note: path and gallery, or media[x][0] and media[x][1].

I want to select all media objects that belong in a certain gallery, and then add them to that gallery. That's where I'm struggling and it's driving me mad.

Here are my fumbled attempts at trying to do this... this is some seriously messy code (and mostly pointless), I'm just providing it so you can get a sense of how clueless I am about this. Please note that NONE of the code I have right now actually tries to do anything; everything I've done so far ends up as a broken for or while loop that either does nothing or crashes Chrome.

// this function is meant to return an array of all media items
// that belong in a certain gallery... didn't get that far because
// the loops tripped me up
function getTheMedia (galNum) {
    var output = [];
    for (var i = 0; i < media.length; ++i) {
        // I tried using an if statement here to check if the
        // media[i][1] == galNum, and if so, add it to the output
        // but that didn't work
        output.push(media[i]);
    }
    return output;
}

// this function was actually my first attempt but I kept running into
// the same issue as above
function fillGal () {
    /*
    var output = [];
    for (var i = 0; i < Gallery.length; ++i) {
        output.push(Gallery[i]);
    }
    */
    var output = [];
    var i = 0;
    while (i < media.length) {
        output.push(i);
        i++;
    }
    console.log(output);
}

Seeing as I'm kind of burnt out and frustrating with running in circles (...loops? aha...), all I'm really looking for is a way to select only those specific array items as specified above. Everything else (adding them to the Gallery, etc) I can figure out myself.

Otherwise I'm just going to have to go back to the old way: define separate media[]arrays for each "gallery" (mediaThisGallery, mediaThatGallery, etc), and then combine them all at the end to get "allMedia". Only reason I don't want to do that is because I want to be able to change which gallery a media item belongs to... this HAS to be possible, right?

Thanks in advance! Sorry for the scatter-brainedness. I also apologize if the title is a bit off.

EDIT:

var media = [];

media[0] = ['0.png', 0, 'index'];
media[1] = ['0.png', 0];

media[2] = ['new/316.png', 1, "316"];
media[3] = ['new/kitties.jpg', 1, "D'aww kitties!!"];
media[4] = ['new/home.jpg', 1, "\"I'm Going Home\""];
media[5] = ['new/3.mp4', 1, "Crucible Carnage"];
media[6] = ['new/942.jpg', 1, "this is straight for testing purposes like omg long ass title lol"];
media[7] = ['new/boom.mp4', 1, "Maximum Efficiency"];
media[8] = ['new/42.jpg', 1, "Moo"];

// this is only included as a quick fix so my working code doesn't break
// as my "production" code is using multiple arrays; Media is used
// to store only the selected array (current Gallery)
// in other words, ignore this
var Media = [];
Media = media;

var Gallery = [];
Gallery[0] = [mediaRoot, "index", media ];
Gallery[1] = [mediaRoot, "new", Media ];

It's pretty arbitrary atm.

Note that the main reason I'm converting from multiple arrays to a single array is that eventually, I plan to expand this app and I thought it made more sense to store ALL media in a single "database".

Body:
Javascript arrays have a filter function, like so:

console.log([0,1,2,3,4,5,6,7,8,9,10].filter(v=>v!==0))

The above example remove all the '0' from the array.
I think it can be helpful in your case.

More information in: https://www.w3schools.com/jsref/jsref_filter.asp


问:
How to change color of bootstrap glyphicon .?
How do I change the color of my star glyphicon? My code is

```<code><span  class="glyphicon glyphicon-star-empty " onclick = "addToFav()">      </span>
</code>```

I am calling a javascript function on the click of glyphicon. I also want to change the color of the glyphicon as shown in the image below. I tried changing the background color of the gyphicon but it doesn't give me the desired output.
**Update"' On changing the style.color of the glyphicon, it just changes the color of the glyphicon but doesn't fill the glypicon with the desired color. The first image is the original glyphicon. The second image is the desired result. The third image is the glyphicon on changing the background color of the glyphicon. The fourth image shows what happens to glyphicon on changing style.color of glyphicon to red.

答:
The following code worked out the best for me. In my class list for glyphicon, I added both, the class for filled star and the class for the empty star. The empty star class is written after the star class and thus it overrides the filled star class and hence, initially I get the empty start on the screen. The code is as follows

```<code><span id="star-glyp"class="glyphicon glyphicon-star glyphicon-star-empty" onclick = "addToFav()">
</code>```

On clicking this glyphicon, I call addToFav() function. In this function, I am doing two things to produce the desired output. First, I am changing the color of the glyphicon to yellow. Second, I am removing the glyphicon-star-empty class from my class list. The code is as follows:

```<code> function addToFav(){

                ths = document.getElementById("star-glyp");
                ths.style.color="YELLOW";
                ths.classList.remove('glyphicon-star-empty');
}
</code>```

Body:
How do I change the color of my star glyphicon? My code is

I am calling a javascript function on the click of glyphicon. I also want to change the color of the glyphicon as shown in the image below. I tried changing the background color of the gyphicon but it doesn't give me the desired output.
**Update"' On changing the style.color of the glyphicon, it just changes the color of the glyphicon but doesn't fill the glypicon with the desired color. The first image is the original glyphicon. The second image is the desired result. The third image is the glyphicon on changing the background color of the glyphicon. The fourth image shows what happens to glyphicon on changing style.color of glyphicon to red.

Body:
The following code worked out the best for me. In my class list for glyphicon, I added both, the class for filled star and the class for the empty star. The empty star class is written after the star class and thus it overrides the filled star class and hence, initially I get the empty start on the screen. The code is as follows

<span id="star-glyp"class="glyphicon glyphicon-star glyphicon-star-empty" onclick = "addToFav()">

On clicking this glyphicon, I call addToFav() function. In this function, I am doing two things to produce the desired output. First, I am changing the color of the glyphicon to yellow. Second, I am removing the glyphicon-star-empty class from my class list. The code is as follows:

 function addToFav(){

                ths = document.getElementById("star-glyp");
                ths.style.color="YELLOW";
                ths.classList.remove('glyphicon-star-empty');
}


问:
How to append elements into a dictionary in Swift?
I have a simple Dictionary which is defined like:

```<code>var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
</code>```

Now I want to add an element into this dictionary: 3 : "efg"

How can I append 3 : "efg" into this existing dictionary?

答:
Dict.updateValue updates value for existing key from dictionary or adds new new key-value pair if key does not exists.

Example-

```<code>var caseStatusParams: [String: AnyObject] = ["userId" : UserDefault.userID ]
caseStatusParams.updateValue("Hello" as AnyObject, forKey: "otherNotes")
</code>```

Result-

```<code>▿  : 2 elements
    - key : "userId"
    - value : 866
▿  : 2 elements
    - key : "otherNotes"
    - value : "Hello"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a simple Dictionary which is defined like:

var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]

Now I want to add an element into this dictionary: 3 : "efg"

How can I append 3 : "efg" into this existing dictionary?

Body:
Dict.updateValue updates value for existing key from dictionary or adds new new key-value pair if key does not exists.

Example-

var caseStatusParams: [String: AnyObject] = ["userId" : UserDefault.userID ]
caseStatusParams.updateValue("Hello" as AnyObject, forKey: "otherNotes")

Result-

▿  : 2 elements
    - key : "userId"
    - value : 866
▿  : 2 elements
    - key : "otherNotes"
    - value : "Hello"


问:
How to get the search box value in
 tag - HTML,JS
Am new to javascript i foud this one in w3schools.com -  Entering pincode in search box will show in
 tag !! How to do ? any help appreciated. Thanks in advance

HTML :

```<code><form class="form1" role="search" method="get" action="search-pincode.html">
<input class="pincode1" type="number" placeholder="Enter Postcode" id="user-pincode">
<button class="submit" type="submit" formaction="search-pincode.html" onclick="myFunction()">Check</button>
</form>
</code>```

JS SCRIPT :

```<code>    <script>
    function myFunction() {
    var x = document.getElementById("user-pincode").value;
    document.getElementById("user-pincode-show").innerHTML = x;
    }
    </script>
</code>```

OUTPUT : search-pincode.html

```<code>                <h1 class="search-h1-contact">
                Yes, we install CCTV in <p id="user-pincode-show"></p>
                </h1>
</code>```

答:
function myFunction() {
   var x = document.getElementById("user-pincode");
document.getElementById('user-pincode-show').innerHTML = x.value;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="form1" role="search" method="get" action="search-pincode.html">
  <input type="number" placeholder="Enter Postcode" id="user-pincode">
  <button type="button" onclick="myFunction()">Check</button>
</form>

<h1 class="search-h1-contact">
                Yes, we install CCTV in
<p id="user-pincode-show"></p></h1></code>```

Title: How to get the search box value in <p> tag - HTML,JS

Body:
Am new to javascript i foud this one in w3schools.com -  Entering pincode in search box will show in
 tag !! How to do ? any help appreciated. Thanks in advance

HTML :

<form class="form1" role="search" method="get" action="search-pincode.html">
<input class="pincode1" type="number" placeholder="Enter Postcode" id="user-pincode">
<button class="submit" type="submit" formaction="search-pincode.html" onclick="myFunction()">Check</button>
</form>

JS SCRIPT :

OUTPUT : search-pincode.html

                Yes, we install CCTV in

Body:
function myFunction() {
   var x = document.getElementById("user-pincode");
document.getElementById('user-pincode-show').innerHTML = x.value;
    }

<form class="form1" role="search" method="get" action="search-pincode.html">
  <input type="number" placeholder="Enter Postcode" id="user-pincode">
  <button type="button" onclick="myFunction()">Check</button>
</form>

<h1 class="search-h1-contact">
                Yes, we install CCTV in
<p id="user-pincode-show"></p></h1>


问:
replace an empty numpy string with 0
I have to numpy string array which look like this:

[['0', '', '12.12', '140.65', '', ''],

  ['3', '', '10.45', '154.45', '', ''],

  ['5', '', '15.65', '184.74', '', '']]

What I need to do is to replace the empty cells with a number in order to convert it into a float array. I can't just delete the columns because in some cases the empty cells are filled. I tried this:

```<code>data = np.char.replace(data, '','0').astype(np.float64)
</code>```

But this will just put a 0 everywhere between all characters which ends up in this:

[[0, 0, 1020.0102, 104000.0605, 0, 0],

  [30, 0, 1000.0405, 105040.0405, 0, 0],

  [50, 0, 1050.0605, 108040.0704, 0, 0]]

I can't figure out why python does that? I searched via google but couldn't find a good explanation for numpy.char.replace. Can anyone explain to me how it works?

Title: replace an empty numpy string with 0

Body:
I have to numpy string array which look like this:

[['0', '', '12.12', '140.65', '', ''],

  ['3', '', '10.45', '154.45', '', ''],

  ['5', '', '15.65', '184.74', '', '']]

What I need to do is to replace the empty cells with a number in order to convert it into a float array. I can't just delete the columns because in some cases the empty cells are filled. I tried this:

data = np.char.replace(data, '','0').astype(np.float64)

But this will just put a 0 everywhere between all characters which ends up in this:

[[0, 0, 1020.0102, 104000.0605, 0, 0],

  [30, 0, 1000.0405, 105040.0405, 0, 0],

  [50, 0, 1050.0605, 108040.0704, 0, 0]]

I can't figure out why python does that? I searched via google but couldn't find a good explanation for numpy.char.replace. Can anyone explain to me how it works?

Body:
data = np.char.replace(data, '','0')

It seems to replace all empty places, like '' has one place , and '0' has two places, '12.12' has 6 places. The result is

[['000' '0' '01020.01020' '0104000.06050' '0' '0']
 ['030' '0' '01000.04050' '0105040.04050' '0' '0']
 ['050' '0' '01050.06050' '0108040.07040' '0' '0']]

Try this :

import numpy as np

a = np.array([['0', '', '12.12', '140.65', '', ''],
              ['3', '', '10.45', '154.45', '', ''],
              ['5', '', '15.65', '184.74', '', '']])

#a[np.where(a == '')] = '0'
a[a == ''] = '0'

a = a.astype(np.float64)

print(a)


问:
How do I best organise multiple projects in GIT?
I'm elaluating whether GIT is possible to organise our projects.
We are working under Windows with Visual Studio 2010 on a local network.

Our project organisation is as follows:

We have a shared code base (call it SHARE) where all developers are allowed to extend, modify and do bug fixes.
All developers have multiple private projects which depend on thes shared code base.
So the structure is:

```<code>root
   |
   +-- SHARE
   +-- Project 1 Dev 1
   +-- Project 2 Dev 1
   +-- Project 1 Dev 2
</code>```

What I think of is one origin Repository on a network drive with clones on every developer PC and 1 private Repository for each project on the developer PCs (maybe some backup on network as well). Good would be some kind of link, so that when a developer checks out his project he will get the correct shared source as well.
Is this possible with GIT and how?

Or can you recommend a better way?

答:
Good would be some kind of link, so
  that when a developer checks out his
  project he will get the correct shared
  source as well. Is this possible with
  GIT and how?

Submodules is probably what you're after -- they let you store a "pointer" to some other repo inside a main one (the "superproject") with metadata about the exact "state" of the subproject so everyone is working against a consistent shared subproject.

The submodule itself can be worked on and improved just like any other repository, and the "state" pointer can be updated to the newly agreed upon version whenever is appropriate.

So your superproject would contain one submodule: "shared", and when devs clone your main repo, they run git submodule init && git submodule update to automatically get their submodules set up as necessary.

Body:
I'm elaluating whether GIT is possible to organise our projects.
We are working under Windows with Visual Studio 2010 on a local network.

Our project organisation is as follows:

We have a shared code base (call it SHARE) where all developers are allowed to extend, modify and do bug fixes.
All developers have multiple private projects which depend on thes shared code base.
So the structure is:

root
   |
   +-- SHARE
   +-- Project 1 Dev 1
   +-- Project 2 Dev 1
   +-- Project 1 Dev 2

What I think of is one origin Repository on a network drive with clones on every developer PC and 1 private Repository for each project on the developer PCs (maybe some backup on network as well). Good would be some kind of link, so that when a developer checks out his project he will get the correct shared source as well.
Is this possible with GIT and how?

Or can you recommend a better way?


问:
Call a function in another function
I have a function publicRooms to display public discussions that are on the server. I want to use this data for another function I created addNewMessageNewThread:

```<code>matrixClient.publicRooms(function(err, data) {
  console.log("Public Rooms: %s", JSON.stringify(data));
  console.log("data", data.chunk[0].aliases[0]);

  this.addNewMessageNewThread({
    'id': 'paul',
    'author': 'Paul Manip',
    'body': '  ?'
  });
});
</code>```

Off when I do that, he tells me he does not know this function :

ERROR TypeError: Cannot read property 'addNewMessageNewThread' of
  undefined

And when I test this function outside the function, it works

///////////EDIT//////////////

This is my function addNewMessageNewThread() :

```<code>addNewMessageNewThread(objMessage: any): void {

    const newUser: User      = new User(objMessage.author, objMessage.site);
    const newThread: Thread = new Thread(objMessage.id, [newUser],objMessage.title);
    const newMessage = new Message(objMessage);

    objMessage.date = moment().toDate();

    newThread.arrayMessages.push(newMessage);
    newThread.messages = Observable.of(newThread.arrayMessages);

    newThread.lastMessage = newMessage;

    objMessage.thread = newThread;
    this.addThread(newThread);
}
</code>```

答:
Instrad of calling this.addNewMessageNewThread try with matrixClient.addNewMessageNewThread.

this reffers to the callback's context.

If this addNewMessageNewThread doesn't belong to the matrixClient (guessing), before calling matrixClient.publicRooms(), assing:

```<code>var that = this;
</code>```

And use that inside callback instead of this.

Title: Call a function in another function

Body:
I have a function publicRooms to display public discussions that are on the server. I want to use this data for another function I created addNewMessageNewThread:

matrixClient.publicRooms(function(err, data) {
  console.log("Public Rooms: %s", JSON.stringify(data));
  console.log("data", data.chunk[0].aliases[0]);

  this.addNewMessageNewThread({
    'id': 'paul',
    'author': 'Paul Manip',
    'body': '  ?'
  });
});

Off when I do that, he tells me he does not know this function :

ERROR TypeError: Cannot read property 'addNewMessageNewThread' of
  undefined

And when I test this function outside the function, it works

///////////EDIT//////////////

This is my function addNewMessageNewThread() :

addNewMessageNewThread(objMessage: any): void {

    const newUser: User      = new User(objMessage.author, objMessage.site);
    const newThread: Thread = new Thread(objMessage.id, [newUser],objMessage.title);
    const newMessage = new Message(objMessage);

    objMessage.date = moment().toDate();

    newThread.arrayMessages.push(newMessage);
    newThread.messages = Observable.of(newThread.arrayMessages);

    newThread.lastMessage = newMessage;

    objMessage.thread = newThread;
    this.addThread(newThread);
}

Body:
Instrad of calling this.addNewMessageNewThread try with matrixClient.addNewMessageNewThread.

this reffers to the callback's context.

If this addNewMessageNewThread doesn't belong to the matrixClient (guessing), before calling matrixClient.publicRooms(), assing:

var that = this;

And use that inside callback instead of this.


问:
How to fix the "Base table or view not found: 1146" error when running 'php artisan migrate' command?
I am trying to rum php artisan migrate to generate table migration, but I am getting an error:

[2016-03-08 05:49:01] local.ERROR: exception 'PDOException' with
message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table
'testing.permissions' doesn't exist' in
D:\xampp\htdocs\LMS-testing\vendor\laravel\framework\src\Illuminate\Database\Connection.php:333

I have tried Base table or view not found: 1146 Table Laravel 5 and Doing a Laravel tutorial, getting "Base table or view not found: 1146 Table 'sdbd_todo.migrations' doesn't exist" but did not succeed.

I have also tried to run php artisan list but getting the same error.

Updated

```<code>**RolesPermission migration table**

Schema::create('roles', function(Blueprint $table){
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('label');
            $table->string('description')->nullable();
            $table->timestamps();
        });

        Schema::create('permissions', function(Blueprint $table){
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('label');
            $table->string('description')->nullable();
            $table->timestamps();
        });

        Schema::create('permission_role', function(Blueprint $table){
            $table->integer('permission_id')->unsigned();
            $table->integer('role_id')->unsigned();

            $table->foreign('permission_id')
                    ->references('id')
                    ->on('permissions')
                    ->onDelete('cascade');

            $table->foreign('role_id')
                    ->references('id')
                    ->on('roles')
                    ->onDelete('cascade');

            $table->primary(['permission_id', 'role_id']);
        });

        Schema::create('role_user', function(Blueprint $table){
            $table->integer('role_id')->unsigned();
            $table->integer('user_id')->unsigned();

            $table->foreign('role_id')
                    ->references('id')
                    ->on('roles')
                    ->onDelete('cascade');

            $table->foreign('user_id')
                    ->references('id')
                    ->on('users')
                    ->onDelete('cascade');

            $table->primary(['role_id', 'user_id']);

        });

.env file
APP_ENV=local
APP_DEBUG=true
APP_KEY=W8YWZe3LCngvZzexH3WLWqCDlYRSufuy

DB_HOST=127.0.0.1
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=log
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
</code>```

答:
The problem is that the foreign keys are added but cannot find the table because it hasn't been created.

1) make tables without foreign keys

2) Make a 9999_99_99_999999_create_foreign_keys.php file

3) put there the foreign keys you want. With the 999..9 .php file it makes sure that it does the foreign keys last after the tables have been made.

4) You have added the tables first and then added the foreign keys. This will work.

Body:
I am trying to rum php artisan migrate to generate table migration, but I am getting an error:

[2016-03-08 05:49:01] local.ERROR: exception 'PDOException' with
message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table
'testing.permissions' doesn't exist' in
D:\xampp\htdocs\LMS-testing\vendor\laravel\framework\src\Illuminate\Database\Connection.php:333

I have tried Base table or view not found: 1146 Table Laravel 5 and Doing a Laravel tutorial, getting "Base table or view not found: 1146 Table 'sdbd_todo.migrations' doesn't exist" but did not succeed.

I have also tried to run php artisan list but getting the same error.

Updated

**RolesPermission migration table**

Schema::create('roles', function(Blueprint $table){
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('label');
            $table->string('description')->nullable();
            $table->timestamps();
        });

        Schema::create('permissions', function(Blueprint $table){
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('label');
            $table->string('description')->nullable();
            $table->timestamps();
        });

        Schema::create('permission_role', function(Blueprint $table){
            $table->integer('permission_id')->unsigned();
            $table->integer('role_id')->unsigned();

            $table->foreign('permission_id')
                    ->references('id')
                    ->on('permissions')
                    ->onDelete('cascade');

            $table->foreign('role_id')
                    ->references('id')
                    ->on('roles')
                    ->onDelete('cascade');

            $table->primary(['permission_id', 'role_id']);
        });

        Schema::create('role_user', function(Blueprint $table){
            $table->integer('role_id')->unsigned();
            $table->integer('user_id')->unsigned();

            $table->foreign('role_id')
                    ->references('id')
                    ->on('roles')
                    ->onDelete('cascade');

            $table->foreign('user_id')
                    ->references('id')
                    ->on('users')
                    ->onDelete('cascade');

            $table->primary(['role_id', 'user_id']);

        });

.env file
APP_ENV=local
APP_DEBUG=true
APP_KEY=W8YWZe3LCngvZzexH3WLWqCDlYRSufuy

DB_HOST=127.0.0.1
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=log
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null


问:
Get excel cell address in Python 2 using openpyxl
I have the following scenario:

Read the excel file of column A for all active rows

Run if else statement: if column A == 'registered', do nothing and just read the next row. Else, get cell address (not value) and do some actions

For example, here is my "sample.xlsx":

[row 1] A1=registered B1=user1

[row 2] A2=registered B2=user2

[row 3] A3=null B3=user3

my code should ignore row1 and row2 and proceed with row 3. In row 3, I should get "A3" and do some actions.

```<code>from openpyxl import load_workbook
book = load_workbook(filename='sample.xlsx')
sheet = book.active
first_column = sheet['A']

for x in xrange(len(first_column)):
    status = first_column[x].value

    if status == 'registered':
      #enter code to just proceed with the next row

    else:
      #enter code to get the column cell range and do some actions

book.save('sample.xlsx')
</code>```

I got stucked with the scenario 2, I am a newbie in python, I have a code in java using FileScanner but I need it in Python 2. Appreciate your help.

UPDATE:
I already have an answer below but just wondering if there are any other method??

答:
so far, I have tried these. is there any other method?

```<code>from openpyxl import load_workbook
book = load_workbook(filename='sample.xlsx')
sheet = book.active
first_column = sheet['A']
checker = 'false'

for x in xrange(len(first_column)):
    status = first_column[x].value
    xaddress = first_column[x].column
    yaddress = first_column[x].row
    celladdress = xaddress+str(yaddress)

    if status != 'registered':
        print celladdress
        checker == 'true'
        break

if checker == 'true':
    #... my actions here ....
</code>```

Here is my "sample.xlsx":

[row 1] A1=registered B1=user1

[row 2] A2=registered B2=user2

[row 3] A3=null B3=user3

Output: A3

Body:
I have the following scenario:

Read the excel file of column A for all active rows

Run if else statement: if column A == 'registered', do nothing and just read the next row. Else, get cell address (not value) and do some actions

For example, here is my "sample.xlsx":

[row 1] A1=registered B1=user1

[row 2] A2=registered B2=user2

[row 3] A3=null B3=user3

my code should ignore row1 and row2 and proceed with row 3. In row 3, I should get "A3" and do some actions.

from openpyxl import load_workbook
book = load_workbook(filename='sample.xlsx')
sheet = book.active
first_column = sheet['A']

for x in xrange(len(first_column)):
    status = first_column[x].value

    if status == 'registered':
      #enter code to just proceed with the next row

    else:
      #enter code to get the column cell range and do some actions

book.save('sample.xlsx')

I got stucked with the scenario 2, I am a newbie in python, I have a code in java using FileScanner but I need it in Python 2. Appreciate your help.

UPDATE:
I already have an answer below but just wondering if there are any other method??

Body:
so far, I have tried these. is there any other method?

from openpyxl import load_workbook
book = load_workbook(filename='sample.xlsx')
sheet = book.active
first_column = sheet['A']
checker = 'false'

for x in xrange(len(first_column)):
    status = first_column[x].value
    xaddress = first_column[x].column
    yaddress = first_column[x].row
    celladdress = xaddress+str(yaddress)

    if status != 'registered':
        print celladdress
        checker == 'true'
        break

if checker == 'true':
    #... my actions here ....

Here is my "sample.xlsx":

[row 1] A1=registered B1=user1

[row 2] A2=registered B2=user2

[row 3] A3=null B3=user3

Output: A3


问:
How to make the result of "print df" equal the result of "df"

Like the picture above, the df is dataframe, I want the result of running print df on jupyter is dataframe. If tpye(print df),the answer is NoneType instead pd.DataFrame.

答:
Now,I figure it out later.Acctually,my boss told me the answer.thanks to my boss.it is akward to answer my own question,but I still want to answer it in case someone else id in the same situation as me.And everybody can discuss the answer,I think there is better answer.
It can use display

from IPython.display import display,HTML

display(df)

so I can see df in a def.


问:
Angular throwing exception 'module cant be loaded'!
I was trying to clean my angular app code up. So I moved all the controllers in their own files. But when I moved the controllers, my main app stoped working and started throwing the exception below -

Error: $injector:modulerr
  Module Error

Then I tried searching for the why the module won't load but with no luck.

```<code>main.js /*File where app module is declared*/

var app = angular.module('app', ['ngRoute','thatisuday.dropzone','UserController','LinkController','articleController']);
</code>```

I tried injecting the dependency for the controller files.

Controllers:

Link Controller

```<code>var app = angular.module('app');

app.controller('LinkController', ['$scope','$http','$sce',function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

$scope.trustSrc = function (src) {
    return $sce.trustAsResourceUrl(src);
};

/*First AJAX request which gets all the links and categories for the user*/

$http({
    method: 'GET',
    url: '/users'
}).then(function successCallback(response) {

    $scope.user = response.data;

}, function errorCallback(response) {

});

$scope.getUser = function () {
    $http({
        method: 'GET',
        url: '/users'
    }).then(function successCallback(response) {

        $scope.user = response.data;

    }, function errorCallback(response) {

    });
};

$http({
    method: 'GET',
    url: '/links'
}).then(function successCallback(response) {

    this.orderProp = 'age';

    /*the response is saved in scope variables*/
    $scope.links = response.data[0];
    $scope.categories = response.data[1];
    $scope.categorytolink = response.data[2];

}, function errorCallback(response) {
    console.log('There was a problem! Refresh!');
});

/*AJAX request for getting the recommendations according to the most viewed stars*/

$http({
    method: 'GET',
    url: '/recommendations/top'
}).then(function successCallback(response) {

    $scope.recommendations = response.data;

}, function errorCallback(response) {

});

/*AJAX request when a user clicks a link retrieves the link data*/
$scope.getLinkData = function (link) {
    $http({
        method: 'GET',
        url: "/proxy",
        headers: {
            "X-Proxy-To": link.rss_link
        }
    }).then(function successCallback(response) {

        /*AJAX request: add a star to the link*/

        $http.post('/links/' + link.id + '/views/add', {'link': link}).then(function successCallback(data, status, headers, config) {

            // Manually increment star for link just clicked

            var $data;

            $data = data.data;

            $scope.link = $data;

            console.log('200 OK! Star added');

        }, function errorCallback() {

            console.log('Error!');

        });

        /*The data will be retrieved and will be sorted according to the requirements of welcome.blade*/

        $myXml = response.data;

        $xmlObj = $.parseXML($myXml);

        $newsItems = [];

        $channelImage = $($xmlObj).find("channel>image");

        /*the information of the link is sorted */

        $linkData = {
            "title": $channelImage.find("title").text(),
            "link": $channelImage.find("link").text(),
            "imgurl": $channelImage.find("url").text()

        };

        /*the data is sorted below*/

        $.each($($xmlObj).find("item"), function (index, value) {
            $newsItems.push({
                "title": $(value).find("title").text(),
                "description": $(value).find("description").text(),
                "link": $(value).find("link").text(),
                "date_published": moment($(value).find("pubDate").text()).format('MMMM Do YYYY'),
                "time_published": moment($(value).find("pubDate").text()).format('h:mm:ss a'),
                "guid": $(value).find("guid").text()
            })
        });

        $scope.newsItems = $newsItems;

        $scope.linkData = $linkData;

    }, function errorCallback(response) {

    });
};

/*Create a category private to the user*/

$scope.create_category = function (category) {

    /*AJAX request: adds a new category*/
    $http.post('/categories/new', {'category': category}).then(function successCallback(response) {

        /*AJAX request: Updates the categories for the use of new category*/

        $http({
            method: 'GET',
            url: '/categories'
        }).then(function successCallback(response) {

            $scope.categories = response.data;

        }, function errorCallback(response) {

        });
    }, function errorCallback(response) {

    });

};
}]);
</code>```

User Controller

```<code>    var app = angular.module('app');

app.controller("UserController", ['$scope','$http','$sce', function ($scope, $http, $sce) {

/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

$scope.trustSrc = function (src) {
    return $sce.trustAsResourceUrl(src);
};

$scope.dzOptions = {
    paramName: "file",
    dictDefaultMessage: "<h4><i class='fa fa-camera'></i> <b>Upload</b></h4>",
    createImageThumbnails: false,
    autoDiscover: false
};

$scope.dzCallbacks = {
    'sending': function (file, xhr, formData) {
        formData.append('_token', $('#csrf-token').val());
    },
    'success': function (file, response) {
        $scope.user = response;
        $.notify("Profile photo changed!", "success", {autoHide: true, autoHideDelay: 500});
    }
};

/*Update user info*/
$scope.updateUser = function () {
    /*AJAX request: update user info*/
    $http.post('/users/update', {
        'name': $scope.user.name,
        'username': $scope.user.username,
        'email': $scope.user.email
    }).then(
        function successCallback(data) {
            $scope.user = data;
            $.notify("User updated!", "success", {autoHide: true, autoHideDelay: 500});
            console.log('200 OK! User updated');
        }, function errorCallback() {
            console.log('Error!');
        });
};

}]);
</code>```

Article Controller

```<code>    var app = angular.module('app');

app.controller("articleController", ['$scope','$http','$sce', function ($scope, $http, $sce) {

/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

$scope.trustSrc = function (src) {
    return $sce.trustAsResourceUrl(src);
};

/*Populates the comments for particular
 * */
$scope.populatecomments = function (newsItem) {
    $http({
        method: 'GET',
        url: '/articles/' + newsItem.guid + '/comments'
    }).then(function successCallback(response) {

        $scope.comments = response.data;

    }, function errorCallback(response) {

    });
};

$scope.data = [];
$scope.comment = [];
$scope.btn_add = function (newsItem) {
    if ($scope.txtcomment != '') {
        $scope.data.push({
            "comment": $scope.txtcomment,
            "guid": newsItem.guid
        });
        $http.post('/comments/new', {
            "comment": $scope.txtcomment,
            "guid": newsItem.guid
        }).then(function successCallback() {

            var encodedURI = encodeURIComponent(newsItem.guid);

            $http({
                method: 'GET',
                url: '/articles/' + encodedURI + '/comments'
            }).then(function successCallback(response) {

                $scope.comments = response.data;

                $scope.txtcomment = "";

            }, function errorCallback(response) {

            });
        }, function errorCallback() {

            console.log('Error comment!');
        });

    }
};

$scope.savearticle = function (newsItem) {
    $http.post('/saved-articles/save', newsItem).then(function successCallback(response) {
        /*console.log(document.getElementById("save/"+newsItem.guid).className="disabled");*/
    }, function errorCallback(response) {

    });
}

/**
 * The saved articles by the user will be retrieved when a button clicked
 */

$scope.getSavedArticles = function () {

    /*AJAX request: retreive the saved the saved articles for the user*/

    $http({
        method: 'GET',
        url: '/saved-articles'
    }).then(function successCallback(response) {

        $scope.linkData = null;

        $scope.newsItems = response.data;

    }, function errorCallback(response) {

    });
};
}]);
</code>```

HELP needed!

答:
Yo do not need to declare module in each controller file. Remove the line in each controller</p>

```<code> var app = angular.module('app');
</code>```

Body:
I was trying to clean my angular app code up. So I moved all the controllers in their own files. But when I moved the controllers, my main app stoped working and started throwing the exception below -

Error: $injector:modulerr
  Module Error

Then I tried searching for the why the module won't load but with no luck.

main.js /*File where app module is declared*/

var app = angular.module('app', ['ngRoute','thatisuday.dropzone','UserController','LinkController','articleController']);

I tried injecting the dependency for the controller files.

Controllers:

Link Controller

var app = angular.module('app');

app.controller('LinkController', ['$scope','$http','$sce',function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

$scope.trustSrc = function (src) {
    return $sce.trustAsResourceUrl(src);
};

/*First AJAX request which gets all the links and categories for the user*/

$http({
    method: 'GET',
    url: '/users'
}).then(function successCallback(response) {

    $scope.user = response.data;

}, function errorCallback(response) {

});

$scope.getUser = function () {
    $http({
        method: 'GET',
        url: '/users'
    }).then(function successCallback(response) {

        $scope.user = response.data;

    }, function errorCallback(response) {

    });
};

$http({
    method: 'GET',
    url: '/links'
}).then(function successCallback(response) {

    this.orderProp = 'age';

    /*the response is saved in scope variables*/
    $scope.links = response.data[0];
    $scope.categories = response.data[1];
    $scope.categorytolink = response.data[2];

}, function errorCallback(response) {
    console.log('There was a problem! Refresh!');
});

/*AJAX request for getting the recommendations according to the most viewed stars*/

$http({
    method: 'GET',
    url: '/recommendations/top'
}).then(function successCallback(response) {

    $scope.recommendations = response.data;

}, function errorCallback(response) {

});

/*AJAX request when a user clicks a link retrieves the link data*/
$scope.getLinkData = function (link) {
    $http({
        method: 'GET',
        url: "/proxy",
        headers: {
            "X-Proxy-To": link.rss_link
        }
    }).then(function successCallback(response) {

        /*AJAX request: add a star to the link*/

        $http.post('/links/' + link.id + '/views/add', {'link': link}).then(function successCallback(data, status, headers, config) {

            // Manually increment star for link just clicked

            var $data;

            $data = data.data;

            $scope.link = $data;

            console.log('200 OK! Star added');

        }, function errorCallback() {

            console.log('Error!');

        });

        /*The data will be retrieved and will be sorted according to the requirements of welcome.blade*/

        $myXml = response.data;

        $xmlObj = $.parseXML($myXml);

        $newsItems = [];

        $channelImage = $($xmlObj).find("channel>image");

        /*the information of the link is sorted */

        $linkData = {
            "title": $channelImage.find("title").text(),
            "link": $channelImage.find("link").text(),
            "imgurl": $channelImage.find("url").text()

        };

        /*the data is sorted below*/

        $.each($($xmlObj).find("item"), function (index, value) {
            $newsItems.push({
                "title": $(value).find("title").text(),
                "description": $(value).find("description").text(),
                "link": $(value).find("link").text(),
                "date_published": moment($(value).find("pubDate").text()).format('MMMM Do YYYY'),
                "time_published": moment($(value).find("pubDate").text()).format('h:mm:ss a'),
                "guid": $(value).find("guid").text()
            })
        });

        $scope.newsItems = $newsItems;

        $scope.linkData = $linkData;

    }, function errorCallback(response) {

    });
};

/*Create a category private to the user*/

$scope.create_category = function (category) {

    /*AJAX request: adds a new category*/
    $http.post('/categories/new', {'category': category}).then(function successCallback(response) {

        /*AJAX request: Updates the categories for the use of new category*/

        $http({
            method: 'GET',
            url: '/categories'
        }).then(function successCallback(response) {

            $scope.categories = response.data;

        }, function errorCallback(response) {

        });
    }, function errorCallback(response) {

    });

};
}]);

User Controller

    var app = angular.module('app');

app.controller("UserController", ['$scope','$http','$sce', function ($scope, $http, $sce) {

/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

$scope.trustSrc = function (src) {
    return $sce.trustAsResourceUrl(src);
};

$scope.dzOptions = {
    paramName: "file",
    dictDefaultMessage: "
 Upload
",
    createImageThumbnails: false,
    autoDiscover: false
};

$scope.dzCallbacks = {
    'sending': function (file, xhr, formData) {
        formData.append('_token', $('#csrf-token').val());
    },
    'success': function (file, response) {
        $scope.user = response;
        $.notify("Profile photo changed!", "success", {autoHide: true, autoHideDelay: 500});
    }
};

/*Update user info*/
$scope.updateUser = function () {
    /*AJAX request: update user info*/
    $http.post('/users/update', {
        'name': $scope.user.name,
        'username': $scope.user.username,
        'email': $scope.user.email
    }).then(
        function successCallback(data) {
            $scope.user = data;
            $.notify("User updated!", "success", {autoHide: true, autoHideDelay: 500});
            console.log('200 OK! User updated');
        }, function errorCallback() {
            console.log('Error!');
        });
};

}]);

Article Controller

    var app = angular.module('app');

app.controller("articleController", ['$scope','$http','$sce', function ($scope, $http, $sce) {

/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
    return $sce.trustAsHtml(html_code);
};

$scope.trustSrc = function (src) {
    return $sce.trustAsResourceUrl(src);
};

/*Populates the comments for particular
 * */
$scope.populatecomments = function (newsItem) {
    $http({
        method: 'GET',
        url: '/articles/' + newsItem.guid + '/comments'
    }).then(function successCallback(response) {

        $scope.comments = response.data;

    }, function errorCallback(response) {

    });
};

$scope.data = [];
$scope.comment = [];
$scope.btn_add = function (newsItem) {
    if ($scope.txtcomment != '') {
        $scope.data.push({
            "comment": $scope.txtcomment,
            "guid": newsItem.guid
        });
        $http.post('/comments/new', {
            "comment": $scope.txtcomment,
            "guid": newsItem.guid
        }).then(function successCallback() {

            var encodedURI = encodeURIComponent(newsItem.guid);

            $http({
                method: 'GET',
                url: '/articles/' + encodedURI + '/comments'
            }).then(function successCallback(response) {

                $scope.comments = response.data;

                $scope.txtcomment = "";

            }, function errorCallback(response) {

            });
        }, function errorCallback() {

            console.log('Error comment!');
        });

    }
};

$scope.savearticle = function (newsItem) {
    $http.post('/saved-articles/save', newsItem).then(function successCallback(response) {
        /*console.log(document.getElementById("save/"+newsItem.guid).className="disabled");*/
    }, function errorCallback(response) {

    });
}

/**
 * The saved articles by the user will be retrieved when a button clicked
 */

$scope.getSavedArticles = function () {

    /*AJAX request: retreive the saved the saved articles for the user*/

    $http({
        method: 'GET',
        url: '/saved-articles'
    }).then(function successCallback(response) {

        $scope.linkData = null;

        $scope.newsItems = response.data;

    }, function errorCallback(response) {

    });
};
}]);

HELP needed!

Body:
Yo do not need to declare module in each controller file. Remove the line in each controller

 var app = angular.module('app');


问:
Why is starred iterable unpacking in a return statement invalid syntax without parentheses before Python 3.8?
The Python language (especially 3.x) allows very general unpacking of iterables, a simple example of which is

```<code>a, *rest = 1, 2, 3
</code>```

Over the years, this unpacking has been gradually generalized (see e.g. PEP 3132 and PEP 448), allowing it to be used in more and more circumstances. As so, I was surprised to discover that the following is invalid syntax in Python 3.6 (and remains so in Python 3.7):

```<code>def f():
    rest = [2, 3]
    return 1, *rest  # Invalid
</code>```

I can make it work by encapsulating the returned tuple in parentheses like so:

```<code>def f():
    rest = [2, 3]
    return (1, *rest)  # Valid
</code>```

The fact that I use this in a return statement seems to be important, as

```<code>t = 1, *rest
</code>```

is indeed legal and results in the same with and without parentheses.

Have this case simply been forgotten by the Python developers, or are there any reason why this case is invalid syntax?

Why I care

This breaks an important contract I thought I had with the Python language. Consider the following (also valid) solution:

```<code>def f():
    rest = [2, 3]
    t = 1, *rest
    return t
</code>```

Normally when I have code like this, I consider t to be a temporary name, which I ought to be able to get rid of simply be replacing t in the bottom line with its definition. In this case though, this leads to the invalid code

```<code>def f():
    rest = [2, 3]
    return 1, *rest
</code>```

It's of course no big deal to have to place parentheses around the return value, but usually additional parentheses are only needed to distinguish between several possible outcomes (grouping). Here this is not the case, as leaving out the parentheses does not produce some other unwanted behavior, but rather no behavior at all.

Update

Since Python 3.8 (see item 7 on this list), the generalized syntax discussed above is now valid.

答:
I suspect this is an accident, based on the comments from this commit for Python 3.2.

That commit enabled the assignment expression to take a testlist_star_expr production (what allows the unparenthesized unpacking), but left the return statement taking a testlist production. I suspect the commit just missed this (and possibly other locations, but I'm focusing on the return_stmt production for now).

I went ahead and modified the Python Grammar/Grammar file to allow this. All of the tests continue to pass, including those in the test_grammar.py file (but this doesn't seem terribly exhaustive).

If you're curious, this is the change I made. Feel free to clone or download my fork.

UPDATE: I've submitted a bpo issue and a pull request for the return (and yield) unpacking.

Body:
The Python language (especially 3.x) allows very general unpacking of iterables, a simple example of which is

a, *rest = 1, 2, 3

Over the years, this unpacking has been gradually generalized (see e.g. PEP 3132 and PEP 448), allowing it to be used in more and more circumstances. As so, I was surprised to discover that the following is invalid syntax in Python 3.6 (and remains so in Python 3.7):

def f():
    rest = [2, 3]
    return 1, *rest  # Invalid

I can make it work by encapsulating the returned tuple in parentheses like so:

def f():
    rest = [2, 3]
    return (1, *rest)  # Valid

The fact that I use this in a return statement seems to be important, as

t = 1, *rest

is indeed legal and results in the same with and without parentheses.

Have this case simply been forgotten by the Python developers, or are there any reason why this case is invalid syntax?

Why I care

This breaks an important contract I thought I had with the Python language. Consider the following (also valid) solution:

def f():
    rest = [2, 3]
    t = 1, *rest
    return t

Normally when I have code like this, I consider t to be a temporary name, which I ought to be able to get rid of simply be replacing t in the bottom line with its definition. In this case though, this leads to the invalid code

def f():
    rest = [2, 3]
    return 1, *rest

It's of course no big deal to have to place parentheses around the return value, but usually additional parentheses are only needed to distinguish between several possible outcomes (grouping). Here this is not the case, as leaving out the parentheses does not produce some other unwanted behavior, but rather no behavior at all.

Update

Since Python 3.8 (see item 7 on this list), the generalized syntax discussed above is now valid.


答:
It can be done by standard functions

```<code>$res = [];
foreach(array_count_values(array_map('json_encode', $a)) as $k=>$v) {
    $res[] = array_fill(0, $v, json_decode($k, true));
}
</code>```

demo on eval.in

Title: php in array collect same array

Body:
I have this array in PHP:

$a = [
['name'=>'salvar','type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
['name'=>'salvar','type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
['name'=>'salvar','type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
['name'=>'salvar','type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
['name'=>'salvar','type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
['name'=>'corab' ,'type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
['name'=>'corab' ,'type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
['name'=>'corab' ,'type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
['name'=>'yag' ,'type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
];

I want to collect same array in one array. Can anyone help please?
i need some thing like this result

 [
  [
   ['name'=>'salvar','type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
   ['name'=>'salvar','type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
   ['name'=>'salvar','type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
   ['name'=>'salvar','type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
   ['name'=>'salvar','type'=>'Qt','count'=>'1','price'=>'10','total'=>'7']
  ],
  [
   ['name'=>'corab' ,'type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
   ['name'=>'corab' ,'type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
   ['name'=>'corab' ,'type'=>'Qt','count'=>'1','price'=>'10','total'=>'7'],
  ],
  [
   ['name'=>'yag' ,'type'=>'Qt','count'=>'1','price'=>'10','total'=>'7']
  ]
 ]

Body:
It can be done by standard functions

$res = [];
foreach(array_count_values(array_map('json_encode', $a)) as $k=>$v) {
    $res[] = array_fill(0, $v, json_decode($k, true));
}

demo on eval.in


问:
How do I launch the recent apps programmatically?

can anyone give me help:
I have put this code is work well if my app is last app opened. but if I open other app after my app, she's stays in background.

if anyone can give me how I can run my application as if it's the last open application or something else like its.

code:

```<code>public void Show_App(String packageName){

this.activity.getWindow().addFlags(
        WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|
        WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
        WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

Intent startIntent =
        context.getPackageManager().getLaunchIntentForPackage(packageName);
startIntent.setFlags(
                Intent.FLAG_ACTIVITY_REORDER_TO_FRONT |
                Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
);
this.context.startActivity(startIntent);
}
</code>```

答:
```<code>private void getRecentAppList() {

    ActivityManager mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RecentTaskInfo> recentTasks = mActivityManager.getRecentTasks(10, 0);
    for (ActivityManager.RecentTaskInfo taskInfo : recentTasks) {
String packagename = task.baseIntent.getComponent().getPackageName();
        Intent intent = taskInfo.baseIntent;
        ResolveInfo resolveInfo = mPackageManager.resolveActivity(intent, 0);
        ActivityInfo activityInfo = resolveInfo.activityInfo;
    } }
</code>```

you didn't close or clear app in recent list than recent app lunch list is get.

Body:
can anyone give me help:
I have put this code is work well if my app is last app opened. but if I open other app after my app, she's stays in background.

if anyone can give me how I can run my application as if it's the last open application or something else like its.

code:

public void Show_App(String packageName){

this.activity.getWindow().addFlags(
        WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|
        WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|
        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|
        WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

Intent startIntent =
        context.getPackageManager().getLaunchIntentForPackage(packageName);
startIntent.setFlags(
                Intent.FLAG_ACTIVITY_REORDER_TO_FRONT |
                Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
);
this.context.startActivity(startIntent);
}

Body:
private void getRecentAppList() {

    ActivityManager mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RecentTaskInfo> recentTasks = mActivityManager.getRecentTasks(10, 0);
    for (ActivityManager.RecentTaskInfo taskInfo : recentTasks) {
String packagename = task.baseIntent.getComponent().getPackageName();
        Intent intent = taskInfo.baseIntent;
        ResolveInfo resolveInfo = mPackageManager.resolveActivity(intent, 0);
        ActivityInfo activityInfo = resolveInfo.activityInfo;
    } }

you didn't close or clear app in recent list than recent app lunch list is get.


问:
Performance of sqrt function on AArch64
I'm taking the performance of sqrt function on AArch64 for academic reasons.
Code for Single float sqrtf function:

```<code>fsqrt s0, s0
ret
</code>```

Code for Double float sqrt function:

```<code>fsqrt d0, d0
ret
</code>```

I'm referring to theoretical latencies for FSQRT from here:
http://infocenter.arm.com/help/topic/com.arm.doc.uan0015b/Cortex_A57_Software_Optimization_Guide_external.pdf

Single sqrt seems 2x better than double.

But, while profiling I'm getting these numbers:

```<code>326 ms  sqrt
 82 ms  sqrtf
</code>```

I'm taking times for same number of cycles.
From those numbers, sqrtf seems 4x better.

I'm not able find proper reason why?
Not able to find proper explanations about how actually this instruction on internet.

Some info or direction on this would be really useful.

答:
If you look at the note attached to the table entries for the FSQRT instruction in the Cortex-A57 optimization guide, it says that the "FP divide and square root operations are performed using an iterative algorithm".

That means that depending on the input to the instruction, the latency will vary. That is the meaning of the "7-17" and "7-32" latency numbers in the table. Depending on the input the single-precision FSQRT can take between 7 and 17 cycles to complete whereas the double-precision variant can take between 7 and 32 cycles.

So if a particular single-precision computation happens to take 7 cycles but a double precision computation takes, say, 28 cycles you have a 4x disparity.

Title: Performance of sqrt function on AArch64

Body:
I'm taking the performance of sqrt function on AArch64 for academic reasons.
Code for Single float sqrtf function:

fsqrt s0, s0
ret

Code for Double float sqrt function:

fsqrt d0, d0
ret

I'm referring to theoretical latencies for FSQRT from here:
http://infocenter.arm.com/help/topic/com.arm.doc.uan0015b/Cortex_A57_Software_Optimization_Guide_external.pdf

Single sqrt seems 2x better than double.

But, while profiling I'm getting these numbers:

326 ms  sqrt
 82 ms  sqrtf

I'm taking times for same number of cycles.
From those numbers, sqrtf seems 4x better.

I'm not able find proper reason why?
Not able to find proper explanations about how actually this instruction on internet.

Some info or direction on this would be really useful.