问:
How to use multiline flag in python regex?
I want to transform chunks of text into a database of single line entries database with regex. But I don't know why the regex group isn't recognized.
Maybe because the multiline flag isn't properly set.
I am a beginner at python.

```<code>import re
with open("a-j-0101.txt", encoding="cp1252") as f:
    start=1
    ecx=r"(?P<entrcnt>[0-9]{1,3}) célébrités ou évènements"
    ec1=""
    nmx=r"(?P<ename>.+)\r\nAfficher le.*"
    nm1=""
    for line in f:
        if start == 1:
            out = open('AST0101.txt' + ".txt", "w", encoding="cp1252") #utf8 cp1252
            ec1 = re.search(ecx,line)
            out.write(ec1.group("entrcnt"))
            start=0
        out.write(r"\r\n")
        nm1 = re.search(nmx,line, re.M)
        out.write(str(nm1.group("ename")).rstrip('\r\n'))
    out.close()
</code>```

But I get the error:

```<code>File "C:\work-python\transform-asth-b.py", line 16, in <module>
  out.write(str(nm1.group("ename")).rstrip('\r\n'))

builtins.AttributeError: 'NoneType' object has no attribute 'group'
</code>```

here is the input:

```<code>210 célébrités ou évènements ont été trouvés pour la date du 1er janvier.
Création de l'euro
Afficher le...
...
...
...
</code>```

expected output:

```<code>210
Création de l'euro ;...
... ;...
... ;...
</code>```

EDIT: I try to change nmx to match \n or \r\n but no result:

```<code>nmx=r"(?P<ename>.+)(\n|\r\n)Afficher le"
</code>```

best regards

答:
If you are reading a single line at a time, there is no way for a regex to match on a previous line you have read and then forgotten.

If you read a group of lines, you can apply a regex to the collection of lines, and the multiline flag will do something useful. But your current code should probably simply search for r'^Afficher le\.\.\.' and use the state machine (start == 0 or start == 1) to do this in the right context.

Body:
I want to transform chunks of text into a database of single line entries database with regex. But I don't know why the regex group isn't recognized.
Maybe because the multiline flag isn't properly set.
I am a beginner at python.

import re
with open("a-j-0101.txt", encoding="cp1252") as f:
    start=1
    ecx=r"(?P<entrcnt>[0-9]{1,3}) célébrités ou évènements"
    ec1=""
    nmx=r"(?P<ename>.+)\r\nAfficher le.*"
    nm1=""
    for line in f:
        if start == 1:
            out = open('AST0101.txt' + ".txt", "w", encoding="cp1252") #utf8 cp1252
            ec1 = re.search(ecx,line)
            out.write(ec1.group("entrcnt"))
            start=0
        out.write(r"\r\n")
        nm1 = re.search(nmx,line, re.M)
        out.write(str(nm1.group("ename")).rstrip('\r\n'))
    out.close()

But I get the error:

File "C:\work-python\transform-asth-b.py", line 16, in <module>
  out.write(str(nm1.group("ename")).rstrip('\r\n'))

builtins.AttributeError: 'NoneType' object has no attribute 'group'

here is the input:

210 célébrités ou évènements ont été trouvés pour la date du 1er janvier.
Création de l'euro
Afficher le...
...
...
...

expected output:

210
Création de l'euro ;...
... ;...
... ;...

EDIT: I try to change nmx to match \n or \r\n but no result:

nmx=r"(?P<ename>.+)(\n|\r\n)Afficher le"

best regards


来源: stackexchange

问:
Curve fit in python using scipy.optimize.curve_fit
I am trying to curve fit my data with scipy.optimize.curve_fit. For some reason it doesn't like my equation. If I plot the equation using plausible numbers it looks right. So I trust my equation. If I try to fit to a simpler equation, it works, so I trust my code in general. Any advice as to why it doesn't work? The specific error return is "Residuals are not finite in the initial point." Changing p0 to anything reasonable is also unhelpful</p>

```<code>import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np

Y=np.array([0.00001,1.421828697,2.553970883,3.340262844,3.931459808,
4.640896164,5.084293887,5.379892368,5.557251457,5.705050698,
5.823290091,5.911969636,5.971089332,6.059768876,6.118888573,6.178008269,
6.266687814])

X=np.array([0,2500,5000,7500,10000,15000,20000,25000,
30000,35000,40000,45000,50000,55000,60000,65000,70000])

plt.plot(X,Y,'g^')

def func(X,J,g):

    u=6.720*10**-5
    k=1.380*(10**-16)
    T=2
    N=1
    x=g*J*u*(X)/(k*T)
    return N*g*J*(((2*J+1)/(2*J))*(1/(np.tanh((2*J+1)*x/(2*J))))-(1/(2*J))*
    (1/(np.tanh(x/(2*J)))))

plt.figure(1)
popt, pcov = curve_fit(func, X,Y,p0=[3.5,2],bounds=([0.25,0.001],[10,4]))
plt.plot(X, func(X, *popt), 'r--', label='fit-with-bounds')

print(" J is %s " %(popt[0]),"\n","g is %s" %(popt[1]))
</code>```

答: You include an X value of exactly zero, causing divide-by-zero errors. If I replace the value of zero with 0.01 your code works in my tests.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to curve fit my data with scipy.optimize.curve_fit. For some reason it doesn't like my equation. If I plot the equation using plausible numbers it looks right. So I trust my equation. If I try to fit to a simpler equation, it works, so I trust my code in general. Any advice as to why it doesn't work? The specific error return is "Residuals are not finite in the initial point." Changing p0 to anything reasonable is also unhelpful

import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np

Y=np.array([0.00001,1.421828697,2.553970883,3.340262844,3.931459808,
4.640896164,5.084293887,5.379892368,5.557251457,5.705050698,
5.823290091,5.911969636,5.971089332,6.059768876,6.118888573,6.178008269,
6.266687814])

X=np.array([0,2500,5000,7500,10000,15000,20000,25000,
30000,35000,40000,45000,50000,55000,60000,65000,70000])

plt.plot(X,Y,'g^')

def func(X,J,g):

    u=6.720*10**-5
    k=1.380*(10**-16)
    T=2
    N=1
    x=g*J*u*(X)/(k*T)
    return N*g*J*(((2*J+1)/(2*J))*(1/(np.tanh((2*J+1)*x/(2*J))))-(1/(2*J))*
    (1/(np.tanh(x/(2*J)))))

plt.figure(1)
popt, pcov = curve_fit(func, X,Y,p0=[3.5,2],bounds=([0.25,0.001],[10,4]))
plt.plot(X, func(X, *popt), 'r--', label='fit-with-bounds')

print(" J is %s " %(popt[0]),"\n","g is %s" %(popt[1]))


问:
magento escape string for javascript
Is there a helper function that will properly escape a string to be rendered as a single quote quoted JavaScript string literal?

I know of jsQuoteEscape but it only handles quotes and does not treat \n & \r  etc.

so if my string is 'line1\nlineb' (i.e. two lines with a newline between them)

and I use

```<code>var jsvar='<?php echo $this->helper('myextension')->jsQuoteEscape($mystring); ?>';
</code>```

I will get in the rendered content

```<code>    var jsvar='line1
line2';
</code>```

which is a syntax error.

Thanks,
Eyal

答:
Yes

```<code>$string = 'Hello
There';
var_dump( Mage::helper('core')->jsonEncode($string) );
var_dump( json_encode($string) );
</code>```

I've never been clear if this encoding a non-object string datatypes as a javascript string is a side-effect of the JSON encoding, or if it's true, according to <s>Hoyle</s> Crockford JSON, so I always like to wrap my strings in an object when passing them around

```<code>$o = new stdClass();
$o->param = 'This is my
Param';
$json = json_encode($o);
echo 'var data = ' . $json . ';' . "\n";
echo 'var jsdata = data.param';
</code>```

This is how you'd handle this with javascript.  There's no method that's build specifically for this.  If you're interested in seeing the helper methods you do have available from a block, checkout the methods in

```<code>app/code/core/Mage/Core/Block/Abstract.php
app/code/core/Mage/Core/Block/Template.php
</code>```

and if you're dealing with a template that's part of a block higher up the chain, get its class and then check its definition

```<code>var_dump get_class($this);
</code>```

ContentLicense: CC BY-SA 2.5

Title: magento escape string for javascript

Body:
Is there a helper function that will properly escape a string to be rendered as a single quote quoted JavaScript string literal?

I know of jsQuoteEscape but it only handles quotes and does not treat \n & \r  etc.

so if my string is 'line1\nlineb' (i.e. two lines with a newline between them)

and I use

var jsvar='<?php echo $this->helper('myextension')->jsQuoteEscape($mystring); ?>';

I will get in the rendered content

    var jsvar='line1
line2';

which is a syntax error.

Thanks,
Eyal

Body:
Yes

$string = 'Hello
There';
var_dump( Mage::helper('core')->jsonEncode($string) );
var_dump( json_encode($string) );

I've never been clear if this encoding a non-object string datatypes as a javascript string is a side-effect of the JSON encoding, or if it's true, according to <s>Hoyle</s> Crockford JSON, so I always like to wrap my strings in an object when passing them around

$o = new stdClass();
$o->param = 'This is my
Param';
$json = json_encode($o);
echo 'var data = ' . $json . ';' . "\n";
echo 'var jsdata = data.param';

This is how you'd handle this with javascript.  There's no method that's build specifically for this.  If you're interested in seeing the helper methods you do have available from a block, checkout the methods in

app/code/core/Mage/Core/Block/Abstract.php
app/code/core/Mage/Core/Block/Template.php

and if you're dealing with a template that's part of a block higher up the chain, get its class and then check its definition

var_dump get_class($this);


问:
How to use Gradle in Unity
Since I want to add Firebase to my Android Game I want to include Google Auth. But I have the following Problem. I need to add some Code to the build.gradle File but I cant find it in my Unity Project.

Here is the manual I found from Firebase : https://firebase.google.com/docs/auth/android/google-signin

I searched on all my Drives for build.gradle but found nothing.
Can you tell me where I find it or what do I have to do to implement the Code from the Link?

答:
To use Gradle in Unity.

1.Go to <UnityInstallationDirecory>\Editor\Data\PlaybackEngines\AndroidPlayer\Tools\GradleTemplates, then copy mainTemplate.gradle file to your <ProjectName>Assets\Plugins\Android folder.

2.You can then modify mainTemplate.gradle to be whatever you want it to be. Now, to make sure the build uses the gradle file, change the Build System to "Gradle (New)".

Title: How to use Gradle in Unity


问:
FPDF Table cell wrap
I Created a table with FPDF and I want to wrap the word in the cells(table).
this is my code .

```<code>$w = array(7, 150, 40);
$pdf->Cell($w[0], 6, $count, 'LR');
$pdf->Cell($w[1], 6, $column_heading, 'LR');
$pdf->Cell($w[2], 6, $rekey, 'LR', 0, 'R');

$pdf->Ln();
$pdf->Cell(array_sum($w), 0, '', 'T');
$count++;
</code>```

This is out put of the code how can I break the text in cells.

答:
FPDF prints the cells and the text separately (means that it's like 2 layers)

from manual: http://www.fpdf.org/

```<code>Cell(float w [, float h [, string txt [, mixed border [, int ln [, string align [, boolean fill [, mixed link]]]]]]])
</code>```

Suggested Approach:

context length should be computed code-wise, if the content is greater than the allotted cell width then it should be divided and transferred to a new line.

At the same time cell height h should be adjusted (increase in height).

As I remember (fpdf experts can correct me) automatic adjustment of cells based on content is not yet implemented as a feature of the library.

Correction: there is http://www.fpdf.org/en/doc/multicell.htm

Title: FPDF Table cell wrap

Body:
I Created a table with FPDF and I want to wrap the word in the cells(table).
this is my code .

$w = array(7, 150, 40);
$pdf->Cell($w[0], 6, $count, 'LR');
$pdf->Cell($w[1], 6, $column_heading, 'LR');
$pdf->Cell($w[2], 6, $rekey, 'LR', 0, 'R');

$pdf->Ln();
$pdf->Cell(array_sum($w), 0, '', 'T');
$count++;

This is out put of the code how can I break the text in cells.

Body:
FPDF prints the cells and the text separately (means that it's like 2 layers)

from manual: http://www.fpdf.org/

Cell(float w [, float h [, string txt [, mixed border [, int ln [, string align [, boolean fill [, mixed link]]]]]]])

Suggested Approach:

context length should be computed code-wise, if the content is greater than the allotted cell width then it should be divided and transferred to a new line.

At the same time cell height h should be adjusted (increase in height).

As I remember (fpdf experts can correct me) automatic adjustment of cells based on content is not yet implemented as a feature of the library.

Correction: there is http://www.fpdf.org/en/doc/multicell.htm


问:
simple Clock in python
I wanted to program a simple clock in python:

```<code>class Clock:
    def __init__(self):
        self._hours = 0
        self._minutes = 0

    def gethours(self):
        return self._hours

    def getminutes(self):
        return self._minutes

    def sethours(self, hours):
        self._hours = hours

    def setminutes(self,minutes):
        if self._minutes > 60:
            self._hours = self._hours + 1
            self._minutes = 1
        else:
            self._minutes = minutes

    def tic(self):
        if self._minutes > 58:
            self._hours = self._hours + 1
            self._minutes = 1
        else:
            self._minutes = self._minutes + 1

    minutes = property(getminutes, setminutes)
    hours = property(gethours, sethours)
</code>```

But when I now wanted to check it with the following code I get an AssertionError at assert(c.hours == i and c.minutes == j)

```<code>c = Clock()

assert(c.minutes == 0 and c.hours == 0)

for i in range(24):
    assert(c.hours == i)
    for j in range(60):
        assert(c.hours == i and c.minutes == j)
        c.tic()

assert(c.minutes == 0 and c.hours == 0)
</code>```

答:
Here is a fixed rewriting, using the same test.
The setters take care of setting correctly the values for hours and minutes (though hours' setter does not manage correctly adding more than one day, but this is easy to add based on the same model as for minutes).

Then tic() is only a shortcut for adding one minute.

Comment out the print statement to remove all hours:minutes.

Note: I've turned Clock to a "new style" class object, that allow to use property decorators and makes everything more readable (this not necessary for python3, but necessary to let the same code work also in python2).

```<code>class Clock(object):
    def __init__(self):
        self._hours = 0
        self._minutes = 0

    @property
    def hours(self):
        return self._hours

    @property
    def minutes(self):
        return self._minutes

    @minutes.setter
    def minutes(self, value):
        if value >= 60:
            # Take care, if one adds more than one hour, to
            # take the extra hours into account too:
            self.hours += value // 60
        self._minutes = value % 60

    @hours.setter
    def hours(self, value):
        self._hours = value % 24

    def tic(self):
        self.minutes += 1

c = Clock()

assert(c.minutes == 0 and c.hours == 0)

for i in range(24):
    assert(c.hours == i)
    for j in range(60):
        assert(c.hours == i and c.minutes == j)
        c.tic()
        print('{}:{}'.format(c.hours, c.minutes))

assert(c.minutes == 0 and c.hours == 0)
</code>```

Excerpt and end of output:

```<code>12:57
12:58
12:59
13:0
13:1
13:2
13:3
.
.
.
23:46
23:47
23:48
23:49
23:50
23:51
23:52
23:53
23:54
23:55
23:56
23:57
23:58
23:59
0:0
</code>```

Title: simple Clock in python

Body:
I wanted to program a simple clock in python:

class Clock:
    def __init__(self):
        self._hours = 0
        self._minutes = 0

    def gethours(self):
        return self._hours

    def getminutes(self):
        return self._minutes

    def sethours(self, hours):
        self._hours = hours

    def setminutes(self,minutes):
        if self._minutes > 60:
            self._hours = self._hours + 1
            self._minutes = 1
        else:
            self._minutes = minutes

    def tic(self):
        if self._minutes > 58:
            self._hours = self._hours + 1
            self._minutes = 1
        else:
            self._minutes = self._minutes + 1

    minutes = property(getminutes, setminutes)
    hours = property(gethours, sethours)

But when I now wanted to check it with the following code I get an AssertionError at assert(c.hours == i and c.minutes == j)

c = Clock()

assert(c.minutes == 0 and c.hours == 0)

for i in range(24):
    assert(c.hours == i)
    for j in range(60):
        assert(c.hours == i and c.minutes == j)
        c.tic()

assert(c.minutes == 0 and c.hours == 0)

Body:
Here is a fixed rewriting, using the same test.
The setters take care of setting correctly the values for hours and minutes (though hours' setter does not manage correctly adding more than one day, but this is easy to add based on the same model as for minutes).

Then tic() is only a shortcut for adding one minute.

Comment out the print statement to remove all hours:minutes.

Note: I've turned Clock to a "new style" class object, that allow to use property decorators and makes everything more readable (this not necessary for python3, but necessary to let the same code work also in python2).

class Clock(object):
    def __init__(self):
        self._hours = 0
        self._minutes = 0

    @property
    def hours(self):
        return self._hours

    @property
    def minutes(self):
        return self._minutes

    @minutes.setter
    def minutes(self, value):
        if value >= 60:
            # Take care, if one adds more than one hour, to
            # take the extra hours into account too:
            self.hours += value // 60
        self._minutes = value % 60

    @hours.setter
    def hours(self, value):
        self._hours = value % 24

    def tic(self):
        self.minutes += 1

c = Clock()

assert(c.minutes == 0 and c.hours == 0)

for i in range(24):
    assert(c.hours == i)
    for j in range(60):
        assert(c.hours == i and c.minutes == j)
        c.tic()
        print('{}:{}'.format(c.hours, c.minutes))

assert(c.minutes == 0 and c.hours == 0)

Excerpt and end of output:

12:57
12:58
12:59
13:0
13:1
13:2
13:3
.
.
.
23:46
23:47
23:48
23:49
23:50
23:51
23:52
23:53
23:54
23:55
23:56
23:57
23:58
23:59
0:0


问:
Openldap support for sha256 and sha512 password format
How to configure Openldap server for {SHA256} and {SHA512} password format ? is this functionality available in latest Openldap or still we have to add external module( slapd-sha2.so)? </p>

答:
There is no will to include SHA2 support in base OpenLDAP installation.

"At present there is no need to change anything in the core since SHA-2 support can be dynamically loaded. Don't fix what isn't broken."

Howard Chu
CTO, Symas Corp.
Director, Highland Sun
Chief Architect, OpenLDAP

Ref:http://www.openldap.org/lists/openldap-bugs/201205/msg00055.html


问:
Changing this Python program to have function def()
The following Python program flips a coin several times, then reports the longest series of heads and tails. I am trying to convert this program into a program that uses functions so it uses basically less code. I am very new to programming and my teacher requested this of us, but I have no idea how to do it. I know I'm supposed to have the function accept 2 parameters: a string or list, and a character to search for. The function should return, as the value of the function, an integer which is the longest sequence of that character in that string. The function shouldn't accept input or output from the user.

```<code>import random

print("This program flips a coin several times, \nthen reports the longest
series of heads and tails")

cointoss = int(input("Number of times to flip the coin: "))

varlist = []
i = 0
varstring = ' '

 while i < cointoss:
    r = random.choice('HT')

    varlist.append(r)
    varstring = varstring + r
    i += 1

print(varstring)

print(varlist)

print("There's this many heads: ",varstring.count("H"))
print("There's this many tails: ",varstring.count("T"))
print("Processing input...")

i = 0
longest_h = 0
longest_t = 0
inarow = 0
prevIn = 0

while i < cointoss:
    print(varlist[i])
    if varlist[i] == 'H':
        prevIn += 1
        if prevIn > longest_h:
            longest_h = prevIn
        print("",longest_h,"")

        inarow = 0

    if varlist[i] == 'T':
        inarow += 1
        if inarow > longest_t:
            longest_t = inarow
        print("",longest_t,"")

        prevIn = 0

    i += 1
print ("The longest series of heads is: ",longest_h)

print ("The longest series of tails is: ",longest_t)
</code>```

If this is asking too much, any explanatory help would be really nice instead. All I've got so far is:

```<code>def flip (a, b):
    flipValue = random.randint
</code>```

but it's barely anything.

答:
First, you need a function that flips a coin x times. This would be one possible implementation, favoring random.choice over random.randint:

```<code>def flip(x):
  result = []
  for _ in range(x):
    result.append(random.choice(("h", "t")))
  return result
</code>```

Of course, you could also pass from what exactly we are supposed to take a choice as a parameter.

Next, you need a function that finds the longest sequence of some value in some list:

```<code>def longest_series(some_value, some_list):
  current, longest = 0, 0
  for r in some_list:
    if r == some_value:
      current += 1
      longest = max(current, longest)
    else:
      current = 0
  return longest
</code>```

And now you can call these in the right order:

```<code># initialize the random number generator, so we get the same result
random.seed(5)

# toss a coin a hundred times
series = flip(100)

# count heads/tails
headflips = longest_series('h', series)
tailflips = longest_series('t', series)

# print the results
print("The longest series of heads is: " + str(headflips))
print("The longest series of tails is: " + str(tailflips))
</code>```

Output:

```<code>>> The longest series of heads is: 8
>> The longest series of heads is: 5
</code>```

edit: removed the flip implementation with yield, it made the code weird.

Body:
The following Python program flips a coin several times, then reports the longest series of heads and tails. I am trying to convert this program into a program that uses functions so it uses basically less code. I am very new to programming and my teacher requested this of us, but I have no idea how to do it. I know I'm supposed to have the function accept 2 parameters: a string or list, and a character to search for. The function should return, as the value of the function, an integer which is the longest sequence of that character in that string. The function shouldn't accept input or output from the user.

import random

print("This program flips a coin several times, \nthen reports the longest
series of heads and tails")

cointoss = int(input("Number of times to flip the coin: "))

varlist = []
i = 0
varstring = ' '

 while i < cointoss:
    r = random.choice('HT')

    varlist.append(r)
    varstring = varstring + r
    i += 1

print(varstring)

print(varlist)

print("There's this many heads: ",varstring.count("H"))
print("There's this many tails: ",varstring.count("T"))
print("Processing input...")

i = 0
longest_h = 0
longest_t = 0
inarow = 0
prevIn = 0

while i < cointoss:
    print(varlist[i])
    if varlist[i] == 'H':
        prevIn += 1
        if prevIn > longest_h:
            longest_h = prevIn
        print("",longest_h,"")

        inarow = 0

    if varlist[i] == 'T':
        inarow += 1
        if inarow > longest_t:
            longest_t = inarow
        print("",longest_t,"")

        prevIn = 0

    i += 1
print ("The longest series of heads is: ",longest_h)

print ("The longest series of tails is: ",longest_t)

If this is asking too much, any explanatory help would be really nice instead. All I've got so far is:

def flip (a, b):
    flipValue = random.randint

but it's barely anything.

Body:
First, you need a function that flips a coin x times. This would be one possible implementation, favoring random.choice over random.randint:

def flip(x):
  result = []
  for _ in range(x):
    result.append(random.choice(("h", "t")))
  return result

Of course, you could also pass from what exactly we are supposed to take a choice as a parameter.

Next, you need a function that finds the longest sequence of some value in some list:

def longest_series(some_value, some_list):
  current, longest = 0, 0
  for r in some_list:
    if r == some_value:
      current += 1
      longest = max(current, longest)
    else:
      current = 0
  return longest

And now you can call these in the right order:

# initialize the random number generator, so we get the same result
random.seed(5)

# toss a coin a hundred times
series = flip(100)

# count heads/tails
headflips = longest_series('h', series)
tailflips = longest_series('t', series)

# print the results
print("The longest series of heads is: " + str(headflips))
print("The longest series of tails is: " + str(tailflips))

Output:

>> The longest series of heads is: 8
>> The longest series of heads is: 5

edit: removed the flip implementation with yield, it made the code weird.


问:
MVC Close Modal when DataTable Row is clicked
I am rather new Asp.net mvc. I am trying to have a dropdownlist selected based on a large list of values. When the dropdown is clicked a modal is brought up with a jquery DataTable in side. I am trying to implement when a row from the DataTable is clicked the modal is closed and the two values(data: "Name" and data: "Company") from the row are passed back to parent window so i can populate the dropdownlist. any help would be well appreciated.

Dropdown:

```<code>@Html.DropDownListFor(model => model.Company,
Enumerable.Empty<SelectListItem>(),
new {@id="drop" })
</code>```

modal:

```<code><div id='myModal' class='modal'>
    <div class="modal-dialog">
        <div class="modal-content">
            <div id='myModalContent'></div>
        </div>
    </div>
</div>
</code>```

js to bring up modal:

```<code><script>
    var TeamDetailPostBackURL = '/Home/Details';
    $(function () {
        $("#drop").click(function () {
            debugger;
            $("#drop").blur();
            var $buttonClicked = $(this);
            var id = $buttonClicked.attr('data-id');
            var options = { "backdrop": "static", keyboard: true };
            $.ajax({
                type: "GET",
                url: TeamDetailPostBackURL,
                contentType: "application/json; charset=utf-8",
                data: { "Id": id },
                datatype: "json",
                success: function (data) {
                    debugger;
                    $('#myModalContent').html(data);
                    $('#myModal').modal(options);
                    $('#myModal').modal('show');

                },
                error: function () {
                    alert("Dynamic content load failed.");
                }
            });
        });
    });
</script>
</code>```

partial view(when a row in #t1 in clicked i would like to populate the dropdown "Drop"):

```<code>@model MvcApplication1.Models.About
@{
    ViewBag.Title = "Abouts";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h4 class="modal-title" id="myModalLabel">FriendsInfo</h4>
</div>
<div>
    <table id="exampless" class="display" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Company</th>
            </tr>
        </thead>
    </table>
</div>
@section Scripts{
    <script src="~/Scripts/jquery.dataTables.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    @Scripts.Render("~/Content/themes/base/css")
    <script>
        $(document).ready(function () {
            $('#exampless').DataTable({
                "ajax": {
                    "url": "/home/loaddata",
                    "type": "GET",
                    "datatype": "json"
                },
                "columns": [
                        { "data": "Name", "autoWidth": true },
                        { "data": "Company", "autoWidth": true }
                ]
            });
        });
    </script>
    }
</code>```

Update: I was able to get the values from the DataTable with this javascript:

```<code><script>
        $('#exampless').on('click', 'tr', function () {
            var ddValue = $('td', this).eq(0).text();
            var ddText = $('td', this).eq(1).text();
            $("#closeMod").click()
        });
</script>
</code>```

I just need help with getting var ddValue and var ddText from the partial view back to the parent view.

答:
You should just be able to assign it as the Modal is not a separate window, once you load it it becomes part of the View.

Something like

```<code>$("#drop").val(ddValue);
</code>```

Body:
I am rather new Asp.net mvc. I am trying to have a dropdownlist selected based on a large list of values. When the dropdown is clicked a modal is brought up with a jquery DataTable in side. I am trying to implement when a row from the DataTable is clicked the modal is closed and the two values(data: "Name" and data: "Company") from the row are passed back to parent window so i can populate the dropdownlist. any help would be well appreciated.

Dropdown:

@Html.DropDownListFor(model => model.Company,
Enumerable.Empty<SelectListItem>(),
new {@id="drop" })

modal:

js to bring up modal:

partial view(when a row in #t1 in clicked i would like to populate the dropdown "Drop"):

@model MvcApplication1.Models.About
@{
    ViewBag.Title = "Abouts";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

FriendsInfo

                Name
                Company

@section Scripts{

    @Scripts.Render("~/Content/themes/base/css")

    }

Update: I was able to get the values from the DataTable with this javascript:

I just need help with getting var ddValue and var ddText from the partial view back to the parent view.

Body:
You should just be able to assign it as the Modal is not a separate window, once you load it it becomes part of the View.

Something like

$("#drop").val(ddValue);


问:
Best way to serve file to html page once in flask (python)
for a assignment we need to make a website with flask or django as backend. I've been working on it and am almost finished but am running into a problem that I cannot really seem to tackle. I have users submit photo's to the website via either a url or upload. I will do some stuff to the images and than want to display the image again. But after the users closes the page where is image is being show I'd like for the image to be automatically deleted from my server.

I was thinking about making a temporary file, but from what I gather these only get deleted once the file is closed. But since I have to return the template with flask first I cannot really close it then right? What would be the best way to approach this?

答:
After the user receives the file, you can safely delete it and it'll still be in their browser. Since you can't remove it after returning from the function, you must first load it into memory with a variable, then remove the file, and then return the image you have loaded. This example does just that:</p>

```<code>from flask import Flask, send_file
import io
import os
app = Flask(__name__)

@app.route("/image-route.jpg")  # Change this to match your route
def send_my_image():
    image_in_memory = None  # Create variable so it has the correct scope
    # Open file and load it into a BytesIO object which behaves just as if it was a file
    with open('my-file-location.jpg', 'rb') as f:
        image_in_memory = io.BytesIO(f.read())
    # Since we have the image in memory, we can safely remove it
    os.remove('my-file-location.jpg')
    # Finally, return our BytesIO object as if it was a file
    return send_file(image_in_memory, attachment_filename='my-file.jpg')

app.run()
</code>```

Body:
After the user receives the file, you can safely delete it and it'll still be in their browser. Since you can't remove it after returning from the function, you must first load it into memory with a variable, then remove the file, and then return the image you have loaded. This example does just that:

from flask import Flask, send_file
import io
import os
app = Flask(__name__)

@app.route("/image-route.jpg")  # Change this to match your route
def send_my_image():
    image_in_memory = None  # Create variable so it has the correct scope
    # Open file and load it into a BytesIO object which behaves just as if it was a file
    with open('my-file-location.jpg', 'rb') as f:
        image_in_memory = io.BytesIO(f.read())
    # Since we have the image in memory, we can safely remove it
    os.remove('my-file-location.jpg')
    # Finally, return our BytesIO object as if it was a file
    return send_file(image_in_memory, attachment_filename='my-file.jpg')

app.run()


问:
How to collect data from parallel running tasks using GPars and Groovy
GPars documentation says we should not do:

```<code>def thumbnails = []
images.eachParallel {thumbnails << it.thumbnail} // Concurrently accessing a not-thread-safe collection of thumbnails? Don't do this!
</code>```

source: http://www.gpars.org/webapp/guide/index.html#_avoid_side_effects_in_functions

I want to write a similar kind of code, where parallel executing methods need to write to a common List. How can I do that?

答:
The code you have shown is not thread-safe - multiple different threads will try adding elements to the list in parallel. What may happen is two (or more) threads try to add an element at the same index, so the last thread will actually replace what the previous one did.

Instead try following:

```<code>def thumbnails = images.collectParallel {it.thumbnail}
</code>```

or

```<code>def thumbnails = images.parallel.map {it.thumbnail}
</code>```

It's thread-safe and you get a list of all thumbnails as a result.

Body:
GPars documentation says we should not do:

def thumbnails = []
images.eachParallel {thumbnails << it.thumbnail} // Concurrently accessing a not-thread-safe collection of thumbnails? Don't do this!

source: http://www.gpars.org/webapp/guide/index.html#_avoid_side_effects_in_functions

I want to write a similar kind of code, where parallel executing methods need to write to a common List. How can I do that?

Body:
The code you have shown is not thread-safe - multiple different threads will try adding elements to the list in parallel. What may happen is two (or more) threads try to add an element at the same index, so the last thread will actually replace what the previous one did.

Instead try following:

def thumbnails = images.collectParallel {it.thumbnail}

or

def thumbnails = images.parallel.map {it.thumbnail}

It's thread-safe and you get a list of all thumbnails as a result.


问:
Couldn't hear incoming voice in recorded calls in android 7?
I am developing an Android app for recording calls.
This is my code snippet.

```<code>    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    recorder.setOutputFile(file_path);
</code>```

This is working perfectly for devices below android 7, but when I use Android 7 mobile devices I can hear only outgoing voice but cannot hear incoming voice.

Can anyone help me in fixing it?

答:
this code works like a charm for Android 7 built with API 25,</p>

```<code>recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setAudioSamplingRate(8000);
recorder.setAudioEncodingBitRate(12200);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am developing an Android app for recording calls.
This is my code snippet.

    recorder = new MediaRecorder();
    recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
    recorder.setOutputFile(file_path);

This is working perfectly for devices below android 7, but when I use Android 7 mobile devices I can hear only outgoing voice but cannot hear incoming voice.

Can anyone help me in fixing it?

Body:
this code works like a charm for Android 7 built with API 25,

recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setAudioSamplingRate(8000);
recorder.setAudioEncodingBitRate(12200);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);


问:
Add animation delay to li automatically
I have a slideshow with CSS3 which have animation-delay in each child,
but this is not dynamic because for each tag I should add nth-child ,

Is there any way to add animation-delay automatically to li tags?

this is CSS code:

```<code>.cb-slideshow li:nth-child(2) span {
  -webkit-animation-delay: 6s;
  -moz-animation-delay: 6s;
  -o-animation-delay: 6s;
  -ms-animation-delay: 6s;
  animation-delay: 6s;
}

.cb-slideshow li:nth-child(3) span {
  -webkit-animation-delay: 12s;
  -moz-animation-delay: 12s;
  -o-animation-delay: 12s;
  -ms-animation-delay: 12s;
  animation-delay: 12s;
}

.cb-slideshow li:nth-child(4) span {
  -webkit-animation-delay: 18s;
  -moz-animation-delay: 18s;
  -o-animation-delay: 18s;
  -ms-animation-delay: 18s;
  animation-delay: 18s;
}

.cb-slideshow li:nth-child(5) span {
  -webkit-animation-delay: 24s;
  -moz-animation-delay: 24s;
  -o-animation-delay: 24s;
  -ms-animation-delay: 24s;
  animation-delay: 24s;
}

.cb-slideshow li:nth-child(6) span {
  -webkit-animation-delay: 30s;
  -moz-animation-delay: 30s;
  -o-animation-delay: 30s;
  -ms-animation-delay: 30s;
  animation-delay: 30s;
}
</code>```

I want to change this code to add 6s delay to each tags.

答:
You could use PHP to dynamically echo each part of the style, or intergrate it right into the css.
For example

```<code>.button:hover {
    border: 10px solid;
    transition: <?php echo $lot ?>;
}
</code>```

Where $lot is the animation time.

I dont know how to get the nth-child(N) in php, but there is undoubtably a way.
Sorry if this wasn't very useful, just wanted to say that php would be a good way to do it.

Title: Add animation delay to li automatically

Body:
I have a slideshow with CSS3 which have animation-delay in each child,
but this is not dynamic because for each tag I should add nth-child ,

Is there any way to add animation-delay automatically to li tags?

this is CSS code:

.cb-slideshow li:nth-child(2) span {
  -webkit-animation-delay: 6s;
  -moz-animation-delay: 6s;
  -o-animation-delay: 6s;
  -ms-animation-delay: 6s;
  animation-delay: 6s;
}

.cb-slideshow li:nth-child(3) span {
  -webkit-animation-delay: 12s;
  -moz-animation-delay: 12s;
  -o-animation-delay: 12s;
  -ms-animation-delay: 12s;
  animation-delay: 12s;
}

.cb-slideshow li:nth-child(4) span {
  -webkit-animation-delay: 18s;
  -moz-animation-delay: 18s;
  -o-animation-delay: 18s;
  -ms-animation-delay: 18s;
  animation-delay: 18s;
}

.cb-slideshow li:nth-child(5) span {
  -webkit-animation-delay: 24s;
  -moz-animation-delay: 24s;
  -o-animation-delay: 24s;
  -ms-animation-delay: 24s;
  animation-delay: 24s;
}

.cb-slideshow li:nth-child(6) span {
  -webkit-animation-delay: 30s;
  -moz-animation-delay: 30s;
  -o-animation-delay: 30s;
  -ms-animation-delay: 30s;
  animation-delay: 30s;
}

I want to change this code to add 6s delay to each tags.

Body:
You could use PHP to dynamically echo each part of the style, or intergrate it right into the css.
For example

.button:hover {
    border: 10px solid;
    transition: <?php echo $lot ?>;
}

Where $lot is the animation time.

I dont know how to get the nth-child(N) in php, but there is undoubtably a way.
Sorry if this wasn't very useful, just wanted to say that php would be a good way to do it.


问:
how to prevent cpu usage from changing timing in labview?
I'm trying to write a code in which every 1 ms a number plused one , should be replaced the old number . (something  like a chronometer !  )  .

the problem is whenever the cpu usage increases because of some other programs running on the pc,  this 1 milliseconds  is also increased and timing in my program changes !

is there any way to prevent cpu load changes affecting timing in my program ?

答:
It sounds as though you are trying to generate an analogue output waveform with a digital-to-analogue converter card using software timing, where your software is responsible for determining what value should be output at any given time and updating the output accordingly.

This is OK for stationary or low-speed signals but you are trying to do it at 1 ms intervals, in other words to output 1000 samples per second or 1 ks/s. You cannot do this reliably on a desktop operating system - there are too many other processes going on which can use CPU time and block your program from running for many milliseconds (or even seconds, e.g. for network access).

Here are a few ways you could solve this:

Use buffered, hardware-clocked output if your analogue output device supports it. Instead of writing one sample at a time, you send the device a waveform or array of samples and it outputs them at regular intervals using a timing signal generated in hardware. Unfortunately, low-end DAQ devices often don't support hardware-clocked output.

Instead of expecting the loop that writes your samples to the AO to run every millisecond, read LabVIEW's Tick Count (ms) value in the loop and use that as an index to your array of samples: rather than trying to output every sample, your code will now say 'what time is it now, and therefore what should the output be?' That won't give you a perfect signal out but at least now it should keep the correct frequency rather than be 'slowed down' - instead you will see glitches imposed on the signal whenever the loop can't keep up. This is easy to test and maybe it will be adequate for your needs.

Use a real-time operating system instead of a desktop OS. In the case of LabVIEW this would mean using the Real-Time software module and either a National Instruments hardware device that supports RT, such as the CompactRIO series, or installing the RT OS on a dedicated PC if the hardware is compatible. This is not a cheap option, obviously (unless it's strictly for personal, home use). In any case you would need to have an RT-compatible driver for your output device.

Use your computer's sound output as the output device. LabVIEW has functions for buffered sound output and you should be able to get reliable results. You'll need to upsample your signal to one of the sound output's available sample rates, probably 44.1 ks/s. The drawbacks are that the output level is limited in range and is not calibrated, and will probably be AC-coupled so you can't output a DC or very low-frequency signal. However if the level is OK for what you want to connect it to, or you can add suitable signal conditioning, this could be a neat solution. If you need the output level to be calibrated you could simultaneously measure it with your DAQ card and scale the sound waveform you're outputting to keep it correct.


问:
C# Telerik Grid data binding not reloading
I want to bind data in telerik grid dynamically.
Initially I used below code.

```<code>protected void radGridItemList_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            var gridItemList = sender as RadGrid;
            var repoItemMaster = CreateIItemMasterRepository();
            var ItemList = repoItemMaster.GetAll();
            gridItemList.DataSource = ItemList;
}
</code>```

Now I want to reload gridItemList with filtered ItemNumbers (E.g select ItemNumber from ItemMaster where ItemNumber LIKE 'a%') and bind new data source to grid again.

I did something like this but It does not work.

```<code>private void LoadItemListByItemNumber(string ItemNumber)
        {
            var gridItemList = radcmbItemNumber.Items[0].FindControl("radGridItemList") as RadGrid;
            string whereCondition = "a.ItemNumber LIKE '"+ ItemNumber + "%'";

            var repoItemMaster = CreateIItemMasterRepository();
            List<ItemMaster> itemList = repoItemMaster.FindbyItemNumber(ItemNumber, whereCondition);
            gridItemList.DataSource = itemList;
        }
</code>```

Any suggestions?

答:
.aspx

```<code><div class="col-lg-8 qb-col">
                                                    <telerik:RadComboBox ID="radcmbItemNumber" runat="server"
                                                        MarkFirstMatch="True"
                                                        AllowCustomText="true"
                                                        OnClientDropDownOpening="radcmbItemNumberOnClientDropDownOpening"
                                                        OnClientKeyPressing="radcmbItemNumberOnKeyPress"
                                                        OnTextChanged="radcmbItemNumber_TextChanged"
                                                        Width="95%"
                                                        CssClass="qb-input-combo"
                                                        ExpandAnimation-Type="None">
                                                        <ItemTemplate>
                                                            <telerik:RadGrid ID="radGridItemList" runat="server" CssClass="GridStyle1"
                                                                AutoGenerateColumns="false" AllowPaging="true"
                                                                AllowSorting="true" AllowFilteringByColumn="true"
                                                                OnNeedDataSource="radGridItemList_NeedDataSource"
                                                                EnableLinqExpressions="false">
                                                                <GroupingSettings CaseSensitive="false" />
                                                                <PagerStyle Mode="NextPrevAndNumeric" />
                                                                <MasterTableView DataKeyNames="ItemNumber" ClientDataKeyNames="ItemNumber">
                                                                    <Columns>
                                                                        <telerik:GridBoundColumn UniqueName="ItemNumber" DataField="ItemNumber"
                                                                            HeaderText="Item Number" AutoPostBackOnFilter="true"
                                                                            FilterControlWidth="100px">
                                                                            <HeaderStyle Width="150px" />
                                                                        </telerik:GridBoundColumn>
                                                                        <telerik:GridBoundColumn UniqueName="RevisionNumber" DataField="RevisionNumber"
                                                                            HeaderText="Revision Number" AutoPostBackOnFilter="true"
                                                                            FilterControlWidth="100px">
                                                                            <HeaderStyle Width="150px" />
                                                                        </telerik:GridBoundColumn>
                                                                        <telerik:GridBoundColumn UniqueName="Description" DataField="Description"
                                                                            HeaderText="Description" AutoPostBackOnFilter="true"
                                                                            FilterControlWidth="100px">
                                                                            <HeaderStyle Width="150px" />
                                                                        </telerik:GridBoundColumn>

                                                                    </Columns>
                                                                </MasterTableView>
                                                                <ClientSettings>
                                                                    <ClientEvents OnRowClick="radGridItemListOnRowClicked" />
                                                                    <Scrolling AllowScroll="true" UseStaticHeaders="true" />
                                                                </ClientSettings>
                                                            </telerik:RadGrid>
                                                        </ItemTemplate>
                                                        <Items>
                                                            <telerik:RadComboBoxItem runat="server" Text=" "></telerik:RadComboBoxItem>
                                                        </Items>
                                                    </telerik:RadComboBox>
                                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                                                                                ControlToValidate="radcmbItemNumber" ErrorMessage="!"
                                                                                ForeColor="Red"
                                                                                SetFocusOnError="true" />
                                                </div>
</code>```

I used a combo and when it it clicked, I need to load search result in a grid for what is typed in the combo box.
Here is my .cs

```<code> protected void radcmbItemNumber_TextChanged(object sender, EventArgs e)
        {
            string textToSearch = radcmbItemNumber.Text.ToString();
            var gridItemList = radcmbItemNumber.Items[0].FindControl("radGridItemList") as RadGrid;
            if (!string.IsNullOrEmpty(textToSearch))
                gridItemList.MasterTableView.FilterExpression = "([ItemNumber] LIKE \'%" + textToSearch + "%\')";

            gridItemList.MasterTableView.Rebind();
}
</code>```

So this text change works perfectly but in my grid new search result is not reloaded until I go to second page. Hope this makes sense.Let me know if you need further info. Thanks

Body:
I want to bind data in telerik grid dynamically.
Initially I used below code.

protected void radGridItemList_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            var gridItemList = sender as RadGrid;
            var repoItemMaster = CreateIItemMasterRepository();
            var ItemList = repoItemMaster.GetAll();
            gridItemList.DataSource = ItemList;
}

Now I want to reload gridItemList with filtered ItemNumbers (E.g select ItemNumber from ItemMaster where ItemNumber LIKE 'a%') and bind new data source to grid again.

I did something like this but It does not work.

private void LoadItemListByItemNumber(string ItemNumber)
        {
            var gridItemList = radcmbItemNumber.Items[0].FindControl("radGridItemList") as RadGrid;
            string whereCondition = "a.ItemNumber LIKE '"+ ItemNumber + "%'";

            var repoItemMaster = CreateIItemMasterRepository();
            List<ItemMaster> itemList = repoItemMaster.FindbyItemNumber(ItemNumber, whereCondition);
            gridItemList.DataSource = itemList;
        }

Any suggestions?

Body:
.aspx

<div class="col-lg-8 qb-col">
                                                    <telerik:RadComboBox ID="radcmbItemNumber" runat="server"
                                                        MarkFirstMatch="True"
                                                        AllowCustomText="true"
                                                        OnClientDropDownOpening="radcmbItemNumberOnClientDropDownOpening"
                                                        OnClientKeyPressing="radcmbItemNumberOnKeyPress"
                                                        OnTextChanged="radcmbItemNumber_TextChanged"
                                                        Width="95%"
                                                        CssClass="qb-input-combo"
                                                        ExpandAnimation-Type="None">
                                                        <ItemTemplate>
                                                            <telerik:RadGrid ID="radGridItemList" runat="server" CssClass="GridStyle1"
                                                                AutoGenerateColumns="false" AllowPaging="true"
                                                                AllowSorting="true" AllowFilteringByColumn="true"
                                                                OnNeedDataSource="radGridItemList_NeedDataSource"
                                                                EnableLinqExpressions="false">
                                                                <GroupingSettings CaseSensitive="false" />
                                                                <PagerStyle Mode="NextPrevAndNumeric" />
                                                                <MasterTableView DataKeyNames="ItemNumber" ClientDataKeyNames="ItemNumber">
                                                                    <Columns>
                                                                        <telerik:GridBoundColumn UniqueName="ItemNumber" DataField="ItemNumber"
                                                                            HeaderText="Item Number" AutoPostBackOnFilter="true"
                                                                            FilterControlWidth="100px">
                                                                            <HeaderStyle Width="150px" />
                                                                        </telerik:GridBoundColumn>
                                                                        <telerik:GridBoundColumn UniqueName="RevisionNumber" DataField="RevisionNumber"
                                                                            HeaderText="Revision Number" AutoPostBackOnFilter="true"
                                                                            FilterControlWidth="100px">
                                                                            <HeaderStyle Width="150px" />
                                                                        </telerik:GridBoundColumn>
                                                                        <telerik:GridBoundColumn UniqueName="Description" DataField="Description"
                                                                            HeaderText="Description" AutoPostBackOnFilter="true"
                                                                            FilterControlWidth="100px">
                                                                            <HeaderStyle Width="150px" />
                                                                        </telerik:GridBoundColumn>

                                                                    </Columns>
                                                                </MasterTableView>
                                                                <ClientSettings>
                                                                    <ClientEvents OnRowClick="radGridItemListOnRowClicked" />
                                                                    <Scrolling AllowScroll="true" UseStaticHeaders="true" />
                                                                </ClientSettings>
                                                            </telerik:RadGrid>
                                                        </ItemTemplate>
                                                        <Items>
                                                            <telerik:RadComboBoxItem runat="server" Text=" "></telerik:RadComboBoxItem>
                                                        </Items>
                                                    </telerik:RadComboBox>
                                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                                                                                ControlToValidate="radcmbItemNumber" ErrorMessage="!"
                                                                                ForeColor="Red"
                                                                                SetFocusOnError="true" />
                                                </div>

I used a combo and when it it clicked, I need to load search result in a grid for what is typed in the combo box.
Here is my .cs

 protected void radcmbItemNumber_TextChanged(object sender, EventArgs e)
        {
            string textToSearch = radcmbItemNumber.Text.ToString();
            var gridItemList = radcmbItemNumber.Items[0].FindControl("radGridItemList") as RadGrid;
            if (!string.IsNullOrEmpty(textToSearch))
                gridItemList.MasterTableView.FilterExpression = "([ItemNumber] LIKE \'%" + textToSearch + "%\')";

            gridItemList.MasterTableView.Rebind();
}

So this text change works perfectly but in my grid new search result is not reloaded until I go to second page. Hope this makes sense.Let me know if you need further info. Thanks


问:
How to get the following array from database?
Ok to make it more clear:
I am Using doctrine

I have a table Brands and Products

```<code>Brand
  id
  name

Product
  id
  name
  brand_id
</code>```

I have a lot of brands and Products of those brands in the database.
I would like to retrieve List of brands(+ count of its products) Grouped by Brand.name's first latter.

```<code>ex:
array(
   n => array(
        0 => array('Nike', 4 ),
        1 => array('North Pole', 18)
        .....
   )
   .....
)
</code>```

So my question was can this be done with one query in a efficient way.
I really don't wan't to run separate queries for each brand.name's first latter.
Doctrines "Hierarchical Data" cross my mind but I believe it for different thing?.
thanks

答: You cannot take it from database in that way, but you can fetch data as objects or arrays and then transform it to described form. Use foreach loops.</p>

Body:
Ok to make it more clear:
I am Using doctrine

I have a table Brands and Products

Brand
  id
  name

Product
  id
  name
  brand_id

I have a lot of brands and Products of those brands in the database.
I would like to retrieve List of brands(+ count of its products) Grouped by Brand.name's first latter.

ex:
array(
   n => array(
        0 => array('Nike', 4 ),
        1 => array('North Pole', 18)
        .....
   )
   .....
)

So my question was can this be done with one query in a efficient way.
I really don't wan't to run separate queries for each brand.name's first latter.
Doctrines "Hierarchical Data" cross my mind but I believe it for different thing?.
thanks


问:
Calculate the duration between now and the next midnight using Chrono
What is the idiomatic way to get the duration between now and the next midnight?

I have a function like this:

```<code>extern crate chrono;

use chrono::prelude::*;
use time;

fn duration_until_next_midnight() -> time::Duration {
    let now = Local::now(); // Fri Dec 08 2017 23:00:00 GMT-0300 (-03)
    // ... how to continue??
}
</code>```

It should make a Duration with 1 hour, since the next midnight is Sat Dec 09 2017 00:00:00 GMT-0300 (-03)

答:
Just subtract the two dates: midnight and now:

```<code>extern crate chrono;
use chrono::prelude::*;
use std::time;

fn duration_until_next_midnight() -> time::Duration {
    let now = Local::now();
    // change to next day and reset hour to 00:00
    let midnight = (now + chrono::Duration::days(1))
        .with_hour(0).unwrap()
        .with_minute(0).unwrap()
        .with_second(0).unwrap()
        .with_nanosecond(0).unwrap();

    println!("Duration between {:?} and {:?}:", now, midnight);
    midnight.signed_duration_since(now).to_std().unwrap()
}

fn main() {
    println!("{:?}", duration_until_next_midnight())
}
</code>```

As requested by Matthieu, you can write something like:

```<code>fn duration_until_next_midnight() -> Duration {
    let now = Local::now();
    // get the NaiveDate of tomorrow
    let midnight_naivedate = (now + chrono::Duration::days(1)).naive_utc().date();
    // create a NaiveDateTime from it
    let midnight_naivedatetime = NaiveDateTime::new(midnight_naivedate, NaiveTime::from_hms(0, 0, 0));
    // get the local DateTime of midnight
    let midnight: DateTime<Local> = DateTime::from_utc(midnight_naivedatetime, *now.offset());

    println!("Duration between {:?} and {:?}:", now, midnight);
    midnight.signed_duration_since(now).to_std().unwrap()
}
</code>```

But I am not sure if it is better.

Body:
What is the idiomatic way to get the duration between now and the next midnight?

I have a function like this:

extern crate chrono;

use chrono::prelude::*;
use time;

fn duration_until_next_midnight() -> time::Duration {
    let now = Local::now(); // Fri Dec 08 2017 23:00:00 GMT-0300 (-03)
    // ... how to continue??
}

It should make a Duration with 1 hour, since the next midnight is Sat Dec 09 2017 00:00:00 GMT-0300 (-03)

Body:
Just subtract the two dates: midnight and now:

extern crate chrono;
use chrono::prelude::*;
use std::time;

fn duration_until_next_midnight() -> time::Duration {
    let now = Local::now();
    // change to next day and reset hour to 00:00
    let midnight = (now + chrono::Duration::days(1))
        .with_hour(0).unwrap()
        .with_minute(0).unwrap()
        .with_second(0).unwrap()
        .with_nanosecond(0).unwrap();

    println!("Duration between {:?} and {:?}:", now, midnight);
    midnight.signed_duration_since(now).to_std().unwrap()
}

fn main() {
    println!("{:?}", duration_until_next_midnight())
}

As requested by Matthieu, you can write something like:

fn duration_until_next_midnight() -> Duration {
    let now = Local::now();
    // get the NaiveDate of tomorrow
    let midnight_naivedate = (now + chrono::Duration::days(1)).naive_utc().date();
    // create a NaiveDateTime from it
    let midnight_naivedatetime = NaiveDateTime::new(midnight_naivedate, NaiveTime::from_hms(0, 0, 0));
    // get the local DateTime of midnight
    let midnight: DateTime<Local> = DateTime::from_utc(midnight_naivedatetime, *now.offset());

    println!("Duration between {:?} and {:?}:", now, midnight);
    midnight.signed_duration_since(now).to_std().unwrap()
}

But I am not sure if it is better.


问:
Google Chrome localhost | NET::ERR_CERT_AUTHORITY_INVALID
All of a sudden I seem to have an issue with Google Chrome using localhost.

I'm trying to access any of my development sites (using Ampps) and I get the following error:-

Your connection is not private Attackers might be trying to steal your
  information from website.dev (for example, passwords, messages
  or credit cards). Learn more NET::ERR_CERT_AUTHORITY_INVALID

When I visit any of the dev sites it is redirecting from http://website.dev to https://website.dev automatically. I'm not having any issue in Safari or Firefox so I don't understand what is going on.

I've tried re-installing Google Chrome, resetting it to the factory default settings...

I think it could be an issue with Keychain Access --> Certificates but wouldn't that mean it wouldn't work in Firefox and Safari if that was the case?

I've spent a while trying to find a solution but so far nothing has worked so I would appreciate some suggestions on how I can fix this. I can't even proceed passed this warning as I don't get the proceed link (insecure) as shown below:-

答: This is really annoying to deal with, but mapping the local website to something other than .dev (I personally use .devo) does work and fixes the problem in chrome. Also, you can add an exception for the page in Mozilla Firefox and not deal with this at all. It's only a problem on Chrome 63+


问:
Create multiple threads and wait for all of them to complete
How can I create multiple threads and wait for all of them to complete?</p>

答:
If you don't want to use the Task class (for instance, in .NET 3.5), you can just start all your threads, and then add them to the list and join them in a foreach loop.

Example:

List<Thread> threads = new List<Thread>();

// Start threads
for (int i = 0; i < 10; i++) {
    int tmp = i; // Copy value for closure
    Thread t = new Thread(() => Console.WriteLine(tmp));
    t.Start();
    threads.Add(t);
}

// Join threads (wait threads)
foreach (Thread thread in threads) {
    thread.Join();
}
```


问:
codeigniter routing
I am currently working on CMS for a client, and I am going to be using Codeigniter to build on top of, it is only a quick project so I am not looking for a robust solution.

To create pages, I am getting to save the page details and the pull the correct page, based on the slug matching the slug in the mysql table.

My question is however, for this to work, I have to pass this slug from the URL the controller then to the model, this means that I also have too have the controller in the URL which I do not want is it possible to remove the controller from the URL with routes?

so

/page/our-story

becomes

/our-story

Is this possible

答:
I would recommend to do it this way.

Let's say that you have : controller "page" / Method "show"

```<code>$route['page/show/:any'] = "$1";
</code>```

or method is index which I don't recommend, and if you have something like news, add the following.

```<code>$route['news/show/:any'] = "news/$1";
</code>```

That's it.

Title: codeigniter routing

Body:
I would recommend to do it this way.

Let's say that you have : controller "page" / Method "show"

$route['page/show/:any'] = "$1";

or method is index which I don't recommend, and if you have something like news, add the following.

$route['news/show/:any'] = "news/$1";

That's it.


问:
Include POST data as request params using Feign
Suppose I have an API like following where PersonDto is a simple pojo:

```<code>@RequestLine("POST /request/path")
String createPerson(PersonDto dto);
</code>```

When I call this API, feign includes all properties of pojo in request body (which is standard and good so far), but I have a legacy app on the other side which expects the POST data be included as request params. I know I can do something like:

```<code>@RequestLine("POST /request/path?id={id}&name={name}&...")
</code>```

but it gets really ugly if I have too many params.

I tried adding params programmatically using an interceptor and RequestTemplate.query but they all end up in the request body as well.

Any way to do such a thing in feign?

答:
you can use like this:

```<code>@RequestLine("POST /request/path")
@Headers("Content-Type: application/json")
String createPerson(PersonDto dto);
</code>```

and it need jdk1.8

Body:
Suppose I have an API like following where PersonDto is a simple pojo:

@RequestLine("POST /request/path")
String createPerson(PersonDto dto);

When I call this API, feign includes all properties of pojo in request body (which is standard and good so far), but I have a legacy app on the other side which expects the POST data be included as request params. I know I can do something like:

@RequestLine("POST /request/path?id={id}&name={name}&...")

but it gets really ugly if I have too many params.

I tried adding params programmatically using an interceptor and RequestTemplate.query but they all end up in the request body as well.

Any way to do such a thing in feign?

Body:
you can use like this:

@RequestLine("POST /request/path")
@Headers("Content-Type: application/json")
String createPerson(PersonDto dto);

and it need jdk1.8


问:
How to read Attribute Name and Dataset Name from HDF5 file in c++, here I dont know what are the attributes are there in HDF5 file

I have one HDF5 file say Select.h5 , But i dont know anything about the file except file name , How to know the attribute name and Dataset Name from this filename using c++</p>

答:
We can achieved this using Group ID , once you have created the HdF5 file Default group will create with name that '/'(which means root group),

so from that group we can get the information of DataSet of HDF5 file using DataSet  metadata we get the Information about the Attributes including its Name


问:
Angular 5 form duplicates input value
I have a simple form:

```<code>this.searchForm = this.formBuilder.group({
  query: [ null, [Validators.required] ]
});
</code>```

When user paste something into the input I reformat values using regex and update the form.

```<code>onPaste(event) {
    const formattedQuery = event.clipboardData.getData('text/plain')
      .split(/,?[\r\n\t]+\s?/)
      .join(', ')
      .replace(/,\s?$/g, '');

    this.searchForm.get('query').setValue(formattedQuery);
    // this.ref.detectChanges();
  }
</code>```

But when I paste something, for example

```<code>325435956
325435956
</code>```

It duplicate it and as a result I see 325435956, 325435956 325435956 325435956 but I expect to see 325435956, 325435956. Where is my mistake and how to fix that?

Working example you can find here https://stackblitz.com/edit/angular-cp9yhx?file=app%2Fhello.component.ts

答:
Even though you handle the paste function, the default behavior is left unchanged.

So, it first handles the method and prints out the expected values. And then pastes the values as is.

You should prevent the default behavior.

```<code>onPaste(event) {
    event.preventDefault();

    //rest of the method as it is right now
}
</code>```

Fixed example: https://stackblitz.com/edit/angular-7orqb9?file=app/hello.component.ts

Title: Angular 5 form duplicates input value

Body:
I have a simple form:

this.searchForm = this.formBuilder.group({
  query: [ null, [Validators.required] ]
});

When user paste something into the input I reformat values using regex and update the form.

onPaste(event) {
    const formattedQuery = event.clipboardData.getData('text/plain')
      .split(/,?[\r\n\t]+\s?/)
      .join(', ')
      .replace(/,\s?$/g, '');

    this.searchForm.get('query').setValue(formattedQuery);
    // this.ref.detectChanges();
  }

But when I paste something, for example

325435956
325435956

It duplicate it and as a result I see 325435956, 325435956 325435956 325435956 but I expect to see 325435956, 325435956. Where is my mistake and how to fix that?

Working example you can find here https://stackblitz.com/edit/angular-cp9yhx?file=app%2Fhello.component.ts

Body:
Even though you handle the paste function, the default behavior is left unchanged.

So, it first handles the method and prints out the expected values. And then pastes the values as is.

You should prevent the default behavior.

onPaste(event) {
    event.preventDefault();

    //rest of the method as it is right now
}

Fixed example: https://stackblitz.com/edit/angular-7orqb9?file=app/hello.component.ts


问:
Serialize an object to XML without using attributes
Is it possible to control XmlSerializer/DataContractSerializer behavior without specifying any serialization attributes?

To be more specific, I want to control the serialization (XmlIgnore, custom attribute name etc.), but without decorating my properties.
Use cases:

A large existing class, which I don't wish to pollute with serialization attributes

Serializing a class for which no source code is available

Switching from using XmlSerializer to DataContractSerializer to JSON without changing class code

For example, how would I serialize the following without uncommenting the attributes:

```<code>// [Serializable]
public MyClass
{
    // [XmlIgnore] - The following property should not be serialized, without uncommenting this line
    public int DontSerializeMeEvenThoughImPublic { get; set; }

    // [XmlAttribute("another_name")] - should be serialized as 'another_name', not 'SerializeMeAsXmlAttribute'
    public double SerializeMeAsXmlAttribute { get; set; }

    // [DataMember] - should be included
    private string IWantToBeSerializedButDontDecorateMeWithDataMember { get; set; }
}
</code>```

答:
I know this is an old question, but for the XmlSerializer part, it's interesting that no one has suggested the use of Attribute overrides.

Although not solving the Private property, but AFAIK you can't do that with attributes either, so the only route there would be the IXmlSerializable interface.

But what you can do by adding Attributes should be possible with overrides as well.

The following should work for the change wishes reflected by the outcommented XmlAttributes:

```<code>public class Program
{
    public static void Main()
    {
        XmlAttributeOverrides overrides = new XmlAttributeOverrides();
        overrides.Add(typeof(MyClass), "DontSerializeMeEvenThoughImPublic", new XmlAttributes { XmlIgnore = true });
        overrides.Add(typeof(MyClass), "SerializeMeAsXmlAttribute", new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("another_name") });
        XmlSerializer serializer = new XmlSerializer(typeof(MyClass), overrides);
        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, new MyClass());
            Console.WriteLine(writer.ToString());
        }
    }
}
</code>```

Body:
Is it possible to control XmlSerializer/DataContractSerializer behavior without specifying any serialization attributes?

To be more specific, I want to control the serialization (XmlIgnore, custom attribute name etc.), but without decorating my properties.
Use cases:

A large existing class, which I don't wish to pollute with serialization attributes

Serializing a class for which no source code is available

Switching from using XmlSerializer to DataContractSerializer to JSON without changing class code

For example, how would I serialize the following without uncommenting the attributes:

// [Serializable]
public MyClass
{
    // [XmlIgnore] - The following property should not be serialized, without uncommenting this line
    public int DontSerializeMeEvenThoughImPublic { get; set; }

    // [XmlAttribute("another_name")] - should be serialized as 'another_name', not 'SerializeMeAsXmlAttribute'
    public double SerializeMeAsXmlAttribute { get; set; }

    // [DataMember] - should be included
    private string IWantToBeSerializedButDontDecorateMeWithDataMember { get; set; }
}

Body:
I know this is an old question, but for the XmlSerializer part, it's interesting that no one has suggested the use of Attribute overrides.

Although not solving the Private property, but AFAIK you can't do that with attributes either, so the only route there would be the IXmlSerializable interface.

But what you can do by adding Attributes should be possible with overrides as well.

The following should work for the change wishes reflected by the outcommented XmlAttributes:

public class Program
{
    public static void Main()
    {
        XmlAttributeOverrides overrides = new XmlAttributeOverrides();
        overrides.Add(typeof(MyClass), "DontSerializeMeEvenThoughImPublic", new XmlAttributes { XmlIgnore = true });
        overrides.Add(typeof(MyClass), "SerializeMeAsXmlAttribute", new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("another_name") });
        XmlSerializer serializer = new XmlSerializer(typeof(MyClass), overrides);
        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, new MyClass());
            Console.WriteLine(writer.ToString());
        }
    }
}


问:
How to take plan details in onclick the button
Here i have one form and three button,suppose if i am clicking Enroll Now button means i have take the plan details like

Contacts details up to ?

Bonus Contact details up to  ?

Area Master Assistance : No ?

Contact details through sms ?

Above values i want to take how can take ? i tried i can able to take plan name which i have selected but i am not able to take plan details

  $(".payNow").on("click", function(e) {
    var $list = $(this).closest(".pricing-table");
      name = $list.find(".myTitle").text();

    console.log(name);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<body>
  <div class="container-fluid plan-background" style="margin-top: 0%;padding-right: 0px;padding-left: 0px;">
  <div class="container main_btm" style="padding-left: 0px;padding-right: 0px; ">

  <div class="row top" style="margin-left: 0px;margin-right: 0px;margin-top:22px;">

  <div class="col-md-5 col-sm-6 hidden-xs" class-align="right" style="margin-top: 10px;padding:left:23px; ">

  </div>
  <div class="col-md-3 col-sm-6 col-xs-12 mobile-property-list" style="margin-top: 10px; padding-left: 27px;"><h4 style="color:#fff;font-size:20px;"> Select Your Plan</h4></br>  </div>
  <div class="col-md-4 col-sm-0 hidden-xs"></div>

  </div>

  <div class="row mobile-filter"  style="margin-top: 5px; margin-left: 0px;margin-right: 0px;margin-bottom:5%;" >

  <div class="col-md-1"></div>
  <div class="col-md-10 top-a rentListing" style="padding-left:0px;">

  <section id="pricing-table">
                <div class="row pricelistNew">
                    <div class="pricing">

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Easy Plan </p>
         <input type="hidden" value="1 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 1000 <br><span>Including All Tax</span></p>

          Buy Now

                                </div>

                                <div class="pricing-list">
                                    <ul>
           <li>Contacts details up to : 25</li>
            <li>Bonus Contact details up to : 2</li>
            <li>Area Master Assistance : No</li>
            <li>Contact details through sms : Yes</li>
           </ul>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Cool Plan </p>
         <input type="hidden" value="2 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 2000 <br><span>Including All Tax</span></p>

         Buy Now

                                </div>

                                <div class="pricing-list">
                                    <ul>
           <li>Contacts details up to : 48</li>
            <li>Bonus Contact details up to : 4</li>
            <li>Area Master Assistance : Yes</li>
            <li>Contact details through sms : Yes</li>
           </ul>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Free Plan </p>
         <input type="hidden" value="3 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 0 <br><span>Including All Tax</span></p>

                                    Enroll Now

                                </div>

                                <div class="pricing-list">
                                    <ul>
           <li>Contacts details up to : 5</li>
            <li>Bonus Contact details up to : 00</li>
            <li>Area Master Assistance : No</li>
            <li>Contact details through sms : Yes</li>
           </ul>
                                </div>
                            </div>
                        </div>
                       </div>
                </div>
        </section>

  </div>

  <div class="col-md-1 "></div>
  </div>

  </div>
 </code>```

答:
You can use data attribute of HTML5 and get value back in jQuery using following way.

 $(".payNow").on("click", function(e) {
    var $list = $(this).closest(".pricing-table");
      name = $list.find(".myTitle").text();
      contact_upto = $list.find(".pricing-list ul").attr("data-contact-upto");
      bonus_upto = $list.find(".pricing-list ul").attr("data-bonus-upto");
      AMA = $list.find(".pricing-list ul").attr("data-AMA");
      sms = $list.find(".pricing-list ul").attr("data-sms");
      console.log(contact_upto);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<body>
  <div class="container-fluid plan-background" style="margin-top: 0%;padding-right: 0px;padding-left: 0px;">
  <div class="container main_btm" style="padding-left: 0px;padding-right: 0px; ">

  <div class="row top" style="margin-left: 0px;margin-right: 0px;margin-top:22px;">

  <div class="col-md-5 col-sm-6 hidden-xs" class-align="right" style="margin-top: 10px;padding:left:23px; ">

  </div>
  <div class="col-md-3 col-sm-6 col-xs-12 mobile-property-list" style="margin-top: 10px; padding-left: 27px;"><h4 style="color:#fff;font-size:20px;"> Select Your Plan</h4></br>  </div>
  <div class="col-md-4 col-sm-0 hidden-xs"></div>

  </div>

  <div class="row mobile-filter"  style="margin-top: 5px; margin-left: 0px;margin-right: 0px;margin-bottom:5%;" >

  <div class="col-md-1"></div>
  <div class="col-md-10 top-a rentListing" style="padding-left:0px;">

  <section id="pricing-table">
                <div class="row pricelistNew">
                    <div class="pricing">

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Easy Plan </p>
         <input type="hidden" value="1 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 1000 <br><span>Including All Tax</span></p>

          Buy Now

                                </div>

                                <div class="pricing-list">
                                    <ul data-contact-upto="25" data-bonus-upto="2" data-AMA="No" data-sms="Yes">
           <li>Contacts details up to : 25</li>
            <li>Bonus Contact details up to : 2</li>
            <li>Area Master Assistance : No</li>
            <li>Contact details through sms : Yes</li>
           </ul>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Cool Plan </p>
         <input type="hidden" value="2 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 2000 <br><span>Including All Tax</span></p>

         Buy Now

                                </div>

                                <div class="pricing-list">
                                   <ul data-contact-upto="48" data-bonus-upto="4" data-AMA="Yes" data-sms="Yes">
           <li>Contacts details up to : 48</li>
            <li>Bonus Contact details up to : 4</li>
            <li>Area Master Assistance : Yes</li>
            <li>Contact details through sms : Yes</li>
           </ul>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Free Plan </p>
         <input type="hidden" value="3 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 0 <br><span>Including All Tax</span></p>

                                    Enroll Now

                                </div>

                                <div class="pricing-list">
                                    <ul data-contact-upto="5" data-bonus-upto="0" data-AMA="No" data-sms="Yes">
           <li>Contacts details up to : 5</li>
            <li>Bonus Contact details up to : 00</li>
            <li>Area Master Assistance : No</li>
            <li>Contact details through sms : Yes</li>
           </ul>
                                </div>
                            </div>
                        </div>
                       </div>
                </div>
        </section>

  </div>

  <div class="col-md-1 "></div>
  </div>

  </div>
 </code>```

Body:
Here i have one form and three button,suppose if i am clicking Enroll Now button means i have take the plan details like

Contacts details up to ?

Bonus Contact details up to  ?

Area Master Assistance : No ?

Contact details through sms ?

Above values i want to take how can take ? i tried i can able to take plan name which i have selected but i am not able to take plan details

  $(".payNow").on("click", function(e) {
    var $list = $(this).closest(".pricing-table");
      name = $list.find(".myTitle").text();

    console.log(name);
  });

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

 Select Your Plan

Easy Plan

         <input type="hidden" value="1 " name="plan_Id" class="plan_Id">

₹ 1000
Including All Tax

          Buy Now

Contacts details up to : 25

Bonus Contact details up to : 2

Area Master Assistance : No

Contact details through sms : Yes

Cool Plan

         <input type="hidden" value="2 " name="plan_Id" class="plan_Id">

₹ 2000
Including All Tax

         Buy Now

Contacts details up to : 48

Bonus Contact details up to : 4

Area Master Assistance : Yes

Contact details through sms : Yes

Free Plan

         <input type="hidden" value="3 " name="plan_Id" class="plan_Id">

₹ 0
Including All Tax

                                    Enroll Now

Contacts details up to : 5

Bonus Contact details up to : 00

Area Master Assistance : No

Contact details through sms : Yes

Body:
You can use data attribute of HTML5 and get value back in jQuery using following way.

 $(".payNow").on("click", function(e) {
    var $list = $(this).closest(".pricing-table");
      name = $list.find(".myTitle").text();
      contact_upto = $list.find(".pricing-list ul").attr("data-contact-upto");
      bonus_upto = $list.find(".pricing-list ul").attr("data-bonus-upto");
      AMA = $list.find(".pricing-list ul").attr("data-AMA");
      sms = $list.find(".pricing-list ul").attr("data-sms");
      console.log(contact_upto);
  });

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<body>
  <div class="container-fluid plan-background" style="margin-top: 0%;padding-right: 0px;padding-left: 0px;">
  <div class="container main_btm" style="padding-left: 0px;padding-right: 0px; ">

  <div class="row top" style="margin-left: 0px;margin-right: 0px;margin-top:22px;">

  <div class="col-md-5 col-sm-6 hidden-xs" class-align="right" style="margin-top: 10px;padding:left:23px; ">

  </div>
  <div class="col-md-3 col-sm-6 col-xs-12 mobile-property-list" style="margin-top: 10px; padding-left: 27px;"><h4 style="color:#fff;font-size:20px;"> Select Your Plan</h4></br>  </div>
  <div class="col-md-4 col-sm-0 hidden-xs"></div>

  </div>

  <div class="row mobile-filter"  style="margin-top: 5px; margin-left: 0px;margin-right: 0px;margin-bottom:5%;" >

  <div class="col-md-1"></div>
  <div class="col-md-10 top-a rentListing" style="padding-left:0px;">

  <section id="pricing-table">
                <div class="row pricelistNew">
                    <div class="pricing">

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Easy Plan </p>
         <input type="hidden" value="1 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 1000 <br><span>Including All Tax</span></p>

          <a class="btn btn-custom payNow">Buy Now</a>

                                </div>

                                <div class="pricing-list">
                                    <ul data-contact-upto="25" data-bonus-upto="2" data-AMA="No" data-sms="Yes">
           <li>Contacts details up to : 25</li>
            <li>Bonus Contact details up to : 2</li>
            <li>Area Master Assistance : No</li>
            <li>Contact details through sms : Yes</li>
           </ul>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Cool Plan </p>
         <input type="hidden" value="2 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 2000 <br><span>Including All Tax</span></p>

         <a class="btn btn-custom payNow">Buy Now</a>

                                </div>

                                <div class="pricing-list">
                                   <ul data-contact-upto="48" data-bonus-upto="4" data-AMA="Yes" data-sms="Yes">
           <li>Contacts details up to : 48</li>
            <li>Bonus Contact details up to : 4</li>
            <li>Area Master Assistance : Yes</li>
            <li>Contact details through sms : Yes</li>
           </ul>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-4 col-sm-4 col-xs-12">
                            <div class="pricing-table">
                                <div class="pricing-header">
                                    <p class="pricing-title myTitle">Free Plan </p>
         <input type="hidden" value="3 " name="plan_Id" class="plan_Id">

                                    <p class="pricing-rate">₹ 0 <br><span>Including All Tax</span></p>

                                    <a class="btn btn-custom payNow" style="">Enroll Now</a>

                                </div>

                                <div class="pricing-list">
                                    <ul data-contact-upto="5" data-bonus-upto="0" data-AMA="No" data-sms="Yes">
           <li>Contacts details up to : 5</li>
            <li>Bonus Contact details up to : 00</li>
            <li>Area Master Assistance : No</li>
            <li>Contact details through sms : Yes</li>
           </ul>
                                </div>
                            </div>
                        </div>
                       </div>
                </div>
        </section>

  </div>

  <div class="col-md-1 "></div>
  </div>

  </div>


问:
How to highlight SQL syntax of Room Dao in Android Studio
With new Room, How to highlight SQL Syntax in Dao Interfaces?

For example @Query(SELECT * FROM user) is it possible to highlight the words SELECT, FROM with a different color and text format than the word user?

答: I found the answer from this link

Body: I found the answer from this link


问:
Is there a way to add a directory to Git but exclude extensions in .gitgnore?
Is there a way to add a directory to Git, but exclude extensions in .gitgnore?

e.g when I execute a command to add a directory such as

```<code>git add console/*
</code>```

git responds with response

```<code>$ git add console/*
The following paths are ignored by one of your .gitignore files:
console/networkprobing.ppu
console/opsdatamodule.lrs
console/opsdatamodule.o
console/opsdatamodule.ppu
console/rcacsSystemDM.compiled
console/rcacsSystemDM.o
console/rcacsSystemTestProcs.o
console/rcacsSystemTestProcs.ppu
Use -f if you really want to add them.
fatal: no files added
</code>```

How can the command be made to automatically exclude the .gitignore extensions?
Are there some additional options to be passed?

答:
```<code>git add console/*
</code>```

The problem is that the wildcard is expanded by shell globing and not passed directly to git, so git-add is really being passed every file in the console directory[1]. Because git-add is receiving each file in the directory as arguments, it thinks you might really be trying to add an ignored file which is why there is a warning and it hints to use -f if that is what you are really trying to do.

The solution is to not use shell globing but instead just pass the directory like so.

```<code>git add console
</code>```

Similarly the proper way to add everything to a repo (including files starting with a '.') except ignored files[2] to a repo is to use git add . and not git add *.

[1] Except ones starting with a '.' assuming you are on a sh like shell and not attempting this from the Windows cmd.exe command prompt. If you are using the Windows command prompt you should switch to using either the Git-Bash shell from msysgit or a shell from cygwin depending on how you installed git.

[2] .gitignore is only used to prevent untracked files from becoming tracked, if the file is already being tracked by git then it will continue to be treated normally until it is removed from the repo. This can be done without effecting the actual file with git rm --cached filename.

Body:
Is there a way to add a directory to Git, but exclude extensions in .gitgnore?

e.g when I execute a command to add a directory such as

git add console/*

git responds with response

$ git add console/*
The following paths are ignored by one of your .gitignore files:
console/networkprobing.ppu
console/opsdatamodule.lrs
console/opsdatamodule.o
console/opsdatamodule.ppu
console/rcacsSystemDM.compiled
console/rcacsSystemDM.o
console/rcacsSystemTestProcs.o
console/rcacsSystemTestProcs.ppu
Use -f if you really want to add them.
fatal: no files added

How can the command be made to automatically exclude the .gitignore extensions?
Are there some additional options to be passed?

Body:
git add console/*

The problem is that the wildcard is expanded by shell globing and not passed directly to git, so git-add is really being passed every file in the console directory[1]. Because git-add is receiving each file in the directory as arguments, it thinks you might really be trying to add an ignored file which is why there is a warning and it hints to use -f if that is what you are really trying to do.

The solution is to not use shell globing but instead just pass the directory like so.

git add console

Similarly the proper way to add everything to a repo (including files starting with a '.') except ignored files[2] to a repo is to use git add . and not git add *.

[1] Except ones starting with a '.' assuming you are on a sh like shell and not attempting this from the Windows cmd.exe command prompt. If you are using the Windows command prompt you should switch to using either the Git-Bash shell from msysgit or a shell from cygwin depending on how you installed git.

[2] .gitignore is only used to prevent untracked files from becoming tracked, if the file is already being tracked by git then it will continue to be treated normally until it is removed from the repo. This can be done without effecting the actual file with git rm --cached filename.