问:
If statement - C++
I have this array that I have created full of values and basically I want to go thru an if statement to check for every value that is input into the array is of a certain condition. The condition is fine and I have all the values that I need but this if statement is taking all the values from the redsigma array rather than each one from the array. How do I put each value into the if statement rather than the whole array. Relatively new to c++. Any help is appreciated.</p>

```<code>for (int i = 0; i < 7990272; i++)
{
 float redsigma[] = { img1->pixels[i].r + img2->pixels[i].r + img3->pixels[i].r + img4->pixels[i].r}

if (redsigma[0] > lbounds && redsigma[0] < upbounds)
{
                  do work blah blah blah
}
}
</code>```

答:
You need to use a for-loop to iterate over the elements:

```<code>for(int i = 0; i < the length of redsigma; ++i) {
    if(redsigma[i] meets conditions) {
    }
}
</code>```

I recommend that you use std::vector instead of an array.

Title: If statement - C++

Body:
I have this array that I have created full of values and basically I want to go thru an if statement to check for every value that is input into the array is of a certain condition. The condition is fine and I have all the values that I need but this if statement is taking all the values from the redsigma array rather than each one from the array. How do I put each value into the if statement rather than the whole array. Relatively new to c++. Any help is appreciated.

for (int i = 0; i < 7990272; i++)
{
 float redsigma[] = { img1->pixels[i].r + img2->pixels[i].r + img3->pixels[i].r + img4->pixels[i].r}

if (redsigma[0] > lbounds && redsigma[0] < upbounds)
{
                  do work blah blah blah
}
}

Body:
You need to use a for-loop to iterate over the elements:

for(int i = 0; i < the length of redsigma; ++i) {
    if(redsigma[i] meets conditions) {
    }
}

I recommend that you use std::vector instead of an array.


来源: stackexchange

问:
How to display randomly text when a button is clicked
I've got a project to do and I'm stuck at this stage. I have 5 paragraphs that include text and images that have to be displayed randomly in the button in clicked.  I still haven't figured out how to add the images in all of this. So far this is where I am:

function myFunction() {
  idArray = new Array()
  idArray [1] = "First paragraph text"
  idArray [2] = "Second paragraph text
  idArray [3] = "Third paragraph text
  idArray [4] = "Fourth paragraph text"
  idArray [5] = "Fifth paragraph text"

  document.getElementById("select").onclick = myFunction;
  randomParagraph = Math.floor(Math.random()*5);

  document.getElementById("result").innerHTML = new Array[randomParagraph];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <button onclick="myFunction()" id="select">Pick text</button>

  <div class="main">
    <p id="result"></p>
  </div>
  <footer class="footer">Hey</footer>
</body></code>```

答:
Shortened

var text = [
  "First paragraph text",
  "Second paragraph text",
  "Third paragraph text",
  "Fourth paragraph text",
  "Fifth paragraph text"
];

document.getElementById("select").onclick = function() {
  document.getElementById("result").innerHTML = text[Math.floor(Math.random() * text.length)];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <button id="select">Pick text</button>
  <div class="main">
    <p id="result"></p>
  </div>
  <footer class="footer">Footer</footer>
</body></code>```

ContentLicense: CC BY-SA 3.0

Body:
I've got a project to do and I'm stuck at this stage. I have 5 paragraphs that include text and images that have to be displayed randomly in the button in clicked.  I still haven't figured out how to add the images in all of this. So far this is where I am:

function myFunction() {
  idArray = new Array()
  idArray [1] = "First paragraph text"
  idArray [2] = "Second paragraph text
  idArray [3] = "Third paragraph text
  idArray [4] = "Fourth paragraph text"
  idArray [5] = "Fifth paragraph text"

  document.getElementById("select").onclick = myFunction;
  randomParagraph = Math.floor(Math.random()*5);

  document.getElementById("result").innerHTML = new Array[randomParagraph];
}

  <button onclick="myFunction()" id="select">Pick text</button>

  Hey

Body:
Shortened

var text = [
  "First paragraph text",
  "Second paragraph text",
  "Third paragraph text",
  "Fourth paragraph text",
  "Fifth paragraph text"
];

document.getElementById("select").onclick = function() {
  document.getElementById("result").innerHTML = text[Math.floor(Math.random() * text.length)];
}

<body>
  <button id="select">Pick text</button>
  <div class="main">
    <p id="result"></p>
  </div>
  <footer class="footer">Footer</footer>
</body>


问:
Random IO typing in haskell
I want the function to draw a number, and if it is greater than 7, send an approval message and call this add function.

However, my function only falls on the 'else'. The "disapproved" message appears. I think it's the IO Float typing with Float. How can I solve this?

```<code>mySort:: Float -> Int
mySort = ceiling(10 * x)

numberSort:: IO ()
numberSort = do
    num <- randomIO :: IO Float
    print $ mySort num
    if(num >= 7) then
        do
            putStrLn ("approved!" ++ "\n") >> add
        else
        do
            putStrLn "disapproved!"
</code>```

答:
randomIO works like random, which uses [0,1) for fractional types.

```<code>random :: RandomGen g => g -> (a, g)
</code>```

The same as randomR, but using a default range determined by the type:

For bounded types (instances of Bounded, such as Char), the range is normally the whole type.

For fractional types, the range is normally the semi-closed interval [0,1). [emphasis mine]

For Integer, the range is (arbitrarily) the range of Int.

Use randomRIO instead, e.g.

```<code>num <- randomRIO (0, 10) :: IO Float
</code>```

Title: Random IO typing in haskell

Body:
I want the function to draw a number, and if it is greater than 7, send an approval message and call this add function.

However, my function only falls on the 'else'. The "disapproved" message appears. I think it's the IO Float typing with Float. How can I solve this?

mySort:: Float -> Int
mySort = ceiling(10 * x)

numberSort:: IO ()
numberSort = do
    num <- randomIO :: IO Float
    print $ mySort num
    if(num >= 7) then
        do
            putStrLn ("approved!" ++ "\n") >> add
        else
        do
            putStrLn "disapproved!"

Body:
randomIO works like random, which uses [0,1) for fractional types.

random :: RandomGen g => g -> (a, g)

The same as randomR, but using a default range determined by the type:

For bounded types (instances of Bounded, such as Char), the range is normally the whole type.

For fractional types, the range is normally the semi-closed interval [0,1). [emphasis mine]

For Integer, the range is (arbitrarily) the range of Int.

Use randomRIO instead, e.g.

num <- randomRIO (0, 10) :: IO Float


问:
How do i get the root, not the document root
I want to upload images outside the document root:

```<code>// on server:
/home1/myname/artist_gallery

// on localhost
c:/artist_gallery
</code>```

I use the following to create the DEFINE for both local and server:

```<code>define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('GALLERY_FILE', DOCUMENT_ROOT . '/artist_gallery/');
</code>```

but, i get

```<code>/home1/myname/public_html/artist_gallery
C:/public_html/artist_gallery
</code>```

Notice the folder public_html... i dont want that folder...

So, how do I get the root (not the document root) in one DEFINE rule for both the localhost and server?

答:
With a file structure like

```<code>/home1/myname/
  --- public_html/        # all site files
  --- artist_gallery/     # gallery dir
</code>```

You need to define you constants like:

```<code>define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
// will point to document_root, it is `/home1/myname/public_html/`

define('GALLERY_FILE', realpath(DOCUMENT_ROOT . '/../artist_gallery/'));
// path will be resolved and will point to `/home1/myname/artist_gallery/`
</code>```

Body:
I want to upload images outside the document root:

// on server:
/home1/myname/artist_gallery

// on localhost
c:/artist_gallery

I use the following to create the DEFINE for both local and server:

define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('GALLERY_FILE', DOCUMENT_ROOT . '/artist_gallery/');

but, i get

/home1/myname/public_html/artist_gallery
C:/public_html/artist_gallery

Notice the folder public_html... i dont want that folder...

So, how do I get the root (not the document root) in one DEFINE rule for both the localhost and server?

Body:
With a file structure like

/home1/myname/
  --- public_html/        # all site files
  --- artist_gallery/     # gallery dir

You need to define you constants like:

define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
// will point to document_root, it is `/home1/myname/public_html/`

define('GALLERY_FILE', realpath(DOCUMENT_ROOT . '/../artist_gallery/'));
// path will be resolved and will point to `/home1/myname/artist_gallery/`


问:
Set two buttons to same width regardless of screen size?
Ok, i have two buttons in linear layout:

```<code><LinearLayout android:id="@+id/linearLayout1"
              android:layout_height="wrap_content"
              android:layout_width="fill_parent">
        <Button android:id="@+id/aktiviraj_paket"
                android:text="Aktiviraj"
                android:layout_height="40sp"
                android:layout_width="160sp"
                android:background="@drawable/my_border3"
                android:onClick="myClickHandle"></Button>
        <Button android:id="@+id/deaktiviraj_paket"
                android:text="Deaktiviraj"
                android:layout_height="40sp"
                android:layout_width="fill_parent"
                android:background="@drawable/my_border3"
                android:onClick="myClickHandle">
        </Button>
</LinearLayout>
</code>```

So the thing is, if I use fill parent on both buttons, they are one on each other, so i have made first button 160sp width, and second is fill_parent. If this is shown on 4 inch screen or smaller, buttons are the same size, but if i try this on tablet (10 inch) first button stays 160sp wide, and second is stretched till the end of screen (because fill_parent). Can i make this, so both buttons could be even size in no matter what size is the screen ??

答:
```<code><LinearLayout
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_weight="1"
        android:text="One" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_weight="1"
        android:text="Two" />
</LinearLayout>
</code>```

These is the example for equal size buttons for side by side can be done from above code

```<code>android:layout_weight
</code>```

is used to assign space for buttons or whatever of equal amount for every child of LinearLayout.

Note: It works only on linear layout.

Body:
Ok, i have two buttons in linear layout:

<LinearLayout android:id="@+id/linearLayout1"
              android:layout_height="wrap_content"
              android:layout_width="fill_parent">
        <Button android:id="@+id/aktiviraj_paket"
                android:text="Aktiviraj"
                android:layout_height="40sp"
                android:layout_width="160sp"
                android:background="@drawable/my_border3"
                android:onClick="myClickHandle"></Button>
        <Button android:id="@+id/deaktiviraj_paket"
                android:text="Deaktiviraj"
                android:layout_height="40sp"
                android:layout_width="fill_parent"
                android:background="@drawable/my_border3"
                android:onClick="myClickHandle">
        </Button>
</LinearLayout>

So the thing is, if I use fill parent on both buttons, they are one on each other, so i have made first button 160sp width, and second is fill_parent. If this is shown on 4 inch screen or smaller, buttons are the same size, but if i try this on tablet (10 inch) first button stays 160sp wide, and second is stretched till the end of screen (because fill_parent). Can i make this, so both buttons could be even size in no matter what size is the screen ??

Body:
<LinearLayout
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_weight="1"
        android:text="One" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_weight="1"
        android:text="Two" />
</LinearLayout>

These is the example for equal size buttons for side by side can be done from above code

android:layout_weight

is used to assign space for buttons or whatever of equal amount for every child of LinearLayout.

Note: It works only on linear layout.


问:
Symfony2: Custom Error Page Extend base.html.twig
I am trying to customize the error pages in Symfony.

This is my error.html.twig file located in app/Resources/TwigBundle/views/Exception/:

```<code>{% extends '::base.html.twig' %}

{% block body %}

<h1>{{ status_code }}: {{ status_text }}</h1>

{% endblock %}
</code>```

Unfortunately I get the following error message:

Fatal error: Uncaught exception
  'Symfony\Component\Routing\Exception\ResourceNotFoundException' in
  [...]
  vendor\symfony\symfony\src\Symfony\Component\HttpKernel\EventListener\RouterListener.php
  on line 144

When I remove {% extends '::base.html.twig' %} everything works fine. Any ideas how to have my base template included in the error page?

Edit 1:
The strange thing is that it seems to work when a 403 is thrown, e.g., when I access /user but don't have the necessary privilege.

Edit 2:
I pasted the whole content of my base.html.twig into the error.html.twig file and noticed that the error was caused due to the menu rendered by the KnpMenuBundle bundle:

```<code>{{ knp_menu_render('ACMEMemberBundle:Builder:mainMenu', { 'style': 'pills', 'currentClass': 'active' }) }}
</code>```

When I remove this line, everything works fine. But this is not the way I would like to go. Is there no possibility to keep the navigation?

答:
plz remove :: in first line https://symfony.com/doc/current/templating.html

```<code> {% extends 'base.html.twig' %}

{% block body %}

<h1>{{ status_code }}: {{ status_text }}</h1>

{% endblock %}
</code>```

Body:
I am trying to customize the error pages in Symfony.

This is my error.html.twig file located in app/Resources/TwigBundle/views/Exception/:

{% extends '::base.html.twig' %}

{% block body %}

{{ status_code }}: {{ status_text }}

{% endblock %}

Unfortunately I get the following error message:

Fatal error: Uncaught exception
  'Symfony\Component\Routing\Exception\ResourceNotFoundException' in
  [...]
  vendor\symfony\symfony\src\Symfony\Component\HttpKernel\EventListener\RouterListener.php
  on line 144

When I remove {% extends '::base.html.twig' %} everything works fine. Any ideas how to have my base template included in the error page?

Edit 1:
The strange thing is that it seems to work when a 403 is thrown, e.g., when I access /user but don't have the necessary privilege.

Edit 2:
I pasted the whole content of my base.html.twig into the error.html.twig file and noticed that the error was caused due to the menu rendered by the KnpMenuBundle bundle:

{{ knp_menu_render('ACMEMemberBundle:Builder:mainMenu', { 'style': 'pills', 'currentClass': 'active' }) }}

When I remove this line, everything works fine. But this is not the way I would like to go. Is there no possibility to keep the navigation?

Body:
plz remove :: in first line https://symfony.com/doc/current/templating.html

 {% extends 'base.html.twig' %}

{% block body %}

<h1>{{ status_code }}: {{ status_text }}</h1>

{% endblock %}


问:
Hadoop/Hive : Loading data from .csv on a local machine
As this is coming from a newbie...

I had Hadoop and Hive set up for me, so I can run Hive queries on my computer accessing data on AWS cluster.
Can I run Hive queries with .csv data stored on my computer, like I did with MS SQL Server?

How do I load .csv data into Hive then? What does it have to do with Hadoop and which mode I should run that one?

What settings I should care about so that if I did something wrong I can always go back and run queries on Amazon without compromising what was set up for me earlier?

答:
For csv file formate data will be in below format

```<code>"column1", "column2","column3","column4"
</code>```

And if we will use field terminated by ',' then each column will get values like below.

```<code>"column1"    "column2"     "column3"     "column4"
</code>```

also if any of the column value has comma as value then it will not work at all .

So the correct way to create a table would be by using OpenCSVSerde

```<code>create table tableName (column1 datatype, column2 datatype , column3 datatype , column4 datatype)
ROW FORMAT SERDE
'org.apache.hadoop.hive.serde2.OpenCSVSerde'
STORED AS TEXTFILE ;
</code>```

Body:
For csv file formate data will be in below format

"column1", "column2","column3","column4"

And if we will use field terminated by ',' then each column will get values like below.

"column1"    "column2"     "column3"     "column4"

also if any of the column value has comma as value then it will not work at all .

So the correct way to create a table would be by using OpenCSVSerde

create table tableName (column1 datatype, column2 datatype , column3 datatype , column4 datatype)
ROW FORMAT SERDE
'org.apache.hadoop.hive.serde2.OpenCSVSerde'
STORED AS TEXTFILE ;


问:
Sum of some positions in a row - R
Considering a generic matrix nxn - for example:

```<code>A <- matrix(1:16, nrow = 4, ncol = 4)
</code>```

How can I calculate the sum of the rows in the "right lower" triangle and show the information in a vector?

答:
Here is a solution. The key is to use lower.tri or upper.tri function, and then use apply to sort each row or column. Finally calculate the sum of each row.

```<code># Create example data frame
m <- matrix(1:16, 4)
m
#      [,1] [,2] [,3] [,4]
# [1,]    1    5    9   13
# [2,]    2    6   10   14
# [3,]    3    7   11   15
# [4,]    4    8   12   16

# Calculate the sum
rowSums(m * apply(lower.tri(m), 1, sort))
# [1] 0 14 26 36

rowSums(m * apply(upper.tri(m), 2, sort))
# [1] 0 14 26 36
</code>```

Title: Sum of some positions in a row - R

Body:
Considering a generic matrix nxn - for example:

A <- matrix(1:16, nrow = 4, ncol = 4)

How can I calculate the sum of the rows in the "right lower" triangle and show the information in a vector?

Body:
Here is a solution. The key is to use lower.tri or upper.tri function, and then use apply to sort each row or column. Finally calculate the sum of each row.

# Create example data frame
m <- matrix(1:16, 4)
m
#      [,1] [,2] [,3] [,4]
# [1,]    1    5    9   13
# [2,]    2    6   10   14
# [3,]    3    7   11   15
# [4,]    4    8   12   16

# Calculate the sum
rowSums(m * apply(lower.tri(m), 1, sort))
# [1] 0 14 26 36

rowSums(m * apply(upper.tri(m), 2, sort))
# [1] 0 14 26 36


问:
Fetch data with single and fast SQL query
I have the following data:

```<code>ExamEntry   Student_ID     Grade
  11           1             80
  12           2             70
  13           3             20
  14           3             68
  15           4             75
</code>```

I want to find all the students that passed an exam. In this case, if there are few exams
that one student attended to, I need to find the last result.

So, in this case I'd get that all students passed.

Can I find it with one fast query? I do it this way:

Find the list of entries by
select max(ExamEntry) from data group by Student_ID

Find the results:

select ExamEntry from data where ExamEntry in ( ).

But this is VERY slow - I get around 1000 entries, and this 2 step process takes 10 seconds.

Is there a better way?

Thanks.

答:
```<code>select examentry,student_id,grade
from data
where examentry in
  (select max(examentry)
   from data
   where grade > 60
   group by student_id)
</code>```

OwnerDisplayName: Alex

ContentLicense: CC BY-SA 2.5

Body:
I have the following data:

ExamEntry   Student_ID     Grade
  11           1             80
  12           2             70
  13           3             20
  14           3             68
  15           4             75

I want to find all the students that passed an exam. In this case, if there are few exams
that one student attended to, I need to find the last result.

So, in this case I'd get that all students passed.

Can I find it with one fast query? I do it this way:

Find the list of entries by
select max(ExamEntry) from data group by Student_ID

Find the results:

select ExamEntry from data where ExamEntry in ( ).

But this is VERY slow - I get around 1000 entries, and this 2 step process takes 10 seconds.

Is there a better way?

Thanks.

LastEditorDisplayName: Yaakov Ellis

OwnerDisplayName: tuinstoel


问:
why does Python lint want me to use different local variable name, than a global, for the same purpose
Given Python code such as

```<code>def func():
    for i in range(10):
        pass

for i in range(10):
    pass
</code>```

pylint complains

```<code>Redefining name 'i' from outer scope
</code>```

What is the Pythonic way to write the above?  Use a different variable locally, say j?

But why, when the variable means exactly the same in both cases (i for index).  Let's say I change all local indexes to j and then later I find I want to use j as the second index in the glocal scope.  Have to change again?

I can't disable lint warnings, I don't want to have them, I want to write Pythonic, and yet I want to use the same name for the same thing throughout, in the simple case like the above.  Is this not possible?

答:
Because it eliminate the risk of being using one when you believe you are using the other. Lint tools are made to make your code more robust. By having all your variables having different names, you ensure that no such conflict could arise.

This is especially critical in interpreted language because the errors are not checked at "compile time". I once had the problem that the second call to a function gave me an error, because I renamed a function and I didn't realize that in some case There was a variable which was created with the same name as my function, and so, when I was trying to call my function, the interpreter tried to "call" my newly created variable, which never worked XD.

this lint policy will avoid that kind of problem.

Here is a sample code (this is a program to compute pi) :

```<code>from fractions import Fraction

def order(x):
    r, old_r, n, old_n = 2, 1, 1, 0
    while (x>=r):
        r, old_r, n, old_n = r*r, r, 2*n, n
    return order(x >> old_n) + old_n if old_n > 0 else 0

def term(m, n, i):
    return Fraction(4 * m, n**(2*i+1) * (2*i+1))

def terms_generator(exp_prec):
    ws = [ [term(parm[1], parm[2], 0), 0] + list(parm)
          for parm in ((1, 44, 57),
                       (1, 7, 239),
                       (-1, 12, 682),
                       (1, 24, 12943))]
    digits = 0
    while digits<exp_prec:
        curws = max(ws, key=lambda col: col[0])
        digits = int(0.30103 *
                     (order(curws[0].denominator))
                      - order(curws[0].numerator))
        yield curws[2] * curws[0], digits
        curws[2] = -curws[2]
        curws[1] += 1
        curws[0] = term(curws[3], curws[4], curws[1])

expected_precision = 1000
pi = 0
for term, dgts in terms_generator(expected_precision):
    pi += term

print("{} digits".format(dgts))
print("pi = 3.{}".format(int((pi-3)*10**expected_precision)))
</code>```

In this case, I initialized a variable from a generator and the generator used another function which conflicted with my variable name once it was initialized by my generator. Well, It's not a very good example because here both names are global, but from it's structure, it wasn't immediately obvious that it would happen.

My point is that even if you KNOW how to program, you make mistakes and those practices will help reduce the risks for those to stay hidden.

Body:
Given Python code such as

def func():
    for i in range(10):
        pass

for i in range(10):
    pass

pylint complains

Redefining name 'i' from outer scope

What is the Pythonic way to write the above?  Use a different variable locally, say j?

But why, when the variable means exactly the same in both cases (i for index).  Let's say I change all local indexes to j and then later I find I want to use j as the second index in the glocal scope.  Have to change again?

I can't disable lint warnings, I don't want to have them, I want to write Pythonic, and yet I want to use the same name for the same thing throughout, in the simple case like the above.  Is this not possible?

Body:
Because it eliminate the risk of being using one when you believe you are using the other. Lint tools are made to make your code more robust. By having all your variables having different names, you ensure that no such conflict could arise.

This is especially critical in interpreted language because the errors are not checked at "compile time". I once had the problem that the second call to a function gave me an error, because I renamed a function and I didn't realize that in some case There was a variable which was created with the same name as my function, and so, when I was trying to call my function, the interpreter tried to "call" my newly created variable, which never worked XD.

this lint policy will avoid that kind of problem.

Here is a sample code (this is a program to compute pi) :

from fractions import Fraction

def order(x):
    r, old_r, n, old_n = 2, 1, 1, 0
    while (x>=r):
        r, old_r, n, old_n = r*r, r, 2*n, n
    return order(x >> old_n) + old_n if old_n > 0 else 0

def term(m, n, i):
    return Fraction(4 * m, n**(2*i+1) * (2*i+1))

def terms_generator(exp_prec):
    ws = [ [term(parm[1], parm[2], 0), 0] + list(parm)
          for parm in ((1, 44, 57),
                       (1, 7, 239),
                       (-1, 12, 682),
                       (1, 24, 12943))]
    digits = 0
    while digits<exp_prec:
        curws = max(ws, key=lambda col: col[0])
        digits = int(0.30103 *
                     (order(curws[0].denominator))
                      - order(curws[0].numerator))
        yield curws[2] * curws[0], digits
        curws[2] = -curws[2]
        curws[1] += 1
        curws[0] = term(curws[3], curws[4], curws[1])

expected_precision = 1000
pi = 0
for term, dgts in terms_generator(expected_precision):
    pi += term

print("{} digits".format(dgts))
print("pi = 3.{}".format(int((pi-3)*10**expected_precision)))

In this case, I initialized a variable from a generator and the generator used another function which conflicted with my variable name once it was initialized by my generator. Well, It's not a very good example because here both names are global, but from it's structure, it wasn't immediately obvious that it would happen.

My point is that even if you KNOW how to program, you make mistakes and those practices will help reduce the risks for those to stay hidden.


问:
Laravel get last inserted data
Please find the code below, Here I am trying to create master record and based on the id I am adding related data.

```<code>    $country = new Country;

    $country->name = $request->post('country-name');
    $country->xyz  = $request->post('xyz');

    if($country->save()) {
        $n = count($request->post('bname'));

        for ($i = 0; $i < $n; $i++) {
            $dimention = new BoxDimentions;

            $dimention->name = $request->post('bname')[$i];
            $dimention->xyz  = $request->post('xyz')[$i];
            $dimention->cid  = $country->id;

            $dimention->save();
        }
    }
</code>```

Is there any inbuilt laravel function I can use to get all the information about country & BoxDimentions(including id, date time stamp etc) after the operation?

I have created a relation in the Country Model class "boxes" which will return all the box information. I know I can fetch the data using another query with the last created country id. I dont want to go for another query because I believe we have all the data is in our hand.

答:
If you've already setup the relationship, won't the following do the job for you?, sure this might be another query but it will return the data as a collection and saves you handling this yourself.</p>

```<code>dd($country->boxes);
</code>```

Title: Laravel get last inserted data

Body:
Please find the code below, Here I am trying to create master record and based on the id I am adding related data.

    $country = new Country;

    $country->name = $request->post('country-name');
    $country->xyz  = $request->post('xyz');

    if($country->save()) {
        $n = count($request->post('bname'));

        for ($i = 0; $i < $n; $i++) {
            $dimention = new BoxDimentions;

            $dimention->name = $request->post('bname')[$i];
            $dimention->xyz  = $request->post('xyz')[$i];
            $dimention->cid  = $country->id;

            $dimention->save();
        }
    }

Is there any inbuilt laravel function I can use to get all the information about country & BoxDimentions(including id, date time stamp etc) after the operation?

I have created a relation in the Country Model class "boxes" which will return all the box information. I know I can fetch the data using another query with the last created country id. I dont want to go for another query because I believe we have all the data is in our hand.

Body:
If you've already setup the relationship, won't the following do the job for you?, sure this might be another query but it will return the data as a collection and saves you handling this yourself.

dd($country->boxes);


问:
vue Only Load the component content upon request
i'm new to vue, I encountered this problem, say I have dozen popup that contains heavy contents that is actually only needed upon request. I realized my previous approach is wrong (I tried vue-router to render the content, but it was not effective since the content under the popup would change everytime i push to new route). I tried named views, but I still think its wrong. Now my question is, how about I put it inside as a modal compoent? Will it only be rendered upon show? Or will it be rendered at once I attached it to the components regardless if its showing or not? How can I make it only render, say after a user click a button?

```<code>export default {
name: ‘app’,
components: {Modal1,Modal2,Modal3,Modal4}, <-- are all this will be rendered?
}
</code>```

Btw, I'm using webpacks. Also, I'm new to SPA development so I'm not sure if i'm grasping the concept of rendering correctly... I just want to make sure the page would be rendered first and load without waiting for each modal to finish rendering... Also it must be accessible from any router-view inside the app.

EDIT: Upon further research, I think I can do it with dynamic components. I think i'm on the right track now, i just need help finding the right guide out ther.

答:
hi since you mentioned you are using webpack the right approach will be to make use of the "lazy load" & "code splitting" feature.
something specific to vue can be found here</p>

Body:
i'm new to vue, I encountered this problem, say I have dozen popup that contains heavy contents that is actually only needed upon request. I realized my previous approach is wrong (I tried vue-router to render the content, but it was not effective since the content under the popup would change everytime i push to new route). I tried named views, but I still think its wrong. Now my question is, how about I put it inside as a modal compoent? Will it only be rendered upon show? Or will it be rendered at once I attached it to the components regardless if its showing or not? How can I make it only render, say after a user click a button?

export default {
name: ‘app’,
components: {Modal1,Modal2,Modal3,Modal4}, <-- are all this will be rendered?
}

Btw, I'm using webpacks. Also, I'm new to SPA development so I'm not sure if i'm grasping the concept of rendering correctly... I just want to make sure the page would be rendered first and load without waiting for each modal to finish rendering... Also it must be accessible from any router-view inside the app.

EDIT: Upon further research, I think I can do it with dynamic components. I think i'm on the right track now, i just need help finding the right guide out ther.


问:
Does Twig have equivalent 'append'?
```<code>{% block page %}
   <ul class="gallery">
     {% set foo = 0 %}
     {% for products in prodArr %}
       {% if foo % 4 == 0 %}
         <ul class="slides">
           <li>Product</li>
         </ul>
       {% else %}
         <li>Another Product<li> // this
       {% endif %}
     {% set foo = foo + 1 %}
     {% endfor %}
   </ul>
{% endblock %}
</code>```

In other case I want that li will append to ul with class slides. Is this possible?

I want that my HTML will be look like this:

```<code><ul class="gallery">
  <ul class="slides">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
  </ul>
  <ul class="slides">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
  </ul>
</ul>
</code>```

答:
Twig has embed and include, but in your case you can just refactor your code like this:

```<code>// UPDATED:
<ul class="gallery">
    {% for chunk in products|batch(4) %}
        <ul class="slides">
            {% for product in chunk %}
                <li>{{ product.title }}</li> // assuming you have title property
            {% endfor %}
        </ul>
    {% endfor %}
</ul>
</code>```

P.S. Unfortunately I can not test it but you will get the general idea ;)

Title: Does Twig have equivalent 'append'?

Body:
{% block page %}

     {% set foo = 0 %}
     {% for products in prodArr %}
       {% if foo % 4 == 0 %}

Product

       {% else %}

Another Product
 // this
       {% endif %}
     {% set foo = foo + 1 %}
     {% endfor %}

{% endblock %}

In other case I want that li will append to ul with class slides. Is this possible?

I want that my HTML will be look like this:

Body:
Twig has embed and include, but in your case you can just refactor your code like this:

// UPDATED:
<ul class="gallery">
    {% for chunk in products|batch(4) %}
        <ul class="slides">
            {% for product in chunk %}
                <li>{{ product.title }}</li> // assuming you have title property
            {% endfor %}
        </ul>
    {% endfor %}
</ul>

P.S. Unfortunately I can not test it but you will get the general idea ;)


问:
Remove elements from singly linked list (javascript)
I'm doing a CodeFights problem, trying to remove elements from a singly linked list that has the value k.

Below is what I have (l is the list and k is the value):

```<code>function removeKFromList(l, k) {
    //figure out the head of the new list so we can reference it later
    var head = l;

    while (head.value === k){
        head = head.next;
    }

    var node = head;
    var temp = null;

    while (node && node !== null) {
        if (node.next.value === k){
            temp = node.next.next;
            node.next.next = null;
            node.next = temp;
        }
        node = node.next;
        console.log("+++", head)
    }

    console.log("---", head)
}
</code>```

The CodeFight test cast is 3 -> 1 -> 2 -> 3 -> 4 -> 5. The final result would have been 1 -> 2 -> 4 -> 5. But my '---' console log keeps returning "Empty" (according to the CodeFights console).

My '+++' console log returns the correct head with element each loop.

I've been pulling my hair out over this, any idea what is missing here?

答:
You need to return the list if you delete the first node.

Then you need a loop for taking the next not while the value is not found.

At last you need a check if the last node exist and if the value is found, then assign the next node to the last next property.

function removeNode(list, value) {
    var node = list,
        last;

    if (node && node.value === value) {
        return node.next;
    }

    while (node && node.value !== value) {
        last = node,
        node = node.next;
    }
    if (last && node.value === value) {
        last.next = node.next;
    }
    return list;
}

var list = { value: 1, next: { value: 2, next: { value: 3, next: { value: 4, next: { value: 5, next: { value: 6, next: { value: 7, next: null } } } } } } };

list = removeNode(list, 5);
console.log(list)

list = removeNode(list, 1);
console.log(list)

list = removeNode(list, 7);
console.log(list)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm doing a CodeFights problem, trying to remove elements from a singly linked list that has the value k.

Below is what I have (l is the list and k is the value):

function removeKFromList(l, k) {
    //figure out the head of the new list so we can reference it later
    var head = l;

    while (head.value === k){
        head = head.next;
    }

    var node = head;
    var temp = null;

    while (node && node !== null) {
        if (node.next.value === k){
            temp = node.next.next;
            node.next.next = null;
            node.next = temp;
        }
        node = node.next;
        console.log("+++", head)
    }

    console.log("---", head)
}

The CodeFight test cast is 3 -> 1 -> 2 -> 3 -> 4 -> 5. The final result would have been 1 -> 2 -> 4 -> 5. But my '---' console log keeps returning "Empty" (according to the CodeFights console).

My '+++' console log returns the correct head with element each loop.

I've been pulling my hair out over this, any idea what is missing here?

Body:
You need to return the list if you delete the first node.

Then you need a loop for taking the next not while the value is not found.

At last you need a check if the last node exist and if the value is found, then assign the next node to the last next property.

function removeNode(list, value) {
    var node = list,
        last;

    if (node && node.value === value) {
        return node.next;
    }

    while (node && node.value !== value) {
        last = node,
        node = node.next;
    }
    if (last && node.value === value) {
        last.next = node.next;
    }
    return list;
}

var list = { value: 1, next: { value: 2, next: { value: 3, next: { value: 4, next: { value: 5, next: { value: 6, next: { value: 7, next: null } } } } } } };

list = removeNode(list, 5);
console.log(list)

list = removeNode(list, 1);
console.log(list)

list = removeNode(list, 7);
console.log(list)

.as-console-wrapper { max-height: 100% !important; top: 0; }


Title: Sum of some positions in a row - R

Body:
A = matrix(1:16, 4)
A
#      [,1] [,2] [,3] [,4]
# [1,]    1    5    9   13
# [2,]    2    6   10   14
# [3,]    3    7   11   15
# [4,]    4    8   12   16

sapply(1:NROW(A), function(i) sum(tail(A[i,], i - 1)))
#[1]  0 14 26 36


答:
Find a mask that encapsulates the data desired:

```<code>> mask <- apply(lower.tri(A, diag = FALSE), 1, rev)
> mask
      [,1]  [,2]  [,3]  [,4]
[1,] FALSE FALSE FALSE FALSE
[2,] FALSE FALSE FALSE  TRUE
[3,] FALSE FALSE  TRUE  TRUE
[4,] FALSE  TRUE  TRUE  TRUE
</code>```

Multiply this mask and calculate sums:

```<code>> A * mask
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]    0    0    0   14
[3,]    0    0   11   15
[4,]    0    8   12   16

>  rowSums(A * mask)
[1]  0 14 26 36
</code>```

Title: Sum of some positions in a row - R

Body:
Find a mask that encapsulates the data desired:

> mask <- apply(lower.tri(A, diag = FALSE), 1, rev)
> mask
      [,1]  [,2]  [,3]  [,4]
[1,] FALSE FALSE FALSE FALSE
[2,] FALSE FALSE FALSE  TRUE
[3,] FALSE FALSE  TRUE  TRUE
[4,] FALSE  TRUE  TRUE  TRUE

Multiply this mask and calculate sums:

> A * mask
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]    0    0    0   14
[3,]    0    0   11   15
[4,]    0    8   12   16

>  rowSums(A * mask)
[1]  0 14 26 36


问:
libgdx- padding didn't solve black lines on tilemap
I read all the million posts about the problem with black lines shown on screen when rendering tilemaps on libgdx. All the solutions talk about add padding to the tile sets. So I did it, but it didn't solved the problem.
I think maybe I didn't understand it well, so I will post here the process I'm doing, and I will be glad if someone can point out my mistake, if any:

This is an image of my initial tile set:

This is an image of my tile set after adding padding using GIMP plugin which was suggested from this post:

Then in Tiled, I add this tileset and set Margin to 1px and Spacing to 2px like written in this post.

Now as I understand the problem should be solved, but still when I run the program I get:

I can add code parts if you want, but there is really nothing special the way I render my map- just load it with TmxMapLoader and render with MapRenderer (using camera also, of course, otherwise the problem wouldn't appear).

答:
Load your maps like this: </p>

```<code>TmxMapLoader.Parameters() params = new TmxMapLoader.Parameters();
params.generateMipMaps = true;

TmxMapLoader mapLoader = new TmxMapLoader();
TiledMap map = mapLoader.load("pathToMap", params);
</code>```

Body:
Load your maps like this:

TmxMapLoader.Parameters() params = new TmxMapLoader.Parameters();
params.generateMipMaps = true;

TmxMapLoader mapLoader = new TmxMapLoader();
TiledMap map = mapLoader.load("pathToMap", params);


答:
Yeah it's possible. but in that case, you must correct like this: </p>

```<code>{% block page %}
    <ul class="gallery">
      {% set foo = 0 %}
      {% for products in prodArr %}
          {% if foo % 4 == 0 %}
              **<ul class="slides">**
          {% endif %}

          <li>Product</li>

          {% if foo % 4 == 3 or foo == (prodArr|length - 1) %}
              **</ul>**
          {% endif %}

     {% set foo = foo + 1 %}
     {% endfor %}
    </ul>
    {% endblock %}
</code>```

Title: Does Twig have equivalent 'append'?

Body:
Yeah it's possible. but in that case, you must correct like this:

{% block page %}
    <ul class="gallery">
      {% set foo = 0 %}
      {% for products in prodArr %}
          {% if foo % 4 == 0 %}
              **<ul class="slides">**
          {% endif %}

          <li>Product</li>

          {% if foo % 4 == 3 or foo == (prodArr|length - 1) %}
              **</ul>**
          {% endif %}

     {% set foo = foo + 1 %}
     {% endfor %}
    </ul>
    {% endblock %}


问:
Functional programming in Python: find smallest odd number in list

How can I find the smallest odd number in a list of integers, if the problem statement says that I can't use for and if?

答:
You can use filter and min:

```<code>s = [4, 2, 3, 4, 7, 1]
smallest_odd = min(filter(lambda x:x%2 != 0, s))
</code>```

Output:

```<code>1
</code>```

Body:
You can use filter and min:

s = [4, 2, 3, 4, 7, 1]
smallest_odd = min(filter(lambda x:x%2 != 0, s))

Output:

1


问:
CSS Grid - auto column height
The cart form is stretching vertically and the thumbs are positioning in the bottom left corner, when I'd like them to sit directly under the cart form like so:

.product-page--main-content {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: auto 1fr auto;
}

.product-page--main-content>* {
  padding: 50px 100px;
  border: 1px solid #ccc;
}

.product-page--cart-form-block {
  grid-row: 2;
}

.product-page--thumbs {
  grid-row: 3;
}

.product-page--images {
  grid-column: span 2;
  grid-row: span 3;
  height: 400px;
}

.product-page--description {
  grid-row: span 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="product-page--main-content">
  <div class="product-page--title-n-vendor">Title</div>
  <div class="product-page--cart-form-block">Cart form</div>
  <div class="product-page--thumbs">Thumbs</div>
  <div class="product-page--images">Images</div>
  <div class="product-page--description">Description</div>
</div></code>```

Codepen: https://codepen.io/paulmason/pen/rYXyYW

答:
The code you have is working perfectly, as written.

Your image grid item is set to height: 400px.

```<code>.product-page--images {
    grid-column: span 2;
    grid-row: span 3;
    height: 400px;
}
</code>```

Then you have 50px in top and bottom padding.

```<code>.product-page--main-content > * {
    padding: 50px 100px;
    border: 1px solid #ccc;
}
</code>```

So the image grid item is 500px tall, in a row set to 1fr, in a grid with three rows. It all works perfectly, as specified.

Maybe what you want is four rows:

.product-page--main-content {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  /* grid-template-rows: auto 1fr auto; */ /* now defaults to grid-auto-rows: auto */
}
.product-page--main-content > * {
  padding: 50px 100px;
  border: 1px solid #ccc;
}

.product-page--cart-form-block {
  grid-row: 2;
}

.product-page--thumbs {
  grid-row: 3;
}

.product-page--images {
  grid-column: span 2;
  grid-row: span 4;            /* changed from 3 */
  height: 400px;
}

.product-page--description {
  grid-row: span 4;            /* changed from 3 */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="product-page--main-content">
  <div class="product-page--title-n-vendor">Title</div>
  <div class="product-page--cart-form-block">Cart form</div>
  <div class="product-page--thumbs">Thumbs</div>
  <div class="product-page--images">Images</div>
  <div class="product-page--description">Description</div>
</div></code>```

Title: CSS Grid - auto column height

Body:
The cart form is stretching vertically and the thumbs are positioning in the bottom left corner, when I'd like them to sit directly under the cart form like so:

.product-page--main-content {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: auto 1fr auto;
}

.product-page--main-content>* {
  padding: 50px 100px;
  border: 1px solid #ccc;
}

.product-page--cart-form-block {
  grid-row: 2;
}

.product-page--thumbs {
  grid-row: 3;
}

.product-page--images {
  grid-column: span 2;
  grid-row: span 3;
  height: 400px;
}

.product-page--description {
  grid-row: span 3;
}

Title

Cart form

Thumbs

Images

Description

Codepen: https://codepen.io/paulmason/pen/rYXyYW

Body:
The code you have is working perfectly, as written.

Your image grid item is set to height: 400px.

.product-page--images {
    grid-column: span 2;
    grid-row: span 3;
    height: 400px;
}

Then you have 50px in top and bottom padding.

.product-page--main-content > * {
    padding: 50px 100px;
    border: 1px solid #ccc;
}

So the image grid item is 500px tall, in a row set to 1fr, in a grid with three rows. It all works perfectly, as specified.

Maybe what you want is four rows:

.product-page--main-content {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  /* grid-template-rows: auto 1fr auto; */ /* now defaults to grid-auto-rows: auto */
}
.product-page--main-content > * {
  padding: 50px 100px;
  border: 1px solid #ccc;
}

.product-page--cart-form-block {
  grid-row: 2;
}

.product-page--thumbs {
  grid-row: 3;
}

.product-page--images {
  grid-column: span 2;
  grid-row: span 4;            /* changed from 3 */
  height: 400px;
}

.product-page--description {
  grid-row: span 4;            /* changed from 3 */
}

<div class="product-page--main-content">
  <div class="product-page--title-n-vendor">Title</div>
  <div class="product-page--cart-form-block">Cart form</div>
  <div class="product-page--thumbs">Thumbs</div>
  <div class="product-page--images">Images</div>
  <div class="product-page--description">Description</div>
</div>


问:
How to make uiscrollview only vertical scrolling for ios?
I'm trying to make layout inside scrollview using this one tutorial link

And get the following result link

It will be appreciated for any advices or tutorial links. It needs only vertical scrolling

答:
This is because scroll view have no idea where your content should end.

But when at least one item inside your scroll view has its "trailing space" constraint attached to a view outside the scroll view (usually a view the scroll view is sitting in or some other view of a higher level, which "knows" its width) - the scroll view will automatically get an idea about your wanted width and won't scroll horizontally (unless that trailing constraint implies having your content outside the screen).

Better if all items inside scroll view have their "trailing space" constraints connected either to each other or to a view outside the scroll view. But not the scroll view itself.

No additional code or extra constraints needed for this to work.

ContentLicense: CC BY-SA 4.0


问:
org.springframework.amqp.AmqpIllegalStateException: No 'queue' specified. Check configuration of RabbitTemplate
I am making an application that reads messages from rabbitmq and writes into oracle database. I used spring boot batch to read messages, but it ends with the error "No 'queue' specified. Check configuration of RabbitTemplate."

RabbitConfig.java

```<code>@Configuration
public class RabbitMQConfig {

//  @Value("${conveh.rabbitmq.queue}")
    public String queueName ="hello2";

//  @Value("${conveh.rabbitmq.exchange}")
    public String exchange="hello_exchage2";

    @Bean
    public Queue queue() {
        return new Queue(queueName, false);
    }

    @Bean
    public TopicExchange exchange() {
        return new TopicExchange(exchange);
    }

    @Bean
    public Binding binding(Queue queue, TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(queueName);
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public AmqpTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setQueue(queueName);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }

    @Bean
    public ConnectionFactory connectionFactory() {

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost("host");
        connectionFactory.setPort(123);
        connectionFactory.setVirtualHost("/xxx");
        connectionFactory.setUsername("xxx");
        connectionFactory.setPassword("xxx");
        return connectionFactory;
    }
}
</code>```

BatchConfig.java

```<code>@Configuration
@EnableBatchProcessing
public class BatchMqListener {
//  private final Logger logger = LoggerFactory.getLogger(ImportJobConfig.class);

      @Autowired
      JobBuilderFactory jobBuilderFactory;
      @Autowired
      StepBuilderFactory stepBuilderFactory;
      @Autowired
      RabbitTemplate rabbitTemplate;

      @Bean
      public Job importJob() {
        return jobBuilderFactory.get("importJob")
            .listener(new JobExecutionListener() {
              @Override
              public void beforeJob(JobExecution jobExecution) {
//              logger.info("Ready to start the job");
                  System.out.println("Ready to start the job");
              }

              @Override
              public void afterJob(JobExecution jobExecution) {
//              logger.info("Job successfully executed.");
                  System.out.println("Job successfully executed.");
              }
            })
            .incrementer(new RunIdIncrementer())
            .flow(stepBuilderFactory.get("importStep")
                .<VehicleEvent, VehicleEvent>chunk(2)
                .reader(new AmqpItemReader<>(rabbitTemplate))
                .listener(new QueueListener<VehicleEvent>())
                .processor(customProcessor())
                .writer(writer())
                .build())
            .end()
            .build();
      }

      public ItemProcessor<VehicleEvent, VehicleEvent> customProcessor(){
          return null;
      }

      @Bean
      public FlatFileItemWriter<VehicleEvent> writer() {
//      log.info("writer called");
        FlatFileItemWriter<VehicleEvent> writer = new FlatFileItemWriter<>();
        writer.setResource(new FileSystemResource("output/item.all.csv"));
        writer.setAppendAllowed(true);
        writer.setLineAggregator(new DelimitedLineAggregator<VehicleEvent>() {{
          setDelimiter(",");
          setFieldExtractor(new BeanWrapperFieldExtractor<VehicleEvent>() {{
            setNames(new String[]{"id", "itemName"});
          }});
        }});
        return writer;
      }
}
</code>```

what I am missing to give the queue name properly.

答:
I used wrong return type for rabbitTemplate() method. It should be RabbitTemplate.

```<code> @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setQueue(queueName);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }
</code>```

Body:
I am making an application that reads messages from rabbitmq and writes into oracle database. I used spring boot batch to read messages, but it ends with the error "No 'queue' specified. Check configuration of RabbitTemplate."

RabbitConfig.java

@Configuration
public class RabbitMQConfig {

//  @Value("${conveh.rabbitmq.queue}")
    public String queueName ="hello2";

//  @Value("${conveh.rabbitmq.exchange}")
    public String exchange="hello_exchage2";

    @Bean
    public Queue queue() {
        return new Queue(queueName, false);
    }

    @Bean
    public TopicExchange exchange() {
        return new TopicExchange(exchange);
    }

    @Bean
    public Binding binding(Queue queue, TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(queueName);
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public AmqpTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setQueue(queueName);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }

    @Bean
    public ConnectionFactory connectionFactory() {

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost("host");
        connectionFactory.setPort(123);
        connectionFactory.setVirtualHost("/xxx");
        connectionFactory.setUsername("xxx");
        connectionFactory.setPassword("xxx");
        return connectionFactory;
    }
}

BatchConfig.java

@Configuration
@EnableBatchProcessing
public class BatchMqListener {
//  private final Logger logger = LoggerFactory.getLogger(ImportJobConfig.class);

      @Autowired
      JobBuilderFactory jobBuilderFactory;
      @Autowired
      StepBuilderFactory stepBuilderFactory;
      @Autowired
      RabbitTemplate rabbitTemplate;

      @Bean
      public Job importJob() {
        return jobBuilderFactory.get("importJob")
            .listener(new JobExecutionListener() {
              @Override
              public void beforeJob(JobExecution jobExecution) {
//              logger.info("Ready to start the job");
                  System.out.println("Ready to start the job");
              }

              @Override
              public void afterJob(JobExecution jobExecution) {
//              logger.info("Job successfully executed.");
                  System.out.println("Job successfully executed.");
              }
            })
            .incrementer(new RunIdIncrementer())
            .flow(stepBuilderFactory.get("importStep")
                .<VehicleEvent, VehicleEvent>chunk(2)
                .reader(new AmqpItemReader<>(rabbitTemplate))
                .listener(new QueueListener<VehicleEvent>())
                .processor(customProcessor())
                .writer(writer())
                .build())
            .end()
            .build();
      }

      public ItemProcessor<VehicleEvent, VehicleEvent> customProcessor(){
          return null;
      }

      @Bean
      public FlatFileItemWriter<VehicleEvent> writer() {
//      log.info("writer called");
        FlatFileItemWriter<VehicleEvent> writer = new FlatFileItemWriter<>();
        writer.setResource(new FileSystemResource("output/item.all.csv"));
        writer.setAppendAllowed(true);
        writer.setLineAggregator(new DelimitedLineAggregator<VehicleEvent>() {{
          setDelimiter(",");
          setFieldExtractor(new BeanWrapperFieldExtractor<VehicleEvent>() {{
            setNames(new String[]{"id", "itemName"});
          }});
        }});
        return writer;
      }
}

what I am missing to give the queue name properly.

Body:
I used wrong return type for rabbitTemplate() method. It should be RabbitTemplate.

 @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setQueue(queueName);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }


问:
Error dropdown materialize using .dropdown() - $ is not a function
I am triying to install a dropdown in materialize using instructions but when ran the code console throw me an error

This is the code

//main.js
$(()=>{
 alert("Hola de nuevo! Ahora con Materialize")
 console.log('Main cargando')
  $('.dropdown-button').dropdown();

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Ejs Test</title>
 <link rel="stylesheet" href="css/materialize.css">
 <link rel="stylesheet" href="css/materialize.min.css">

 <script src="js/materialize.min.js"></script>
 <script src="js/jquery.js"></script>
 <script src="js/main.js"></script>

</head>
<body>

 <ul class="dropdown-content" id="dropdown1">
  <li>TextoPrueba</li>
  <li>TextoPrueba</li>
  <li>TextoPrueba</li>
 </ul>
 <div class="navbar-fixed">
  <nav>
   <div class="nav-wrapper">
    BrandLogo
    <ul class="right hide-on-med-and-down">
     <li>Texto1</li>
     <li>Texto2</li>
     <li>Texto3</li>
     <li>TextoDropDown</li>
    </ul>
   </div>
  </nav>
 </div>
</body>
</html></code>```

in the  console of the code inspector throw me

Uncaught TypeError: $(...).dropdown is not a function

what can i do to show the dropdown correctly?

答:
jQuery initialization for dropdowns is only necessary if you create them dynamically.

This should be enough:

  Drop Me!

one

two

three

view_modulefour

cloudfive

```

Body:
I am triying to install a dropdown in materialize using instructions but when ran the code console throw me an error

This is the code

//main.js
$(()=>{
 alert("Hola de nuevo! Ahora con Materialize")
 console.log('Main cargando')
  $('.dropdown-button').dropdown();

})

<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Ejs Test</title>
 <link rel="stylesheet" href="css/materialize.css">
 <link rel="stylesheet" href="css/materialize.min.css">

TextoPrueba

TextoPrueba

TextoPrueba

    BrandLogo

Texto1

Texto2

Texto3

TextoDropDown

in the  console of the code inspector throw me

Uncaught TypeError: $(...).dropdown is not a function

what can i do to show the dropdown correctly?

Body:
jQuery initialization for dropdowns is only necessary if you create them dynamically.

This should be enough:

<!-- Dropdown Trigger -->
  <a class='dropdown-button btn' href='#' data-activates='dropdown1'>Drop Me!</a>

  <!-- Dropdown Structure -->
  <ul id='dropdown1' class='dropdown-content'>
    <li><a href="#!">one</a></li>
    <li><a href="#!">two</a></li>
    <li class="divider"></li>
    <li><a href="#!">three</a></li>
    <li><a href="#!"><i class="material-icons">view_module</i>four</a></li>
    <li><a href="#!"><i class="material-icons">cloud</i>five</a></li>
  </ul>


问:
I need to change the stroke color to a user defined color. Nothing to do with the state
I need to change the stroke color from the app.  The user is able to change the background color so I need to also let them change the stroke (outline) of the button. As its is already set in the drawable (sample below) I have not found a way to change this. Seems like all of the other questions like this just said to use the XML file.... but that doesnt let me make it dynamic.  Thank you for any help!

I need to change the stroke color to a user defined color.  Nothing to do with the state.

```<code><?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="#ffffffff"/>
      <stroke
                android:width="3dp"
                android:color="@color/Dim_Gray" />  <<<<--- This is what I need to change

    <padding android:left="10dp"
             android:top="10dp"
             android:right="10dp"
             android:bottom="10dp"
             />

    <corners android:bottomRightRadius="12dp" android:bottomLeftRadius="12dp"
     android:topLeftRadius="12dp" android:topRightRadius="12dp"/>

</shape>
</code>```

答:
Try using StateLists (as opposed to ColorStateList). Take a look:
http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

You can also create a ShapeDrawable (or a RoundRectShape in your example) programmatically, and then call the button's setBackgroundDrawable

Body:
I need to change the stroke color from the app.  The user is able to change the background color so I need to also let them change the stroke (outline) of the button. As its is already set in the drawable (sample below) I have not found a way to change this. Seems like all of the other questions like this just said to use the XML file.... but that doesnt let me make it dynamic.  Thank you for any help!

I need to change the stroke color to a user defined color.  Nothing to do with the state.

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="#ffffffff"/>
      <stroke
                android:width="3dp"
                android:color="@color/Dim_Gray" />  <<<<--- This is what I need to change

    <padding android:left="10dp"
             android:top="10dp"
             android:right="10dp"
             android:bottom="10dp"
             />

    <corners android:bottomRightRadius="12dp" android:bottomLeftRadius="12dp"
     android:topLeftRadius="12dp" android:topRightRadius="12dp"/>

</shape>


问:
How to handle Promise.all properly: Getting undefined
I'm trying to get an array filled with the info back from some requests made to different REST APIs.
I thought about using Promise.all to do that but for some reason, it yields an Array with a bunch of undefined inside.

[ undefined, undefined, undefined, undefined ]

Here's my code:

```<code>var _ = require("lodash");//Used exclusively to check if the result from the request is an object
var ccxt = require("ccxt");//External library used to make the requests

let pairs = ["ETH/EUR", "BTC/EUR", "LTC/EUR", "BCH/EUR"]; //Array on which the Promise.all is based

function test(p) {
  for (var i = 0; i < ccxt.exchanges.length; i++) { //Looping through all the rest APIs
    let exchange = new ccxt[ccxt.exchanges[i]](); //Defining each API to make the requests
    if (exchange.hasFetchOrderBook) {
      exchange //Beginning of the request
        .fetchOrderBook(p)
        .then(order => {
          if (_.isObject(order) && order.bids[0][1]) {
            let now = Math.floor(new Date());
            order.mkt = exchange.name;
            order.pair = p;
            order.ping = now - order.timestamp;
            return order; //Return the result of the request
          }
        })
        .catch(e => {});
    }
  }
}

Promise.all(pairs.map(test)) //Making the requests based on the Pairs Array
  .then(res => {
    console.log(res); //Logging the results ==> [undefined, undefined, undefined, undefined] for some reason...
  })
  .catch(e => {
    console.log(e);
  });
</code>```

I know that the requests are correctly being made since if I console.log the order within the loop, I get the correct results -- Example of the result when logging:

```<code>{ bids:
   [ [ 12009.52, 0.0468 ],
     [ 12008.5, 0.0227 ],
     [ 12007.48, 30.9321 ],
     [ 12006.46, 0.0537 ],
     [ 12005.45, 0.0157 ],
     [ 12004.43, 7.1659 ],
     [ 12003.41, 0.0164 ],
     [ 12002.39, 23.4159 ],
     [ 12001.38, 0.0284 ],
     [ 12000.36, 0.0132 ],
     [ 11999.34, 0.0194 ],
     [ 11998.33, 0.0034 ],
     [ 11997.31, 7.526 ],
     [ 2445.72, 34.075 ],
     [ 2445.17, 25.4842 ],
     [ 2444.96, 0.1118 ],
     [ 2444.75, 23.288 ],
     [ 2444, 0.0247 ],
     [ 2443.8, 0.192 ],
     [ 765.51, 0.0828 ] ],
  asks:
   [ [ 12048.74, 2.523 ],
     [ 12049.77, 0.0159 ],
     [ 12050.79, 0.029 ],
     [ 12051.82, 0.0061 ],
     [ 12052.84, 0.0181 ],
     [ 12053.87, 0.0164 ],
     [ 12054.89, 0.0355 ],
     [ 12055.92, 0.0042 ],
     [ 13419.62, 0.0063 ],
     [ 13420.64, 0.0174 ],
     [ 13421.78, 0.0143 ],
     [ 13422.92, 0.026 ],
     [ 13424.06, 0.0055 ],
     [ 13425.2, 14.4552 ],
     [ 13426.23, 0.0065 ],
     [ 13427.25, 0.0057 ],
     [ 13428.39, 0.0147 ],
     [ 13429.53, 4.0375 ],
     [ 13430.56, 23.9541 ],
     [ 13431.58, 0.0137 ] ],
  timestamp: 1512845715447,
  datetime: '2017-12-09T18:55:15.447Z',
  mkt: 'LakeBTC',
  pair: 'BTC/EUR',
  ping: 0 }
</code>```

So I guess that the problems I'm dealing with has to do with the asynchronous character of the function... but I'm not sure how I can make it synchronous.
Again, just to try to clarify my question: The objective is to get an array with 4 different types of object (one per pair --> array) so that I can operate on each.
Just to make it clearer, here's an illustration of what I'm trying to achieve:

```<code>[
  [
    Object1,
    Object2,
    Object3,
    etc...
  ],
  [
    Object1,
    Object2,
    Object3,
    etc...
  ],
  [
    Object1,
    Object2,
    Object3,
    etc...
  ],
  [
    Object1,
    Object2,
    Object3,
    etc...
  ]
]
</code>```

Why is Promise.all returning the array without waiting on the requests'results?

I hope that was clear enough! If not let mw know! :P

Thanks in advance for your help!

答:
Your test function does return a undefined. You need to return a promise for the result:

```<code>function test(p) {
  return Promise.all(ccxt.exchanges.map(api => { //Looping through all the rest APIs
//^^^^^^^^^^^^^^^^^^
    let exchange = new ccxt[api](); //Defining each API to make the requests
    if (exchange.hasFetchOrderBook) {
      return exchange //Beginning of the request
        .fetchOrderBook(p)
        .then(order => {
          if (_.isObject(order) && order.bids[0][1]) {
            let now = Math.floor(new Date());
            order.mkt = exchange.name;
            order.pair = p;
            order.ping = now - order.timestamp;
            return order; //Return the result of the request
          }
          // else undefined
        })
        .catch(e => {}); // undefined
    }
    // else undefined
  }));
}
</code>```

Of course your promises still fulfill with undefined when the if conditions do not apply or an error happens.

Body:
I'm trying to get an array filled with the info back from some requests made to different REST APIs.
I thought about using Promise.all to do that but for some reason, it yields an Array with a bunch of undefined inside.

[ undefined, undefined, undefined, undefined ]

Here's my code:

var _ = require("lodash");//Used exclusively to check if the result from the request is an object
var ccxt = require("ccxt");//External library used to make the requests

let pairs = ["ETH/EUR", "BTC/EUR", "LTC/EUR", "BCH/EUR"]; //Array on which the Promise.all is based

function test(p) {
  for (var i = 0; i < ccxt.exchanges.length; i++) { //Looping through all the rest APIs
    let exchange = new ccxt[ccxt.exchanges[i]](); //Defining each API to make the requests
    if (exchange.hasFetchOrderBook) {
      exchange //Beginning of the request
        .fetchOrderBook(p)
        .then(order => {
          if (_.isObject(order) && order.bids[0][1]) {
            let now = Math.floor(new Date());
            order.mkt = exchange.name;
            order.pair = p;
            order.ping = now - order.timestamp;
            return order; //Return the result of the request
          }
        })
        .catch(e => {});
    }
  }
}

Promise.all(pairs.map(test)) //Making the requests based on the Pairs Array
  .then(res => {
    console.log(res); //Logging the results ==> [undefined, undefined, undefined, undefined] for some reason...
  })
  .catch(e => {
    console.log(e);
  });

I know that the requests are correctly being made since if I console.log the order within the loop, I get the correct results -- Example of the result when logging:

{ bids:
   [ [ 12009.52, 0.0468 ],
     [ 12008.5, 0.0227 ],
     [ 12007.48, 30.9321 ],
     [ 12006.46, 0.0537 ],
     [ 12005.45, 0.0157 ],
     [ 12004.43, 7.1659 ],
     [ 12003.41, 0.0164 ],
     [ 12002.39, 23.4159 ],
     [ 12001.38, 0.0284 ],
     [ 12000.36, 0.0132 ],
     [ 11999.34, 0.0194 ],
     [ 11998.33, 0.0034 ],
     [ 11997.31, 7.526 ],
     [ 2445.72, 34.075 ],
     [ 2445.17, 25.4842 ],
     [ 2444.96, 0.1118 ],
     [ 2444.75, 23.288 ],
     [ 2444, 0.0247 ],
     [ 2443.8, 0.192 ],
     [ 765.51, 0.0828 ] ],
  asks:
   [ [ 12048.74, 2.523 ],
     [ 12049.77, 0.0159 ],
     [ 12050.79, 0.029 ],
     [ 12051.82, 0.0061 ],
     [ 12052.84, 0.0181 ],
     [ 12053.87, 0.0164 ],
     [ 12054.89, 0.0355 ],
     [ 12055.92, 0.0042 ],
     [ 13419.62, 0.0063 ],
     [ 13420.64, 0.0174 ],
     [ 13421.78, 0.0143 ],
     [ 13422.92, 0.026 ],
     [ 13424.06, 0.0055 ],
     [ 13425.2, 14.4552 ],
     [ 13426.23, 0.0065 ],
     [ 13427.25, 0.0057 ],
     [ 13428.39, 0.0147 ],
     [ 13429.53, 4.0375 ],
     [ 13430.56, 23.9541 ],
     [ 13431.58, 0.0137 ] ],
  timestamp: 1512845715447,
  datetime: '2017-12-09T18:55:15.447Z',
  mkt: 'LakeBTC',
  pair: 'BTC/EUR',
  ping: 0 }

So I guess that the problems I'm dealing with has to do with the asynchronous character of the function... but I'm not sure how I can make it synchronous.
Again, just to try to clarify my question: The objective is to get an array with 4 different types of object (one per pair --> array) so that I can operate on each.
Just to make it clearer, here's an illustration of what I'm trying to achieve:

[
  [
    Object1,
    Object2,
    Object3,
    etc...
  ],
  [
    Object1,
    Object2,
    Object3,
    etc...
  ],
  [
    Object1,
    Object2,
    Object3,
    etc...
  ],
  [
    Object1,
    Object2,
    Object3,
    etc...
  ]
]

Why is Promise.all returning the array without waiting on the requests'results?

I hope that was clear enough! If not let mw know! :P

Thanks in advance for your help!

Body:
Your test function does return a undefined. You need to return a promise for the result:

function test(p) {
  return Promise.all(ccxt.exchanges.map(api => { //Looping through all the rest APIs
//^^^^^^^^^^^^^^^^^^
    let exchange = new ccxt[api](); //Defining each API to make the requests
    if (exchange.hasFetchOrderBook) {
      return exchange //Beginning of the request
        .fetchOrderBook(p)
        .then(order => {
          if (_.isObject(order) && order.bids[0][1]) {
            let now = Math.floor(new Date());
            order.mkt = exchange.name;
            order.pair = p;
            order.ping = now - order.timestamp;
            return order; //Return the result of the request
          }
          // else undefined
        })
        .catch(e => {}); // undefined
    }
    // else undefined
  }));
}

Of course your promises still fulfill with undefined when the if conditions do not apply or an error happens.


问:
SQL Server : extract domain and params from 1 million rows into temp table
I have just over a million rows or Urls in one column. The column name is [url] and the table name is redirects.

I'm running SQL Server 2014.

I need a way to extract the sub domain for each url into a new column in a temp table.

Ideally at the same type select distinct param names for the query string into another column and the param values into another column

My main concern is performance not locking up the server while looping through a million rows.

I would be happy to run 3 queries to get the results if it makes more sense

Examples of the column data:

```<code>https://www.google.com/ads/ga-audiences?v=1&aip=1&t=sr&_r=4&tid=UA-9999999-1&cid=9999107657.199999834&jid=472999996&_v=j66&z=1963999907

https://track.kspring.com/livin-like-a-star#pid=370&cid=6546&sid=front
</code>```

So I end up with 3 columns in a temp table

```<code>URL               | Param | Qstring
------------------+-------+----------
www.google.com        | v     | 1
www.google.com        | aip   | 1
www.google.com        | t     | dc
www.google.com        | tid   | UA-1666666-1
www.google.com        | jid   | 472999996
track.kspring.com | pid   | 370
track.kspring.com | cid   | 6546
track.kspring.com | sid   | front
</code>```

I've been looking at some examples to extract the domain name from a string but I don't have much experience with regex or string manipulation.

答: This is the kind of processing at which .Net CLR functions excel. Just use Uri and parse away, from a CLR Table Value Function (so that you can output more than one column in one single call).

Body:
I have just over a million rows or Urls in one column. The column name is [url] and the table name is redirects.

I'm running SQL Server 2014.

I need a way to extract the sub domain for each url into a new column in a temp table.

Ideally at the same type select distinct param names for the query string into another column and the param values into another column

My main concern is performance not locking up the server while looping through a million rows.

I would be happy to run 3 queries to get the results if it makes more sense

Examples of the column data:

https://www.google.com/ads/ga-audiences?v=1&aip=1&t=sr&_r=4&tid=UA-9999999-1&cid=9999107657.199999834&jid=472999996&_v=j66&z=1963999907

https://track.kspring.com/livin-like-a-star#pid=370&cid=6546&sid=front

So I end up with 3 columns in a temp table

URL               | Param | Qstring
------------------+-------+----------
www.google.com        | v     | 1
www.google.com        | aip   | 1
www.google.com        | t     | dc
www.google.com        | tid   | UA-1666666-1
www.google.com        | jid   | 472999996
track.kspring.com | pid   | 370
track.kspring.com | cid   | 6546
track.kspring.com | sid   | front

I've been looking at some examples to extract the domain name from a string but I don't have much experience with regex or string manipulation.


问:
How to send SMS to multiple people in objective c using Twilio?
I can send sms to one person using following code with twilio api in iOS.

```<code>NSString *kTwilioSID = TWILIO_SID;
NSString *kTwilioSecret = TWILIO_SECRET;
NSString *kFromNumber = TWILIO_FROM_NUMBER;
NSString *kToNumber = TO_NUMBER;
NSString *kMessage = TWILIO_MESSAGE_HEADER;

NSString *urlString = [NSString
                       stringWithFormat:@"https://%@:%@@api.twilio.com/2010-04-01/Accounts/%@/SMS/Messages/",
                       kTwilioSID, kTwilioSecret,kTwilioSID];

NSDictionary*
dic = @{@"From":kFromNumber,@"To":kToNumber,@"Body":kMessage};

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"application/xml"];
[manager POST:urlString parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject)
 {
 } failure:^(AFHTTPRequestOperation *operation, NSError *error)
 {
 }];
</code>```

Then I want to send sms to multiple people.
How can I do it?

答:
You are not supposed to embed your API secret (kTwilioSecret) in a client application, because unless you implement SSL certificate pinning, an attacker routing their device to a proxy could easily obtain your API credentials (including the secret) and send messages with your account.

This is why their iOS client SDK does not support sending SMS. Your app should talk to your backend (where your API secret is safe), which should handle the logic for allowing the SMS's to be sent and then sending them through Twilio.

Make sure you are aware that Twilio uses Rate-Limiting, so you can't send many messages at once from the same number. Short codes are subject to different rules though, but they are more expensive.

Now what you can do is implement some routine that manages rate limiting by only sending as many messages as Twilio allows you to in a given period of time, and/or using many numbers at once, on your backend.
(Or from iOS but I would discourage going with that, for the security issues mentioned above).

Body:
I can send sms to one person using following code with twilio api in iOS.

NSString *kTwilioSID = TWILIO_SID;
NSString *kTwilioSecret = TWILIO_SECRET;
NSString *kFromNumber = TWILIO_FROM_NUMBER;
NSString *kToNumber = TO_NUMBER;
NSString *kMessage = TWILIO_MESSAGE_HEADER;

NSString *urlString = [NSString
                       stringWithFormat:@"https://%@:%@@api.twilio.com/2010-04-01/Accounts/%@/SMS/Messages/",
                       kTwilioSID, kTwilioSecret,kTwilioSID];

NSDictionary*
dic = @{@"From":kFromNumber,@"To":kToNumber,@"Body":kMessage};

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"application/xml"];
[manager POST:urlString parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject)
 {
 } failure:^(AFHTTPRequestOperation *operation, NSError *error)
 {
 }];

Then I want to send sms to multiple people.
How can I do it?


问:
Post json to django rest framework API with jquery-ajax not working
i have the models:

```<code>class Publicacion(models.Model):
    usuario = models.ForeignKey(User)
    fecha = models.DateField(auto_now_add=True)

class Estado(models.Model):
    publicacion = models.OneToOneField(Publicacion, on_delete=models.CASCADE)
    texto = models.TextField()
    imagen = models.ImageField(upload_to='estados', blank=True, null=True)
</code>```

so my json should be like

{
    "estado": {
        "texto": "",
        "imagen": image
    }
}

my jquery ajax is

```<code>$$.ajax({
    beforeSend: function(request) {
        request.setRequestHeader("Authorization", "Token " + token);
    },
    url: "url",
    dataType: 'JSON',
    type: 'POST',
    data: JSON.stringify({"estado":{"texto": "text", "imagen": dataImg}}),
    success: function (data) {
        myApp.alert("Correcto");
    },
    error: function (xhr, ajaxOptions, thrownError) {
        console.log(xhr);
    }
});
</code>```

but when i send it with i have a 400 bad request response, server says that "estado" is required, any idea what's the problem?

答:
You do not have to explicitly set the content_type parameter, if you let jquery handle it you can send the back end a normal assoc array and it will work fine

```<code>$.ajax("domain/end_point",{
    type: "POST",
    data : {"details": "my assoc data"},
    crossDomain: true,
    // contentType: "application/json; charset=utf-8",
    dataType: "json"
});
</code>```

Body:
i have the models:

class Publicacion(models.Model):
    usuario = models.ForeignKey(User)
    fecha = models.DateField(auto_now_add=True)

class Estado(models.Model):
    publicacion = models.OneToOneField(Publicacion, on_delete=models.CASCADE)
    texto = models.TextField()
    imagen = models.ImageField(upload_to='estados', blank=True, null=True)

so my json should be like

{
    "estado": {
        "texto": "",
        "imagen": image
    }
}

my jquery ajax is

$$.ajax({
    beforeSend: function(request) {
        request.setRequestHeader("Authorization", "Token " + token);
    },
    url: "url",
    dataType: 'JSON',
    type: 'POST',
    data: JSON.stringify({"estado":{"texto": "text", "imagen": dataImg}}),
    success: function (data) {
        myApp.alert("Correcto");
    },
    error: function (xhr, ajaxOptions, thrownError) {
        console.log(xhr);
    }
});

but when i send it with i have a 400 bad request response, server says that "estado" is required, any idea what's the problem?

Body:
You do not have to explicitly set the content_type parameter, if you let jquery handle it you can send the back end a normal assoc array and it will work fine

$.ajax("domain/end_point",{
    type: "POST",
    data : {"details": "my assoc data"},
    crossDomain: true,
    // contentType: "application/json; charset=utf-8",
    dataType: "json"
});


问:
Cygwin user permissions for sftp (Operation not permitted)
So, I installed Cygwin 1.7.17 on Win7, I used mkpasswd to bring in a domain user (my main admin account). I used mkpasswd again to bring in a local account I created called "ffftp".

```<code>mkpasswd -d -u administrator > /etc/passwd
mkpasswd -l -u ffftp >> /etc/passwd
</code>```

I used mkgroup to bring in all the necessary windows groups.

I can type

```<code>$ login
user: ffftp
password: mypassword
</code>```

And it logs in... but it says this:

```<code>Last login: Tue Apr 16 11:36:49 on pty0
login: no shell: /bin/bash: Operation not permitted
</code>```

The local user ffftp is just a regular "User" group in windows.

The SID for ffftp starts with S-1-5-21.

I've already created a cygwin/home/ffftp

And set its permissions in windows.

How can I possibly set the private key for "ffftp", if I cannot login to that user?? What am I missing???

Also if anyone has a guide on setting up AES encryption with cygwin sshd that would be greatly appreciated.

答:
I spent a lot of time trying to solve the same problem. Accidentally stumbled upon a solution here:

https://cygwin.com/ml/cygwin/2015-08/msg00162.html

On cygwin server:

Go to Control Panel > Administrative Tools.

Select Local Security Policy > Local Policies > User Rights Assignment.

Right-click Replace a Process Level Token and select Security or Properties.

Click Add to add the account sshd is running on. ( cyg_server in my case )

gpupdate

Restart sshd service

Now try to connect via ssh ...
I was successful

Body:
So, I installed Cygwin 1.7.17 on Win7, I used mkpasswd to bring in a domain user (my main admin account). I used mkpasswd again to bring in a local account I created called "ffftp".

mkpasswd -d -u administrator > /etc/passwd
mkpasswd -l -u ffftp >> /etc/passwd

I used mkgroup to bring in all the necessary windows groups.

I can type

$ login
user: ffftp
password: mypassword

And it logs in... but it says this:

Last login: Tue Apr 16 11:36:49 on pty0
login: no shell: /bin/bash: Operation not permitted

The local user ffftp is just a regular "User" group in windows.

The SID for ffftp starts with S-1-5-21.

I've already created a cygwin/home/ffftp

And set its permissions in windows.

How can I possibly set the private key for "ffftp", if I cannot login to that user?? What am I missing???

Also if anyone has a guide on setting up AES encryption with cygwin sshd that would be greatly appreciated.


答:
```<code>SELECT *
  FROM testing123
 WHERE cat_id IN (SELECT cat_id
                    FROM testing123
                   WHERE subcat_id IN (2, 6)
                GROUP BY cat_id
                  HAVING COUNT(*) = 2)

SELECT *
  FROM testing123
 WHERE cat_id IN (SELECT cat_id
                    FROM testing123
                   WHERE subcat_id IN (2, 4, 5, 7)
                GROUP BY cat_id
                  HAVING COUNT(*) = 4)
</code>```

Note that COUNT(*) = N clause depends on how many subcats were enumerated in the IN()

Title: Mysql complex selection

Body:
How to select rows with exact subcats id's? For example i need to pick only rows which have subcat_id 2,6 or 2,4,5,7.

CREATE TABLE IF NOT EXISTS `testing123` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `cat_id` int(10) DEFAULT '0',
  `subcat_id` int(10) DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=223 DEFAULT CHARSET=utf8;

REPLACE INTO `testing123` (`id`, `cat_id`, `subcat_id`) VALUES
    (170, 32, 5),
    (171, 33, 1),
    (172, 33, 7),
    (173, 34, 5),
    (175, 35, 2),
    (176, 36, 1),
    (177, 36, 2),
    (178, 36, 7),
    (179, 37, 2),
    (180, 37, 6),
    (184, 40, 2),
    (185, 40, 5),
    (186, 40, 6),
    (187, 41, 4),
    (188, 54, 2),
    (189, 54, 4),
    (190, 54, 5),
    (191, 54, 7),
    (192, 55, 6),
    (193, 56, 2),
    (194, 56, 6),
    (195, 57, 6),
    (196, 58, 1),
    (197, 59, 3),
    (198, 60, 6),
    (199, 61, 2),
    (200, 61, 6),
    (203, 63, 1),
    (204, 63, 6),
    (205, 64, 2),
    (206, 64, 6),
    (207, 65, 1),
    (208, 65, 2),
    (209, 66, 4),
    (214, 67, 1),
    (215, 67, 5),
    (220, 70, 1),
    (221, 70, 4),
    (222, 70, 5);

If i'm using OR or IN(), it's picking all rows, that have ANY one provided subcats, but i need to have exact matches only.

Table example provided for experiments.

Help! :)

Body:
SELECT *
  FROM testing123
 WHERE cat_id IN (SELECT cat_id
                    FROM testing123
                   WHERE subcat_id IN (2, 6)
                GROUP BY cat_id
                  HAVING COUNT(*) = 2)

SELECT *
  FROM testing123
 WHERE cat_id IN (SELECT cat_id
                    FROM testing123
                   WHERE subcat_id IN (2, 4, 5, 7)
                GROUP BY cat_id
                  HAVING COUNT(*) = 4)

Note that COUNT(*) = N clause depends on how many subcats were enumerated in the IN()


问:
Missing DataValidation DataSource
I am working on an excel spreadsheet. I have a dropdown with values. I need to add a value in there.

There is no macro and there is no connection. The only thing I found was:

I selected the cell at hand

Data -> DataValidation

In the source i can see this string =Variables!$D$1:$D$23

I do not have a sheet called variables or anything close to the word variables in any of the sheets. Where can this be coming from?

There is also protection on the workbook but not the individual sheets. Could this be the issue?

Thank you

答:
You can usually check the contents of a hidden sheet quite easy using the Immediate Window.

So open the VBA editor (Alt-F11), go to the Immediate window (Ctrl-G), and try:

```<code>?Variables.[D17]
</code>```

If this works, you can repeat this to see the other 22 validation values (or write a small sub, using Debug.Print ubstead of ?).

Title: Missing DataValidation DataSource

Body:
You can usually check the contents of a hidden sheet quite easy using the Immediate Window.

So open the VBA editor (Alt-F11), go to the Immediate window (Ctrl-G), and try:

?Variables.[D17]

If this works, you can repeat this to see the other 22 validation values (or write a small sub, using Debug.Print ubstead of ?).


问:
ModuleNotFound: No module named 'app'
Let's say I have the following folder structure intended to organize the tests in my project repo:

```<code>project/
    app.py
    tests/
        test.py
</code>```

app.py has a simple addition function:

```<code>def add(x, y):
    return x + y
</code>```

test.py tests this function:

```<code>from app import add
import unittest

class TestCase(unittest.TestCase):
    def test_add(self):
        print('Running the test!')
        self.assertEqual(add(3, 4), 7)

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

When I use nose2 everything works:

```<code>mac:project $ nose2
Running the test!
Ran 1 test in 0.000s
Ok
</code>```

The problem is when I try to run test.py directly I get the following error:

```<code>mac:project $ python tests/test.py
ModuleNotFound: No module named 'app'
</code>```

How can I fix this? The reason is I want to use the coverage package to measure code coverage and I'm getting the same error:

```<code>mac:project $ coverage run tests/test.py
ModuleNotFound: No module named 'app'
</code>```

I've tried from ..app import app but I get this error: ValueError: attempted relative import beyond top-level package

答:
Thanks to Alasdair who had the right idea. I need to add the following to the top of test.py to tell python to look for imports in project:

```<code>import os, sys
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(parent_dir)
</code>```

Title: ModuleNotFound: No module named 'app'

Body:
Let's say I have the following folder structure intended to organize the tests in my project repo:

project/
    app.py
    tests/
        test.py

app.py has a simple addition function:

def add(x, y):
    return x + y

test.py tests this function:

from app import add
import unittest

class TestCase(unittest.TestCase):
    def test_add(self):
        print('Running the test!')
        self.assertEqual(add(3, 4), 7)

if __name__ == '__main__':
    unittest.main()

When I use nose2 everything works:

mac:project $ nose2
Running the test!
Ran 1 test in 0.000s
Ok

The problem is when I try to run test.py directly I get the following error:

mac:project $ python tests/test.py
ModuleNotFound: No module named 'app'

How can I fix this? The reason is I want to use the coverage package to measure code coverage and I'm getting the same error:

mac:project $ coverage run tests/test.py
ModuleNotFound: No module named 'app'

I've tried from ..app import app but I get this error: ValueError: attempted relative import beyond top-level package

Body:
Thanks to Alasdair who had the right idea. I need to add the following to the top of test.py to tell python to look for imports in project:

import os, sys
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(parent_dir)


问:
Cannot search based on multiple id in find query in Cakephp 3
I have two tables category and product. I want to get details of product whose id are passed in conditions array of find query. The problem is when i pass condition as an array, it returns

Cannot convert value to integer

Secondly, if i debug it by passing only one id it returns category record, but it should return product record. Please help to solve my issue.

My code is as follows:

```<code> public function display()
    {
      $ids = array(1,2,3,4,5);
      $c_List = $this->Products->Categories->find('all',array('conditions'=>array('Categories.category_id'=>$ids)));
      $data = $c_List->toArray();
       debug($data);
       die();
    }
</code>```

Model - ProductsTable.php

```<code>public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('products');
        $this->setDisplayField('product_id');
        $this->setPrimaryKey('product_id');

        $this->belongsTo('Products', [
            'foreignKey' => 'product_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('Categories', [
            'foreignKey' => 'category_id',
            'joinType' => 'INNER'
        ]);
    }
</code>```

Model - CategoriesTable.php

```<code>public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('categories');
        $this->setDisplayField('category_id');
        $this->setPrimaryKey('category_id');

        $this->belongsTo('Categories', [
            'foreignKey' => 'category_id',
            'joinType' => 'INNER'
        ]);
    }
</code>```

答:
When you are finding the records based on an array of ids, use IN in the condition clause.

```<code>public function display()
    {
      $ids = array(1,2,3,4,5);
      $c_List = $this->Products->Categories->find('all',array('conditions'=>array('Categories.category_id IN'=>$ids)));
      $data = $c_List->hydrate(false)->toArray();
       pr($data);
       die();
    }
</code>```

Body:
I have two tables category and product. I want to get details of product whose id are passed in conditions array of find query. The problem is when i pass condition as an array, it returns

Cannot convert value to integer

Secondly, if i debug it by passing only one id it returns category record, but it should return product record. Please help to solve my issue.

My code is as follows:

 public function display()
    {
      $ids = array(1,2,3,4,5);
      $c_List = $this->Products->Categories->find('all',array('conditions'=>array('Categories.category_id'=>$ids)));
      $data = $c_List->toArray();
       debug($data);
       die();
    }

Model - ProductsTable.php

public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('products');
        $this->setDisplayField('product_id');
        $this->setPrimaryKey('product_id');

        $this->belongsTo('Products', [
            'foreignKey' => 'product_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('Categories', [
            'foreignKey' => 'category_id',
            'joinType' => 'INNER'
        ]);
    }

Model - CategoriesTable.php

public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('categories');
        $this->setDisplayField('category_id');
        $this->setPrimaryKey('category_id');

        $this->belongsTo('Categories', [
            'foreignKey' => 'category_id',
            'joinType' => 'INNER'
        ]);
    }

Body:
When you are finding the records based on an array of ids, use IN in the condition clause.

public function display()
    {
      $ids = array(1,2,3,4,5);
      $c_List = $this->Products->Categories->find('all',array('conditions'=>array('Categories.category_id IN'=>$ids)));
      $data = $c_List->hydrate(false)->toArray();
       pr($data);
       die();
    }


问:
Python strings: backspace at the end of string behaves differently
I'm experimenting with the backspace character \b in Python strings. I tried this:

```<code>>>> s = "The dog\b barks"
>>> print(s)
The do barks
</code>```

This behaves as expected. The g character disappears because of the \b backspace.

Now I try this:

```<code>>>> s = "The dog barks\b"
>>> print(s)
The dog barks
</code>```

Strange... the s character didn't disappear. Why?

Note:

I work on a Windows 10 PC and did these experiments in the Windows cmd prompt (the terminal). I run Python 3.6

答: Python doesn't treat the backspace (\b) character specially, but Windows command prompt (cmd.exe) treats the backspace by moving the cursor left one character, then printing the rest of the string. Because there is nothing left to print, moving the cursor left doesn't actually do anything.

Body:
I'm experimenting with the backspace character \b in Python strings. I tried this:

>>> s = "The dog\b barks"
>>> print(s)
The do barks

This behaves as expected. The g character disappears because of the \b backspace.

Now I try this:

>>> s = "The dog barks\b"
>>> print(s)
The dog barks

Strange... the s character didn't disappear. Why?

Note:

I work on a Windows 10 PC and did these experiments in the Windows cmd prompt (the terminal). I run Python 3.6


问:
Issue using node-sass after updating NodeJS
I get an issue using node-sass after updating my NodeJS version.

Issue :

```<code>(node:472) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
C:\aglqng\src\main\webapp\node_modules\node-sass\lib\index.js:15
    throw new Error(errors.missingBinary());
    ^

Error: Missing binding C:\aglqng\src\main\webapp\node_modules\node-sass\vendor\win32-x64-48\binding.node
Node Sass could not find a binding for your current environment: Windows 64-bit with Node.js 6.x

Found bindings for the following environments:
  - Windows 64-bit with Node 0.12.x

This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass` to build the binding for your current environment.
    at Object.<anonymous> (C:\aglqng\src\main\webapp\node_modules\node-sass\lib\index.js:15:11)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\aglqng\src\main\webapp\node_modules\gulp-sass\index.js:187:21)
    at Module._compile (module.js:541:32)
</code>```

Versions :

```<code>node-sass 3.8.0 (Wrapper) [JavaScript]
libsass 3.3.6 (Sass Compiler) [C/C++]
nodejs v6.3.1
</code>```

Platform : Windows 10 x64

I tried this and it doesn't work :

1)

```<code>node rebuild node-sass
</code>```

2)

```<code>npm uninstall node-sass
npm i node-sass
</code>```

答:
You can run the: </p>

```<code>npm rebuild node-sass
</code>```

Body:
I get an issue using node-sass after updating my NodeJS version.

Issue :

(node:472) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
C:\aglqng\src\main\webapp\node_modules\node-sass\lib\index.js:15
    throw new Error(errors.missingBinary());
    ^

Error: Missing binding C:\aglqng\src\main\webapp\node_modules\node-sass\vendor\win32-x64-48\binding.node
Node Sass could not find a binding for your current environment: Windows 64-bit with Node.js 6.x

Found bindings for the following environments:
  - Windows 64-bit with Node 0.12.x

This usually happens because your environment has changed since running `npm install`.
Run `npm rebuild node-sass` to build the binding for your current environment.
    at Object.<anonymous> (C:\aglqng\src\main\webapp\node_modules\node-sass\lib\index.js:15:11)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\aglqng\src\main\webapp\node_modules\gulp-sass\index.js:187:21)
    at Module._compile (module.js:541:32)

Versions :

node-sass 3.8.0 (Wrapper) [JavaScript]
libsass 3.3.6 (Sass Compiler) [C/C++]
nodejs v6.3.1

Platform : Windows 10 x64

I tried this and it doesn't work :

1)

node rebuild node-sass

2)

npm uninstall node-sass
npm i node-sass

Body:
You can run the:

npm rebuild node-sass