问:
How to explain the reverse of a sequence by slice notation a[::-1]
From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

```<code>>>> a = "hello"
>>> print(a[::-1])
olleh
</code>```

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

```<code>>>> print(len(a[0:5:-1]))
0
</code>```

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.

答:
You'll notice that the third slice argument, the step, is not presented in the part of the tutorial you quoted. That particular snippet assumes a positive step.

When you add in the possibility of a negative step, the behavior is actually pretty intuitive. An empty start parameter refers to whichever end of the sequence one would start at to step through the whole sequence in the direction indicated by the step value. In other words it refers to the lowest index (to count up) if you have a positive step, and the highest index (to count down) if you have a negative step. Likewise, an empty end parameter refers to whichever end of the sequence one would end up at after stepping through in the appropriate direction.

Body:
From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> a = "hello"
>>> print(a[::-1])
olleh

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

>>> print(len(a[0:5:-1]))
0

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.


来源: stackexchange

问:
A quick example to train a model batch by batch in Tensorflow?
I have searched a lot on Google, I couldn't find an example of training a model batch by batch. The mnist built in Tensorflow dataset has mnist.train.next_batch(BATCH_SIZE) function, I need a function like this to separate my dataset into batches and loads the next batch for every iteration.

答:
You can split your train data as follows:

```<code>#Generate a random batch of 200 samples
rand_index = np.random.choice(len(x_data), size=200)
rand_x = x_data[rand_index]
rand_y = y_data[rand_index]
</code>```

And then at each iteration, you train batch by batch.

```<code>for i in range(1000):
   for u in range(number_of_batches):
      sess.run(train, feed_dict={x: rand_x.....})
</code>```

Something like that would work.

ContentLicense: CC BY-SA 3.0

Body:
You can split your train data as follows:

#Generate a random batch of 200 samples
rand_index = np.random.choice(len(x_data), size=200)
rand_x = x_data[rand_index]
rand_y = y_data[rand_index]

And then at each iteration, you train batch by batch.

for i in range(1000):
   for u in range(number_of_batches):
      sess.run(train, feed_dict={x: rand_x.....})

Something like that would work.


问:
Problems with MySQL COUNT() and joins
I need to get a count of which types of tickets have been ordered on each account, and only on accounts that have incurred a transaction. I'm doing this with the following query for each price:

```<code>SELECT tickets.order_id as order_id, count(tickets.id) as count
  FROM tickets,transactions
  WHERE price = $price
    AND tickets.order_id = transactions.order_id
  GROUP BY tickets.order_id
</code>```

This gets the right set of results, but on orders where there are multiple transactions the number for count(tickets.id) is multiplied by that number. What query do I need to use to avoid this problem? Do I need to use a different kind of join?

答:
use</p>

```<code>count (distinct tickets.id)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Problems with MySQL COUNT() and joins

Body:
I need to get a count of which types of tickets have been ordered on each account, and only on accounts that have incurred a transaction. I'm doing this with the following query for each price:

SELECT tickets.order_id as order_id, count(tickets.id) as count
  FROM tickets,transactions
  WHERE price = $price
    AND tickets.order_id = transactions.order_id
  GROUP BY tickets.order_id

This gets the right set of results, but on orders where there are multiple transactions the number for count(tickets.id) is multiplied by that number. What query do I need to use to avoid this problem? Do I need to use a different kind of join?

Body:
use

count (distinct tickets.id)


问:
Is the dash a special character in shiny IDs?
I'm attempting to use a conditionalPanel to hide certain ui elements. I discovered that using a "-" in the id of the input element used in the condition statement causes the condtionalPanel to break. Is this expected behavior? I had thought the "-" character was allowable in shiny IDs.

Working example (remove "-" from 'file-Opt' and 'input.file-Opt' to enable the conditional panel to work again.

```<code>library(shiny)

ui <- shinyUI(fluidPage(
  fileInput('file', 'Choose file to upload',
    accept = c(
      'text/csv',
      'text/comma-separated-values',
      'text/tab-separated-values',
      'text/plain',
      '.csv',
      '.tsv'
    )
  ),
  checkboxInput('file-Opt', "Show advanced file options", FALSE),
  tags$hr(),
  conditionalPanel(
    condition = 'input.file-Opt == true',
    checkboxInput('header', 'Header', TRUE)
  ) # conditionalPanel close
))

server <- shinyServer(function(input, output, session) {

})

shinyApp(ui = ui, server = server)
</code>```

答:
You are not recommended to use special JavaScript characters such as a period . in the input id's, but if you do use them anyway, for example, inputId = "foo.bar", you will have to use input["foo.bar"] instead of input.foo.bar to read the input value.
I guess the same goes for "-".

Source:
https://shiny.rstudio.com/reference/shiny/latest/conditionalPanel.html

Body:
I'm attempting to use a conditionalPanel to hide certain ui elements. I discovered that using a "-" in the id of the input element used in the condition statement causes the condtionalPanel to break. Is this expected behavior? I had thought the "-" character was allowable in shiny IDs.

Working example (remove "-" from 'file-Opt' and 'input.file-Opt' to enable the conditional panel to work again.

library(shiny)

ui <- shinyUI(fluidPage(
  fileInput('file', 'Choose file to upload',
    accept = c(
      'text/csv',
      'text/comma-separated-values',
      'text/tab-separated-values',
      'text/plain',
      '.csv',
      '.tsv'
    )
  ),
  checkboxInput('file-Opt', "Show advanced file options", FALSE),
  tags$hr(),
  conditionalPanel(
    condition = 'input.file-Opt == true',
    checkboxInput('header', 'Header', TRUE)
  ) # conditionalPanel close
))

server <- shinyServer(function(input, output, session) {

})

shinyApp(ui = ui, server = server)


问:
How can I write a piece of Java an code that checks if any character of a string is convertible to an integer between 0 and 9?
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

```<code>String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}
</code>```

where IntegerFormat Exception is something like

```<code>public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}
</code>```

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

```<code>at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)
</code>```

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

答:
Instead of looping you can use regex. This will work and would throw the IntegerFormatException for an empty string as well.

```<code>String s = "...";

if (!s.matches("[0-9]+")) {
    throw new IntegerFormatException();
}
</code>```

It won't cover Integer type capacity overflow - I mean a huge number above Integer.MAX_VALUE. Not sure do you need that though.

Body:
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}

where IntegerFormat Exception is something like

public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

Body:
Instead of looping you can use regex. This will work and would throw the IntegerFormatException for an empty string as well.

String s = "...";

if (!s.matches("[0-9]+")) {
    throw new IntegerFormatException();
}

It won't cover Integer type capacity overflow - I mean a huge number above Integer.MAX_VALUE. Not sure do you need that though.


问:
Show diff between commits
I am using Git on Ubuntu 10.04 (Lucid Lynx).

I have made some commits to my master.

However, I want to get the difference between these commits. All of them are on my master branch.

For example:

```<code>commit dj374
made changes

commit y4746
made changes

commit k73ud
made changes
</code>```

I want to get the difference between k73ud and dj374. However, when I did the following I couldn't see the changes I made in k73ud.

```<code>git diff k73ud..dj374 > master.patch
</code>```

答:
Use this command for the difference between commit and unstaged:</p>

```<code>git difftool --dir-diff
</code>```

Title: Show diff between commits

Body:
I am using Git on Ubuntu 10.04 (Lucid Lynx).

I have made some commits to my master.

However, I want to get the difference between these commits. All of them are on my master branch.

For example:

commit dj374
made changes

commit y4746
made changes

commit k73ud
made changes

I want to get the difference between k73ud and dj374. However, when I did the following I couldn't see the changes I made in k73ud.

git diff k73ud..dj374 > master.patch

Body:
Use this command for the difference between commit and unstaged:

git difftool --dir-diff


问:
Regular expression to find text between characters from specific location
Can someone please help me write an expression to get a value between 5th and 6th pipe of OBX segment (bold text below):

OBX|1|ST|PDF^Display Format in PDF^BASE64|26|JVBERi0xLjMNCiXS50K||||||P

答:
```<code>// split by pipe
string[] strArray = text.Split('|');
// taking sixth element in resulting array
string value = strArray[5].ToString();
</code>```


问:
Lock for ConcurrentDictionary when AddOrUpdate-ing?
I use a ConcurrentDictioanry<string, HashSet<string>> to access some data across many threads.

I read in this article (scroll down) that  the method AddOrUpdate is not executed in the lock, so it could endanger thread-safety.

My code is as follows:

```<code>//keys and bar are not the concern here
ConcurrentDictioanry<string, HashSet<string>> foo = new ...;
foreach(var key in keys) {
    foo.AddOrUpdate(key, new HashSet<string> { bar }, (key, val) => {
        val.Add(bar);
        return val;
    });
}
</code>```

Should I enclose the AddOrUpdate call in a lock statement in order to be sure everything is thread-safe?

答:
Seems the  better answer would be to use Lazy, per this article on the methods that pass in a delegate. </p>

<p>Also another good article Here on Lazy loading the add delegate. </p>

Body:
I use a ConcurrentDictioanry<string, HashSet<string>> to access some data across many threads.

I read in this article (scroll down) that  the method AddOrUpdate is not executed in the lock, so it could endanger thread-safety.

My code is as follows:

//keys and bar are not the concern here
ConcurrentDictioanry<string, HashSet<string>> foo = new ...;
foreach(var key in keys) {
    foo.AddOrUpdate(key, new HashSet<string> { bar }, (key, val) => {
        val.Add(bar);
        return val;
    });
}

Should I enclose the AddOrUpdate call in a lock statement in order to be sure everything is thread-safe?

Body:
Seems the  better answer would be to use Lazy, per this article on the methods that pass in a delegate.

Also another good article Here on Lazy loading the add delegate.


问:
Keep page enumeration between portrait and landscape pages
I am using Word 2013 and in my document I use both portrait and landscapes pages. The problem is that when I add the page enumeration, it gets restarted when the page orientation changes because it is considered as a different section.

How to keep the same correlation of page/number?

答:
Select Insert from the top bar. Then in the column "Headers and Footers", click on Page Number then select "Format Page Numbers" as shown below:

Now select "Continue from previous section" under Page Numbering as shown below:


问:
Coloring non generic contours
I am using C# and I am drawing the picture programmatically (since the picture can differ according to run time values of the parameters in my application). I end up with non generic closed contours (which consist of straight lines and curves). Now I need to fill those with different colors.
Any idea how can I accomplish this?

Thanks in advance.

答: Take a look at flood fill algorithms. You're probably better off drawing to a bitmap, then rendering to the forms (I assume you're using WinForms).</p>

Title: Coloring non generic contours


问:
Occasional IOException when creating a CSV file 'The process cannot access the file...'
I'm creating a CSV (with ';' as seperator) file by using the Office.Interop.Excell library.

Following code works fine on my computer but one of my clients sometimes get's the IO.Exception: 'The process cannot access the file because it is being used by another process'.

The weird thing is that this error is not allways popping up, sometimes it works, sometimes it doesnt...

What could be the cause of this occasional IO.Exception for my client. This is my code:

```<code>public static void GenerateCsvFile(DataSet ds, string paramFileFullPath, Dictionary<string, string[]> tableHeaders)
    {
        object missing = System.Reflection.Missing.Value;

        var excel = new Application { DisplayAlerts = false };
        Workbook workbook = null;
        try
        {
            workbook = excel.Application.Workbooks.Add(true);

            foreach (System.Data.DataTable dt in ds.Tables)
                AddTableSheet(ref workbook, ref excel, dt, true, tableHeaders[dt.TableName], false);

            workbook.SaveAs(paramFileFullPath, XlFileFormat.xlTextMSDOS, missing, missing, false, false,
              XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
        }
        finally
        {
            CleanupExcel(excel, workbook);
        }

        File.WriteAllText(paramFileFullPath, File.ReadAllText(paramFileFullPath).Replace("\t", ";"));
    }
</code>```

I guess the error sometimes come from the line:

File.WriteAllText(paramFileFullPath, File.ReadAllText(paramFileFullPath).Replace("\t", ";"));

Is there perhaps something wrong with the way i'm cleaning/closing Excel ?

```<code>private static void CleanupExcel(Application excel, Workbook workbook)
    {
        if (excel == null)
            return;

        excel.DisplayAlerts = false;
        excel.Quit();

        if (workbook != null)
            Marshal.ReleaseComObject(workbook);
        Marshal.ReleaseComObject(excel);
    }
</code>```

And how come that this allways works for me, but on the PC of my client it only works like 1 out of 5 times...

答:
but one of my clients sometimes get's the IO.Exception: 'The process cannot access the file because it is being used by another process'.

How much should I bet that the underlying problem is that said client is keeping the file open in Excel while trying to run your code? ;)

Body:
I'm creating a CSV (with ';' as seperator) file by using the Office.Interop.Excell library.

Following code works fine on my computer but one of my clients sometimes get's the IO.Exception: 'The process cannot access the file because it is being used by another process'.

The weird thing is that this error is not allways popping up, sometimes it works, sometimes it doesnt...

What could be the cause of this occasional IO.Exception for my client. This is my code:

public static void GenerateCsvFile(DataSet ds, string paramFileFullPath, Dictionary<string, string[]> tableHeaders)
    {
        object missing = System.Reflection.Missing.Value;

        var excel = new Application { DisplayAlerts = false };
        Workbook workbook = null;
        try
        {
            workbook = excel.Application.Workbooks.Add(true);

            foreach (System.Data.DataTable dt in ds.Tables)
                AddTableSheet(ref workbook, ref excel, dt, true, tableHeaders[dt.TableName], false);

            workbook.SaveAs(paramFileFullPath, XlFileFormat.xlTextMSDOS, missing, missing, false, false,
              XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
        }
        finally
        {
            CleanupExcel(excel, workbook);
        }

        File.WriteAllText(paramFileFullPath, File.ReadAllText(paramFileFullPath).Replace("\t", ";"));
    }

I guess the error sometimes come from the line:

File.WriteAllText(paramFileFullPath, File.ReadAllText(paramFileFullPath).Replace("\t", ";"));

Is there perhaps something wrong with the way i'm cleaning/closing Excel ?

private static void CleanupExcel(Application excel, Workbook workbook)
    {
        if (excel == null)
            return;

        excel.DisplayAlerts = false;
        excel.Quit();

        if (workbook != null)
            Marshal.ReleaseComObject(workbook);
        Marshal.ReleaseComObject(excel);
    }

And how come that this allways works for me, but on the PC of my client it only works like 1 out of 5 times...


问:
What's really happening inside getchar() and printf()? Explain whole process
I was learning from geeksforgeeks and when i saw this, a thought came in my mind that as getchar() and other similar functions returns an int(whether due to failure of program or EOF) then why format specifier used is %c, why not %d(or %i).

```<code>// Example for getchar() in C
#include <stdio.h>
int main()
{
   printf("%c", getchar());
   return 0;
}
</code>```

I know that the character we input in is a character and it is taken by the function getchar() and we are displaying it using %c.

But my problem is what's actually happening inside getchar() and printf() during the whole process, where getchar() is returning that integer, where it is getting stored and how the character we inputted is getting displayed by printf() i.e.what's happening inside printf()?

I did some research on printf() implementation and get to know that printf is part of the C standard library (a.k.a. the libc) and is a variadic function(printf) but i didn't came to know that what is really happening inside this function and how it knows by format specifier that it has to print character or int?

Please help me learning the whole detailed process which is going on.

答:
To understand you must read default argument promotions.

where getchar() is returning that integer, where it is getting stored

C handle this for you.

how the character we inputted is getting displayed by printf()

%c tell to printf() to print a character.

Body:
I was learning from geeksforgeeks and when i saw this, a thought came in my mind that as getchar() and other similar functions returns an int(whether due to failure of program or EOF) then why format specifier used is %c, why not %d(or %i).

// Example for getchar() in C
#include <stdio.h>
int main()
{
   printf("%c", getchar());
   return 0;
}

I know that the character we input in is a character and it is taken by the function getchar() and we are displaying it using %c.

But my problem is what's actually happening inside getchar() and printf() during the whole process, where getchar() is returning that integer, where it is getting stored and how the character we inputted is getting displayed by printf() i.e.what's happening inside printf()?

I did some research on printf() implementation and get to know that printf is part of the C standard library (a.k.a. the libc) and is a variadic function(printf) but i didn't came to know that what is really happening inside this function and how it knows by format specifier that it has to print character or int?

Please help me learning the whole detailed process which is going on.


问:
Do date ranges in Rails include the border dates?
I want to query a date range in Rails:

```<code>User.where(:created_at => Time.now.beginning_of_day..Time.now.end_of_day)

Time.now.beginning_if_day is at 00:00:00
Time.now.end_of_day is at: 23.59.59
</code>```

Does my range include those two border times, or does is use < and >?

答:
Opening up the good console answers all your questions.

With .. calls a BETWEEN statement in the db

```<code>User.where(created_at: Time.zone.today.beginning_of_day..Time.zone.today.end_of_day).to_sql

# SELECT "users".*
# FROM "users"
# WHERE ("users"."created_at" BETWEEN '2017-06-06 00:00:00' AND '2017-06-06 23:59:59.999999')
</code>```

With ... it calls the >= < magic.

```<code>User.where(created_at: Time.zone.today.beginning_of_day...Time.zone.today.end_of_day).to_sql

# SELECT "users".*
# FROM "users"
# WHERE ("users"."created_at" >= '2017-06-06 00:00:00' AND
#        "users"."created_at" < '2017-06-06 23:59:59.999999')
</code>```

Rails 5.1 includes a nice little helper called all_day which makes this possible. It issues the same statement as with ..

```<code>Users.where(created_at: Time.zone.today.all_day).to_sql
</code>```

Note:

If you're really paranoid and have a super important life-saving app going on, Time.zone.today might actually change in the milliseconds from calling beginning_of_day and end_of_day, so you can do this then.

```<code>today = Time.zone.today
Users.where(created_at: today.beginning_of_day..today.end_of_day)
</code>```

Body:
I want to query a date range in Rails:

User.where(:created_at => Time.now.beginning_of_day..Time.now.end_of_day)

Time.now.beginning_if_day is at 00:00:00
Time.now.end_of_day is at: 23.59.59

Does my range include those two border times, or does is use < and >?

Body:
Opening up the good console answers all your questions.

With .. calls a BETWEEN statement in the db

User.where(created_at: Time.zone.today.beginning_of_day..Time.zone.today.end_of_day).to_sql

# SELECT "users".*
# FROM "users"
# WHERE ("users"."created_at" BETWEEN '2017-06-06 00:00:00' AND '2017-06-06 23:59:59.999999')

With ... it calls the >= < magic.

User.where(created_at: Time.zone.today.beginning_of_day...Time.zone.today.end_of_day).to_sql

# SELECT "users".*
# FROM "users"
# WHERE ("users"."created_at" >= '2017-06-06 00:00:00' AND
#        "users"."created_at" < '2017-06-06 23:59:59.999999')

Rails 5.1 includes a nice little helper called all_day which makes this possible. It issues the same statement as with ..

Users.where(created_at: Time.zone.today.all_day).to_sql

Note:

If you're really paranoid and have a super important life-saving app going on, Time.zone.today might actually change in the milliseconds from calling beginning_of_day and end_of_day, so you can do this then.

today = Time.zone.today
Users.where(created_at: today.beginning_of_day..today.end_of_day)


问:
changing scroll speed of divs?
I am trying to adjust scroll speeds of some divs depending on if an other div (image-ul) is fully above the bottom of the webpage or not.

When the div "image-ul" moves above or below the bottom edge of the browser window it does change CSS, but the scroll speeds do not change upon scrolling or scaling of the window. I also want the scroll speeds to then change.

Only when (re)loading the page do the scroll speeds change according to where "image-ul" is in relation to the bottom egde of the browser window.

What am I doing wrong? Please see example here.

So, the goal is to have different scroll speeds for divs when div "image-ul" is fully above the bowser window's bottom edge, and different scroll speeds for those divs when div "image-ul" is NOT fully above the bowser window's bottom edge.

I am already achieving moving elements at different speeds, but, as my question states, I need the speeds to change depending on if div "image-ul" is fully above the browser window's bottom egde or not.

```<code>    // Assign attribute specific "data-scroll-speed" to elements upon loading, resizing and scrolling of the webpage page. "if/else" is depending on if #image-ul is fully above the bottom edge of the browser window.
 $(document).ready(function() {
     $(window).on('load resize scroll', function() {
         var WindowScrollTop = $(this).scrollTop(),
             Div_one_top = $('#image-ul').offset().top,
             Div_one_height = $('#image-ul').outerHeight(true),
             Window_height = $(this).outerHeight(true);
         if (WindowScrollTop + Window_height >= (Div_one_top + Div_one_height)) {
             $('#sloganenglish').attr('data-scroll-speed', '4');
             $('.slogan-a-line').attr('data-scroll-speed', '5');
             $('.slogan-a-line').css('color', 'yellow');
         } else {
             $('#sloganenglish').attr('data-scroll-speed', '1');
             $('.slogan-a-line').attr('data-scroll-speed', '1');
             $('.slogan-a-line').css('color', 'red');
         }
     }).scroll();
 });
</code>```

答:
I am not sure if I understand you right, but I found that your data-scroll-speed value does not get updated when you are calling your inline css changes. The following works in "some" way, but I am also not sure if this is exactly what you want. But maybe this already helps you out:

https://jsfiddle.net/wyx3o6uy/40/

The important part is this line which I changed to fetch the current value:

```<code>var pos = scrollTop / parseInt(this.el.attr('data-scroll-speed'));
</code>```

Original was:

```<code>var pos = scrollTop / this.speed;
</code>```

Is this what you were looking for?

Title: changing scroll speed of divs?

Body:
I am trying to adjust scroll speeds of some divs depending on if an other div (image-ul) is fully above the bottom of the webpage or not.

When the div "image-ul" moves above or below the bottom edge of the browser window it does change CSS, but the scroll speeds do not change upon scrolling or scaling of the window. I also want the scroll speeds to then change.

Only when (re)loading the page do the scroll speeds change according to where "image-ul" is in relation to the bottom egde of the browser window.

What am I doing wrong? Please see example here.

So, the goal is to have different scroll speeds for divs when div "image-ul" is fully above the bowser window's bottom edge, and different scroll speeds for those divs when div "image-ul" is NOT fully above the bowser window's bottom edge.

I am already achieving moving elements at different speeds, but, as my question states, I need the speeds to change depending on if div "image-ul" is fully above the browser window's bottom egde or not.

    // Assign attribute specific "data-scroll-speed" to elements upon loading, resizing and scrolling of the webpage page. "if/else" is depending on if #image-ul is fully above the bottom edge of the browser window.
 $(document).ready(function() {
     $(window).on('load resize scroll', function() {
         var WindowScrollTop = $(this).scrollTop(),
             Div_one_top = $('#image-ul').offset().top,
             Div_one_height = $('#image-ul').outerHeight(true),
             Window_height = $(this).outerHeight(true);
         if (WindowScrollTop + Window_height >= (Div_one_top + Div_one_height)) {
             $('#sloganenglish').attr('data-scroll-speed', '4');
             $('.slogan-a-line').attr('data-scroll-speed', '5');
             $('.slogan-a-line').css('color', 'yellow');
         } else {
             $('#sloganenglish').attr('data-scroll-speed', '1');
             $('.slogan-a-line').attr('data-scroll-speed', '1');
             $('.slogan-a-line').css('color', 'red');
         }
     }).scroll();
 });

Body:
I am not sure if I understand you right, but I found that your data-scroll-speed value does not get updated when you are calling your inline css changes. The following works in "some" way, but I am also not sure if this is exactly what you want. But maybe this already helps you out:

https://jsfiddle.net/wyx3o6uy/40/

The important part is this line which I changed to fetch the current value:

var pos = scrollTop / parseInt(this.el.attr('data-scroll-speed'));

Original was:

var pos = scrollTop / this.speed;

Is this what you were looking for?


问:
Adding a product to advanced stock management programmatically on Prestashop 1.6
I am trying to assign certain products for be used with advanced stock management, it seems OK in the DB, but some things aren't ticked on the BO, I'm wondering if this might have any impact.

For example, when selecting shop groups and going on a product in the BO, I don't see "I want to use advanced stock management for this product" ticked, while the "depends on stock" radio button is correctly selected (and thus disabled since the checkbox if left untouched). I don't know if this is problematic or not for the stock of the product. If anyone had any input on this, it would be appreciated.

Here is what I have so far:

```<code>$warehouse = new Warehouse(1);
$stock_manager = StockManagerFactory::getManager();
foreach($prods as $prod)
{
    StockAvailable::setProductDependsOnStock($prod['id_product'], 1);
    if ($stock_manager->addProduct($prod['id_product'], 0, $warehouse, 1, 5, 0.1, 1))
    {
        StockAvailable::synchronize($prod['id_product']);
    }
}
</code>```

答:
The StockAvailable::setProductDependsOnStock doesn't enable the AdvancedStockManagement for that product. You also need to set the product AdvancedStockManagement. You can use:

```<code>$warehouse = new Warehouse(1);
$stock_manager = StockManagerFactory::getManager();
foreach($prods as $prod)
{
    $product = new Product($prod['id_product']);
    if(!$product->advanced_stock_management)
        $product->setAdvancedStockManagement(true);
    StockAvailable::setProductDependsOnStock($prod['id_product'], 1);
    if ($stock_manager->addProduct($prod['id_product'], 0, $warehouse, 1, 5, 0.1, 1))
    {
        StockAvailable::synchronize($prod['id_product']);
    }
}
</code>```

Body:
I am trying to assign certain products for be used with advanced stock management, it seems OK in the DB, but some things aren't ticked on the BO, I'm wondering if this might have any impact.

For example, when selecting shop groups and going on a product in the BO, I don't see "I want to use advanced stock management for this product" ticked, while the "depends on stock" radio button is correctly selected (and thus disabled since the checkbox if left untouched). I don't know if this is problematic or not for the stock of the product. If anyone had any input on this, it would be appreciated.

Here is what I have so far:

$warehouse = new Warehouse(1);
$stock_manager = StockManagerFactory::getManager();
foreach($prods as $prod)
{
    StockAvailable::setProductDependsOnStock($prod['id_product'], 1);
    if ($stock_manager->addProduct($prod['id_product'], 0, $warehouse, 1, 5, 0.1, 1))
    {
        StockAvailable::synchronize($prod['id_product']);
    }
}

Body:
The StockAvailable::setProductDependsOnStock doesn't enable the AdvancedStockManagement for that product. You also need to set the product AdvancedStockManagement. You can use:

$warehouse = new Warehouse(1);
$stock_manager = StockManagerFactory::getManager();
foreach($prods as $prod)
{
    $product = new Product($prod['id_product']);
    if(!$product->advanced_stock_management)
        $product->setAdvancedStockManagement(true);
    StockAvailable::setProductDependsOnStock($prod['id_product'], 1);
    if ($stock_manager->addProduct($prod['id_product'], 0, $warehouse, 1, 5, 0.1, 1))
    {
        StockAvailable::synchronize($prod['id_product']);
    }
}


问:
How do i get the most updated api by android?
I would like to use the "new" findViewById that returns T extends View and not just View , what do i need to update to receive that ?

this is the updated Doc :

https://developer.android.com/reference/android/view/View.html

the new method  is already there .

答:
You have to install Android Studio 3.0 Preview/Canary and update all required SDK/Tools.

You have to Target the new API-Level, e.g.:

```<code>android {
   compileSdkVersion 'android-O'
   buildToolsVersion '26.0.0-rc2'

    defaultConfig {
        targetSdkVersion 'O'
        ....
    }
}
</code>```

Note that the Preview is only available from the Google Maven Repository, e.g.:

```<code>repositories {
    jcenter()
    maven {
        url 'https://maven.google.com'
    }
}
</code>```

Body:
You have to install Android Studio 3.0 Preview/Canary and update all required SDK/Tools.

You have to Target the new API-Level, e.g.:

android {
   compileSdkVersion 'android-O'
   buildToolsVersion '26.0.0-rc2'

    defaultConfig {
        targetSdkVersion 'O'
        ....
    }
}

Note that the Preview is only available from the Google Maven Repository, e.g.:

repositories {
    jcenter()
    maven {
        url 'https://maven.google.com'
    }
}


问:
Oracle Query to select only the text between two '-' characters
I would like to replace a column values selecting only the text inside the two '-' character. Example: Case 1 - Deleted - The case is closed.

So, i would like something like this:

Original:

```<code>Description
------------------------------------------
Case 1 - Deleted - The case is closed
</code>```

What I want to have:

```<code>Description
------------------------------------------
Deleted
</code>```

I have this but i dont know how to delete the text after the second '-' and replace that result on the current column Description

```<code>select SUBSTR(description, INSTR(description, '-') + 1) left_value
from (
    select description
    from all_cases
    );
</code>```

答:
Avoid all that fugly nested substr/instr with REGEXP_SUBSTR():

```<code>SQL> with tbl(str) as (
     select 'Case 1 - Deleted - The case is closed' from dual
   )
   select trim(regexp_substr(str, '-(.*)-', 1, 1, null, 1)) fixed
   from tbl;

FIXED
-------
Deleted
</code>```

Edit: Changed to simplify regex and allow for cases where there may not be spaces inside of the dashes.

ContentLicense: CC BY-SA 4.0

Body:
I would like to replace a column values selecting only the text inside the two '-' character. Example: Case 1 - Deleted - The case is closed.

So, i would like something like this:

Original:

Description
------------------------------------------
Case 1 - Deleted - The case is closed

What I want to have:

Description
------------------------------------------
Deleted

I have this but i dont know how to delete the text after the second '-' and replace that result on the current column Description

select SUBSTR(description, INSTR(description, '-') + 1) left_value
from (
    select description
    from all_cases
    );

Body:
Avoid all that fugly nested substr/instr with REGEXP_SUBSTR():

SQL> with tbl(str) as (
     select 'Case 1 - Deleted - The case is closed' from dual
   )
   select trim(regexp_substr(str, '-(.*)-', 1, 1, null, 1)) fixed
   from tbl;

FIXED
-------
Deleted

Edit: Changed to simplify regex and allow for cases where there may not be spaces inside of the dashes.


问:
Seggregating the output of a query
My question might seem weird. But I need to know whether we can identify and seggregate the rows fetched from particular table in a query, which is formed by joining tables.

Please refer the below query if I am you are not clear with my question.

My requirement is to know the rows fetched from table 'rel' alone in the query.

```<code>SELECT rel.*
FROM rel,  C
WHERE rel.col1  = C.col1
AND C.col1 NOT IN (SELECT R.col1 FROM R WHERE R.col2 = 'MN')
AND rel.col2= 'MN'
AND rel.col3= 'MN'
AND c.col2  ='MN';
</code>```

Thanks,
Savitha

答: Since you are performing an INNER JOIN by using the comparison in the WHERE clause, all your records, by definition, are coming from the rel table.</p>

Title: Seggregating the output of a query

Body:
My question might seem weird. But I need to know whether we can identify and seggregate the rows fetched from particular table in a query, which is formed by joining tables.

Please refer the below query if I am you are not clear with my question.

My requirement is to know the rows fetched from table 'rel' alone in the query.

SELECT rel.*
FROM rel,  C
WHERE rel.col1  = C.col1
AND C.col1 NOT IN (SELECT R.col1 FROM R WHERE R.col2 = 'MN')
AND rel.col2= 'MN'
AND rel.col3= 'MN'
AND c.col2  ='MN';

Thanks,
Savitha


问:
$eq not working with $unwind result mongoose
i've simple schema where Events.like store objectId of user. i'd like to match a particular user in array (Events.like) and add a flag isLiked according to match.

```<code>   Events.aggregate([
    { $unwind: '$like'},
      {
          "$project":{
            //   "count" : {$size: "$like"},
            "like":1,
          "isLiked" :{ "$eq": [ "like", "593564b94642650d5b09f16b"  ] },
            //   "isLiked" : { "$cond": [{ "$eq": [ "like", "593564b94642650d5b09f16b" ] }, true, false ] } }
            }
        }
    ], function(err, list) { }
</code>```

this method always give me false. see results

```<code> "data": [
    {
      "_id": "593647ae9e10082982d3f7a2",
      "like": "593563f66d2e9f0b84553fc3",
      "isLiked": false
    },
    {
      "_id": "593643a5a1e73a2841d3cddb",
      "like": "593564b94642650d5b09f16b",
      "isLiked": false
    },
    {
      "_id": "593643a5a1e73a2841d3cddb",
      "like": "593563f66d2e9f0b84553fc3",
      "isLiked": false
    }
  ]
</code>```

can anyone tell me where i'm mistaking

########## update ##########

```<code>{ $unwind: '$like'},
    {
          "$project":{
          "isLiked" :{ "$eq": [ "$like", mongoose.Types.ObjectId("593564b94642650d5b09f16b")  ] },
        }
    },
    {
        $group: {
          _id: '$_id',
          'likes': { $sum: 1},
          "like": { $push: '$like' },
          "isLiked" : 1
      }
    }
</code>```

then
 MongoError: the group aggregate field 'isLiked' must be defined as an expression inside an object

i simple want below result

```<code> "data": [
    {
      "_id": "593647ae9e10082982d3f7a2",
      "like": ["593563f66d2e9f0b84553fc3","593643a5a1e73a2841d3cddb" ],
      "likes":2
      "isLiked": true
    },
    {
      "_id": "593643a5a1e73a2841d3cddb",
      "like": "[593563f66d2e9f0b84553fc3"],
      "likes":1,
      "isLiked": false
    }
  ]
</code>```

答:
Hi the user id you are passing is being passed as a string you will need to convert it to objectId. Try this

EDIT: fixed path of the field as pointed by the asker, @ShivShanker

```<code>Events.aggregate([
{ $unwind: '$like'},
  {
      "$project":{
        //   "count" : {$size: "$like"},
        "like":1,
      "isLiked" :{ "$eq": [ "$like", mongoose.Types.ObjectId("593564b94642650d5b09f16b")  ] }
        }
    }
], function(err, list) { }
</code>```

Body:
i've simple schema where Events.like store objectId of user. i'd like to match a particular user in array (Events.like) and add a flag isLiked according to match.

   Events.aggregate([
    { $unwind: '$like'},
      {
          "$project":{
            //   "count" : {$size: "$like"},
            "like":1,
          "isLiked" :{ "$eq": [ "like", "593564b94642650d5b09f16b"  ] },
            //   "isLiked" : { "$cond": [{ "$eq": [ "like", "593564b94642650d5b09f16b" ] }, true, false ] } }
            }
        }
    ], function(err, list) { }

this method always give me false. see results

 "data": [
    {
      "_id": "593647ae9e10082982d3f7a2",
      "like": "593563f66d2e9f0b84553fc3",
      "isLiked": false
    },
    {
      "_id": "593643a5a1e73a2841d3cddb",
      "like": "593564b94642650d5b09f16b",
      "isLiked": false
    },
    {
      "_id": "593643a5a1e73a2841d3cddb",
      "like": "593563f66d2e9f0b84553fc3",
      "isLiked": false
    }
  ]

can anyone tell me where i'm mistaking

########## update ##########

{ $unwind: '$like'},
    {
          "$project":{
          "isLiked" :{ "$eq": [ "$like", mongoose.Types.ObjectId("593564b94642650d5b09f16b")  ] },
        }
    },
    {
        $group: {
          _id: '$_id',
          'likes': { $sum: 1},
          "like": { $push: '$like' },
          "isLiked" : 1
      }
    }

then
 MongoError: the group aggregate field 'isLiked' must be defined as an expression inside an object

i simple want below result

 "data": [
    {
      "_id": "593647ae9e10082982d3f7a2",
      "like": ["593563f66d2e9f0b84553fc3","593643a5a1e73a2841d3cddb" ],
      "likes":2
      "isLiked": true
    },
    {
      "_id": "593643a5a1e73a2841d3cddb",
      "like": "[593563f66d2e9f0b84553fc3"],
      "likes":1,
      "isLiked": false
    }
  ]

Body:
Hi the user id you are passing is being passed as a string you will need to convert it to objectId. Try this

EDIT: fixed path of the field as pointed by the asker, @ShivShanker

Events.aggregate([
{ $unwind: '$like'},
  {
      "$project":{
        //   "count" : {$size: "$like"},
        "like":1,
      "isLiked" :{ "$eq": [ "$like", mongoose.Types.ObjectId("593564b94642650d5b09f16b")  ] }
        }
    }
], function(err, list) { }


问:
React router v4 use declarative Redirect without rendering the current component
I am using a similar code like this to redirect in my app after users logged in. The code looks like the following:

```<code>import React, { Component } from 'react'
import { Redirect } from 'react-router'

export default class LoginForm extends Component {
  constructor () {
    super();
    this.state = {
      fireRedirect: false
    }
  }

  submitForm = (e) => {
    e.preventDefault()
    //if login success
    this.setState({ fireRedirect: true })
  }

  render () {
    const { from } = this.props.location.state || '/'
    const { fireRedirect } = this.state

    return (
      <div>
        <form onSubmit={this.submitForm}>
          <button type="submit">Submit</button>
        </form>
        {fireRedirect && (
          <Redirect to={from || '/home'}/>
        )}
      </div>
    )

  }
}
</code>```

Works fine when a successful login has been triggered. But there is the case, that logged in users enter the login page and should be automatically redirected to the "home" page (or whatever other page).

How can I use the Redirect component without rendering the current component and without (as far as I understand discouraged) imperative pushing to the history (e.g. in componentWillMount)?

答:
Solution 1

You could use withRouter HOC to access history via props.

Import withRouter.

```<code>import {
  withRouter
} from 'react-router-dom';
</code>```

Then wrap with HOC.

```<code>// Example code
export default withRouter(connect(...))(Component)
</code>```

Now you can access this.props.history. For example use it with componentDidMount().

```<code>componentDidMount() {
  const { history } = this.props;

  if (this.props.authenticated) {
    history.push('/private-route');
  }
}
</code>```

Solution 2 Much better

Here is example on reacttraining.

Which would perfectly work for you.

But you just need to create LoginRoute to handle problem you described.

```<code>const LoginRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
        <Redirect to={{
          pathname: '/private-route',
          state: { from: props.location }
        }} />
      ) : (
        <Component {...props} />
      )
  )} />
);
</code>```

and inside <Router /> just replace

```<code><Route path="/login" component={Login}/>
</code>```

with

```<code><LoginRoute path="/login" component={Login}/>
</code>```

Now everytime somebody will try to access /login route as authenticated user, he will be redirected to /private-route. It's even better solution because it doesn't mount your LoginComponent if condition isn't met.

Body:
I am using a similar code like this to redirect in my app after users logged in. The code looks like the following:

import React, { Component } from 'react'
import { Redirect } from 'react-router'

export default class LoginForm extends Component {
  constructor () {
    super();
    this.state = {
      fireRedirect: false
    }
  }

  submitForm = (e) => {
    e.preventDefault()
    //if login success
    this.setState({ fireRedirect: true })
  }

  render () {
    const { from } = this.props.location.state || '/'
    const { fireRedirect } = this.state

    return (

        <form onSubmit={this.submitForm}>
          <button type="submit">Submit</button>
        </form>
        {fireRedirect && (
          <Redirect to={from || '/home'}/>
        )}

    )

  }
}

Works fine when a successful login has been triggered. But there is the case, that logged in users enter the login page and should be automatically redirected to the "home" page (or whatever other page).

How can I use the Redirect component without rendering the current component and without (as far as I understand discouraged) imperative pushing to the history (e.g. in componentWillMount)?

Body:
Solution 1

You could use withRouter HOC to access history via props.

Import withRouter.

import {
  withRouter
} from 'react-router-dom';

Then wrap with HOC.

// Example code
export default withRouter(connect(...))(Component)

Now you can access this.props.history. For example use it with componentDidMount().

componentDidMount() {
  const { history } = this.props;

  if (this.props.authenticated) {
    history.push('/private-route');
  }
}

Solution 2 Much better

Here is example on reacttraining.

Which would perfectly work for you.

But you just need to create LoginRoute to handle problem you described.

const LoginRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
        <Redirect to={{
          pathname: '/private-route',
          state: { from: props.location }
        }} />
      ) : (
        <Component {...props} />
      )
  )} />
);

and inside <Router /> just replace

<Route path="/login" component={Login}/>

with

<LoginRoute path="/login" component={Login}/>

Now everytime somebody will try to access /login route as authenticated user, he will be redirected to /private-route. It's even better solution because it doesn't mount your LoginComponent if condition isn't met.


问:
Mercurial - file history doesn't show the same change on different branches
We have had a production issue where a duplicate change was made on different branches (one of them by accident) and we didn't spot it because the Hg file history didn't show us the change on the second branch.

We have done some analysis and this is fairly easy to replicate (see simple example below). Is this is a feature or a bug?

Steps to replicate:

```<code>hg init Test
cd Test
hg branch "branch 1"
echo "file1" > test.txt
hg add
hg commit -m "Added test.txt - branch 1"
hg branch "branch 2"
echo "file2" > test.txt
hg commit -m "Updated test.txt - branch 2"
hg update "branch 1"
hg branch "branch 3"
echo "file2" > test.txt
hg commit -m "Updated test.txt - branch 3"
</code>```

If we run

```<code>> hg log test.txt
</code>```

Then we only get 2 changes shown in the file history - the change on branch 3 is missing.

```<code>changeset:   1:1754be7ba0aa
branch:      branch 2
user:        chrisgill
date:        Tue Jun 06 14:30:13 2017 +0100
summary:     Updated test.txt - branch 2

changeset:   0:b10c4fde7ba1
branch:      branch 1
user:        chrisgill
date:        Tue Jun 06 14:30:13 2017 +0100
summary:     Added test.txt - branch 1
</code>```

But the history for the repository shows all 3 commits

```<code>> hg log

changeset:   2:f6f91ab357a6
branch:      branch 3
tag:         tip
parent:      0:b10c4fde7ba1
user:        chrisgill
date:        Tue Jun 06 14:30:14 2017 +0100
summary:     Updated test.txt - branch 3

changeset:   1:1754be7ba0aa
branch:      branch 2
user:        chrisgill
date:        Tue Jun 06 14:30:13 2017 +0100
summary:     Updated test.txt - branch 2

changeset:   0:b10c4fde7ba1
branch:      branch 1
user:        chrisgill
date:        Tue Jun 06 14:30:13 2017 +0100
summary:     Added test.txt - branch 1
</code>```

答:
That is documented:

Note:

For performance reasons, 'hg log FILE' may omit duplicate changes
  made on branches and will not show removals or mode changes. To see
  all such changes, use the --removed switch.

Body:
We have had a production issue where a duplicate change was made on different branches (one of them by accident) and we didn't spot it because the Hg file history didn't show us the change on the second branch.

We have done some analysis and this is fairly easy to replicate (see simple example below). Is this is a feature or a bug?

Steps to replicate:

hg init Test
cd Test
hg branch "branch 1"
echo "file1" > test.txt
hg add
hg commit -m "Added test.txt - branch 1"
hg branch "branch 2"
echo "file2" > test.txt
hg commit -m "Updated test.txt - branch 2"
hg update "branch 1"
hg branch "branch 3"
echo "file2" > test.txt
hg commit -m "Updated test.txt - branch 3"

If we run

> hg log test.txt

Then we only get 2 changes shown in the file history - the change on branch 3 is missing.

changeset:   1:1754be7ba0aa
branch:      branch 2
user:        chrisgill
date:        Tue Jun 06 14:30:13 2017 +0100
summary:     Updated test.txt - branch 2

changeset:   0:b10c4fde7ba1
branch:      branch 1
user:        chrisgill
date:        Tue Jun 06 14:30:13 2017 +0100
summary:     Added test.txt - branch 1

But the history for the repository shows all 3 commits

> hg log

changeset:   2:f6f91ab357a6
branch:      branch 3
tag:         tip
parent:      0:b10c4fde7ba1
user:        chrisgill
date:        Tue Jun 06 14:30:14 2017 +0100
summary:     Updated test.txt - branch 3

changeset:   1:1754be7ba0aa
branch:      branch 2
user:        chrisgill
date:        Tue Jun 06 14:30:13 2017 +0100
summary:     Updated test.txt - branch 2

changeset:   0:b10c4fde7ba1
branch:      branch 1
user:        chrisgill
date:        Tue Jun 06 14:30:13 2017 +0100
summary:     Added test.txt - branch 1


问:
How can I display multiple action errors on multiple lines in Struts2?
I have a Struts2 page where I need to display 2 Action Warnings (which are essentially Errors with a flag set): 1 every time the page loads, and another depending on a property of the page.

The code I'm using for adding the action messages:

```<code>addActionWarning(getText(MessageKeys.WARN_PROJECTSTREAM_NOT_SAFE_DELETE));
AddProjectStreamDependencyService addProjectStreamDependencyService = (AddProjectStreamDependencyService) ServiceFactory
.getInstance().createService(AddProjectStreamDependencyService.class);
isUsedByList = addProjectStreamDependencyService.getProjectStreamDependencies(oid,
AddProjectStreamDependencyService.DEPENDENCY_TYPE_IS_USED_BY);
if(!isUsedByList.isEmpty()){
    addActionWarning(getText(MessageKeys.WARN_PROJECTSTREAM_IS_USED_BY_DELETE));
}
</code>```

The jsp code for this page (note that this is imported by every page, so I can't alter this easily):

```<code><c:choose>
  <c:when test='${! empty actionErrors || ! empty actionWarnings}'>
        <s:actionerror id="globalError" cssClass="globalError" escape="false"/>
  </c:when>
  <c:when test='${! empty actionMessages}'>
        <s:actionmessage id="globalError" cssClass="globalInfo" escape="false"/>
  </c:when>
  <c:otherwise>
    <span id="globalError" class="globalError"> </span>
  </c:otherwise>
</c:choose>
</code>```

This results in the following message displayed:

.globalWarning, .globalWarningDiff {
    color: #ef4121;
}
.globalInfo, .globalWarning, .globalError, .globalInfoDiff, .globalWarningDiff, .globalErrorDiff {
    font-size: 11px !important;
    font-weight: bold;
    text-align: left;
    text-transform: uppercase;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="globalError" class="globalWarning">
    warning: <span>This will also delete historical Project Stream information <br>like Level Requests, Builds, Deploys, etc...</span>    warning: <span>This Project Stream is still used as a Dependency by other Project Streams.</span> </span></code>```

As you can see, the second message is on the same line as the first, which looks somewhat sloppy. I have tried fixing this using a Decorator method:

```<code>public Collection<String> getActionErrors() {
    return decorateToStringMethod(super.getActionErrors());
}

protected static Collection<String> decorateToStringMethod(Collection<String> c) {
    return new ArrayList<String>(c) {
        /* (non-Javadoc)
         * @see java.util.AbstractCollection#toString()
         */
        @Override
        public String toString() {
            return StringUtils.join(this, "<br />");
        }
    };
}
</code>```

However, this doesn't fix the issue: it still shows on the same line.

Is there a way to display multiple action errors on the same line?

答:
After some searching through my project source code, I found a Freemarker template where a <#list> was used to iterate over the elements. I edited this template to include <#sep>
</#sep> so it uses
 as a separator. Unfortunately, this doesn't work for the version of Freemarker my project uses (we use 2.3.19, list builtins were added in 2.3.23).

As an alternative, I ended up using <#if item_has_next>
</#if>, which was available in my version. This has solved the issue. Thanks to Roman C for suggesting to check the template.

Body:
I have a Struts2 page where I need to display 2 Action Warnings (which are essentially Errors with a flag set): 1 every time the page loads, and another depending on a property of the page.

The code I'm using for adding the action messages:

addActionWarning(getText(MessageKeys.WARN_PROJECTSTREAM_NOT_SAFE_DELETE));
AddProjectStreamDependencyService addProjectStreamDependencyService = (AddProjectStreamDependencyService) ServiceFactory
.getInstance().createService(AddProjectStreamDependencyService.class);
isUsedByList = addProjectStreamDependencyService.getProjectStreamDependencies(oid,
AddProjectStreamDependencyService.DEPENDENCY_TYPE_IS_USED_BY);
if(!isUsedByList.isEmpty()){
    addActionWarning(getText(MessageKeys.WARN_PROJECTSTREAM_IS_USED_BY_DELETE));
}

The jsp code for this page (note that this is imported by every page, so I can't alter this easily):

<c:choose>
  <c:when test='${! empty actionErrors || ! empty actionWarnings}'>
        <s:actionerror id="globalError" cssClass="globalError" escape="false"/>
  </c:when>
  <c:when test='${! empty actionMessages}'>
        <s:actionmessage id="globalError" cssClass="globalInfo" escape="false"/>
  </c:when>
  <c:otherwise>

  </c:otherwise>
</c:choose>

This results in the following message displayed:

.globalWarning, .globalWarningDiff {
    color: #ef4121;
}
.globalInfo, .globalWarning, .globalError, .globalInfoDiff, .globalWarningDiff, .globalErrorDiff {
    font-size: 11px !important;
    font-weight: bold;
    text-align: left;
    text-transform: uppercase;
}

    warning: This will also delete historical Project Stream information
like Level Requests, Builds, Deploys, etc...    warning: This Project Stream is still used as a Dependency by other Project Streams.

As you can see, the second message is on the same line as the first, which looks somewhat sloppy. I have tried fixing this using a Decorator method:

public Collection<String> getActionErrors() {
    return decorateToStringMethod(super.getActionErrors());
}

protected static Collection<String> decorateToStringMethod(Collection<String> c) {
    return new ArrayList<String>(c) {
        /* (non-Javadoc)
         * @see java.util.AbstractCollection#toString()
         */
        @Override
        public String toString() {
            return StringUtils.join(this, "
");
        }
    };
}

However, this doesn't fix the issue: it still shows on the same line.

Is there a way to display multiple action errors on the same line?

Body:
After some searching through my project source code, I found a Freemarker template where a <#list> was used to iterate over the elements. I edited this template to include <#sep><br /></#sep> so it uses <br /> as a separator. Unfortunately, this doesn't work for the version of Freemarker my project uses (we use 2.3.19, list builtins were added in 2.3.23).

As an alternative, I ended up using <#if item_has_next><br /></#if>, which was available in my version. This has solved the issue. Thanks to Roman C for suggesting to check the template.


问:
Send variables from a python script run on a raspberry pi to webserver
I have a python script running on my raspberry pi that outputs data from sensors connected to the pi's GPIO input. I need a simple way to have this live data on a server accessible from anywhere. I've looked at django framework but it seems like overkill for what I need to do. </p>

答:
You can use Flask instead of Django.

And if you don't want to create server you can use third party Application Like ThingSpeak where you can just post data and you can view your data from anywhere.


问:
Using something other than single or double quotes to set variable?
I have some hard coded text that contains many single quotes and double quotes.

```<code>text = "get in the "van" I said get in the 'van'"
</code>```

I can escape each double quote with \ or I can switch to single quotes on the outside and escape each single quote.

What I'd like to do is just be able to pick something else, like !
Is there something simple I can do?  In Perl I was always able to:

```<code>text = qq!this will use "whatever" I'm happy with!
</code>```

I'm using Python 3.6 if that helps.

答:
Another option to initialize a string is with """ or ''':

text = """get in the "van" I said get in the 'van'"""

Body:
I have some hard coded text that contains many single quotes and double quotes.

text = "get in the "van" I said get in the 'van'"

I can escape each double quote with \ or I can switch to single quotes on the outside and escape each single quote.

What I'd like to do is just be able to pick something else, like !
Is there something simple I can do?  In Perl I was always able to:

text = qq!this will use "whatever" I'm happy with!

I'm using Python 3.6 if that helps.


问:
elastic search sort not working
Hi This is my sample output from elastic search

```<code>"table":{
   "data":[
      {
         "label":"First Label",
         "value":"10"
      },
      {
         "label":"1st Label",
         "value":"9"
      }
   ],
   "details":"Examples set on MSRP, your actual payment may vary based on price set by dealer."
}
</code>```

And i wish to sort this in the ascending order, either thru the colunm label or through value.

The search options i tried are

```<code>sort = [{"data.label" : {"order" : "asc", "mode" : "min", "nested_path" : "data"}}];
sort = [{ "table.data": {"order": "asc"}]
</code>```

But, I am not getting the expected sorted result

Any help on this will be greatly appreciated

答:
Your sort part of the query should be -

```<code>"sort": { "label":   { "order": "desc" }}
</code>```

or

```<code>"sort": { "value":   { "order": "desc" }}
</code>```

or

```<code>"sort": [
        { "label":   { "order": "desc" }},
        { "value": { "order": "desc" }}
    ]
</code>```

Below is the mapping, docs and subsequent query to get inner sorted elements.

```<code>PUT /table
{
  "mappings": {
    "data": {
      "properties": {
        "name": {"type": "string"},
        "subjects": {
          "type": "nested",
          "properties": {
            "name": { "type": "string"},
            "marks":{ "type": "integer"}
          }
        }
      }
    }
  }
}

PUT /table/data/1?pretty
{
  "name":"Ram",
  "subjects":[
    {
      "name":"English",
      "marks":13
    },
    {
      "name":"Hindi",
      "marks":12
    }
    ]
}
PUT /table/data/2?pretty
{
  "name":"Sam",
  "subjects":[
    {
      "name":"Biology",
      "marks":83
    },
    {
      "name":"Maths",
      "marks":68
    }
    ]
}

PUT /table/data/3?pretty
{
  "name":"Jim",
  "subjects":[
    {
      "name":"Chemistry",
      "marks":96
    },
    {
      "name":"Geology",
      "marks":58
    }
    ]
}

GET table/data/_search
{
 "query":{
   "nested":{
     "path":"subjects",
     "query": {
        "match_all": {}
      },
     "inner_hits":{
       "sort":{
         "subjects.marks":{
           "order":"asc"
         }
       }
     }
   }
 }
}
</code>```

Title: elastic search sort not working

Body:
Hi This is my sample output from elastic search

"table":{
   "data":[
      {
         "label":"First Label",
         "value":"10"
      },
      {
         "label":"1st Label",
         "value":"9"
      }
   ],
   "details":"Examples set on MSRP, your actual payment may vary based on price set by dealer."
}

And i wish to sort this in the ascending order, either thru the colunm label or through value.

The search options i tried are

sort = [{"data.label" : {"order" : "asc", "mode" : "min", "nested_path" : "data"}}];
sort = [{ "table.data": {"order": "asc"}]

But, I am not getting the expected sorted result

Any help on this will be greatly appreciated

Body:
Your sort part of the query should be -

"sort": { "label":   { "order": "desc" }}

or

"sort": { "value":   { "order": "desc" }}

or

"sort": [
        { "label":   { "order": "desc" }},
        { "value": { "order": "desc" }}
    ]

Below is the mapping, docs and subsequent query to get inner sorted elements.

PUT /table
{
  "mappings": {
    "data": {
      "properties": {
        "name": {"type": "string"},
        "subjects": {
          "type": "nested",
          "properties": {
            "name": { "type": "string"},
            "marks":{ "type": "integer"}
          }
        }
      }
    }
  }
}

PUT /table/data/1?pretty
{
  "name":"Ram",
  "subjects":[
    {
      "name":"English",
      "marks":13
    },
    {
      "name":"Hindi",
      "marks":12
    }
    ]
}
PUT /table/data/2?pretty
{
  "name":"Sam",
  "subjects":[
    {
      "name":"Biology",
      "marks":83
    },
    {
      "name":"Maths",
      "marks":68
    }
    ]
}

PUT /table/data/3?pretty
{
  "name":"Jim",
  "subjects":[
    {
      "name":"Chemistry",
      "marks":96
    },
    {
      "name":"Geology",
      "marks":58
    }
    ]
}

GET table/data/_search
{
 "query":{
   "nested":{
     "path":"subjects",
     "query": {
        "match_all": {}
      },
     "inner_hits":{
       "sort":{
         "subjects.marks":{
           "order":"asc"
         }
       }
     }
   }
 }
}


问:
Firebase Google sign in: get user location
Is it possible to access a Google user's location once they've signed in (using GIDSignIn)?

I have no trouble accessing a user's name, email, and photo.

答:
I am not 100% sure if user location is accessible through GIDSignIn but according to their documentation, you can request for additional scope of information; aside from the basic info, from the user. Here's even more info about it.

Here's the extensive list of Google's current OAuth 2.0 API Scopes


问:
How can I write a piece of Java an code that checks if any character of a string is convertible to an integer between 0 and 9?
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

```<code>String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}
</code>```

where IntegerFormat Exception is something like

```<code>public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}
</code>```

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

```<code>at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)
</code>```

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

答:
You can use Character class isdigit api or other api to test if it is digit or not</p>

```<code>String s = "1234/&&56";
         for(int i=0;i<s.length();i++){
             char ch=s.charAt(i);
             if((Character.isDigit(ch))){
                 System.out.println(ch);
             }
         }
</code>```

Body:
How can I write a piece of Java code that checks if a string is convertible to an integer, that is if any character of it is convertible to an integer between 0 and 9 ? I thought of something like this:

String s = "...";

for (int i = 0; i < s.length(); i++)

{

    int h = Integer.parseInt(s.substring(i, i + 1));
    if (h < 0 || h > 9)
        throw new IntegerFormatException();
}

catch (IntegerFormatException e)

{

    System.out.println("This is not an integer");

}

where IntegerFormat Exception is something like

public class IntegerFormatException extends Exception

{

    public IntegerFormatException()
    {
        super ("This string isn't convertible to  an integer");
    }
    public IntegerFormatException(String message)
    {
        super (message);
    }

}

But if I then try the code with, say, "8&35" as the string I don't get my message "This is not an integer", but I get and IDE automatic red ink message stating

Exception in thread "main" java.lang.NumberFormatException: For input string: "&"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at project.pkg9.pkg2.Project92.main(Project92.java:60)

Java Result: 1

Is my code wrong ? If yes, how can I fix it ? Many thanks in advance for all your answers.

Body:
You can use Character class isdigit api or other api to test if it is digit or not

String s = "1234/&&56";
         for(int i=0;i<s.length();i++){
             char ch=s.charAt(i);
             if((Character.isDigit(ch))){
                 System.out.println(ch);
             }
         }


问:
Redirect standard output and standard err when executing a method
I have a program that tests each method in a Test# subclass and outputs XML in JUnit's XML format.

For instance:

```<code>class ExampleTest : Test
{
  Void testOne()
  {
   ...
  }
}
</code>```

I want to execute the testOne method and capture the standard output and standard error produced in it. This out and err output will be included in the XML report.

My first idea was to look at sys::Env. The environment class sys::Env has err and out but are readonly.

My second idea is that sys::Process can be launched for each test method and redirect sys::Process#.err and sys::Process#.out in it, but I'm afraid it will be very slow.

There is other way to do it?

答:
You won't be able to redirect output from your current process (and really should not).

If the output absolutely has to be stdout/err - you'll need to go the Process route.  You'll take the fork/jvm/stream setup hit, but that may be negligible compared to your test runtime.

A better option would be to log using the Logging API - which will give more control over what gets logged, and where things go.

Body:
I have a program that tests each method in a Test# subclass and outputs XML in JUnit's XML format.

For instance:

class ExampleTest : Test
{
  Void testOne()
  {
   ...
  }
}

I want to execute the testOne method and capture the standard output and standard error produced in it. This out and err output will be included in the XML report.

My first idea was to look at sys::Env. The environment class sys::Env has err and out but are readonly.

My second idea is that sys::Process can be launched for each test method and redirect sys::Process#.err and sys::Process#.out in it, but I'm afraid it will be very slow.

There is other way to do it?


问:
Coloring non generic contours
I am using C# and I am drawing the picture programmatically (since the picture can differ according to run time values of the parameters in my application). I end up with non generic closed contours (which consist of straight lines and curves). Now I need to fill those with different colors.
Any idea how can I accomplish this?

Thanks in advance.

答: If it is Winforms I think best one is FillRegion. Or try Flood Fill. Unfortunately this is not that easy because there no native Flood fill in .net. But there are free implementations and ways to import it from GDI</p>

Title: Coloring non generic contours


问:
Unknown error inserting in table in Python 3
I'm trying to do a class to access a database in Sqlite3 in Python 3.
The database was created and when I check if its inserting on the database I get the following error on the second line of the init method:

```<code>File "~/implementacao 2/Dabase_Connection.py", line 16, in __init__
    self.insert_in_database('database_name.db','table_name', '(\'111\',\'qqqq\')')
  File "~/implementacao 2/Dabase_Connection.py", line 33, in insert_in_database
    c.execute('INSERT INTO '+ table_name + ' VALUES ( '+ data +' )')# Insert a row of data
sqlite3.OperationalError: near ",": syntax error
</code>```

The code is this one:

```<code>def __init__(self):
        # self.create_database('database_name.db', 'table_name', 'id TEXT, data TEXT')
        self.insert_in_database('database_name.db','table_name', '(\'111\',\'qqqq\')')
        # self.delete_from_database('database_name.db', 'table_name', 'data1')
        # self.update_in_database('database_name.db','table_name', 'data', 'data_nova', 'data1')
        # self.insert_all_in_database('database_name.db', 'table_name', [('data1','data1'),('data2','data2'),('data3','data3'),('data4','data4')])
        # self.Search_in_database('database_name.db', 'table_name', 'data')

def create_database(self,database_name,table_name,table_args):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('CREATE TABLE '+ table_name + '(' + table_args + ')')# Create table
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

# INSERT INTO prontuarios VALUES(id,prontuario);
def insert_in_database(self,database_name,table_name, data):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('INSERT INTO '+ table_name + ' VALUES ( '+ data +' )')# Insert a row of data
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

def delete_from_database(self,database_name,table_name, chave):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('DELETE FROM ' + table_name +' WHERE Id= '+ chave +' ; ')# Insert a row of data
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

def update_in_database(self,database_name,table_name, table_field, data, chave):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('UPDATE ' +table_name+ ' SET ' + table_field + ' = ' + data + ' WHERE id = ' + chave+' ;')# Insert a row of data
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

# persons = [("Hugo", "Boss"),("Calvin", "Klein")]
# Fill the table conn.executemany("'"insert into person(firstname, lastname) values (?, ?)", persons)

def insert_all_in_database(self,database_name,table_name, data):
    data_interrog = self.get_parameters(data)
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.executemany('insert into ' + table_sifnature + ' values ( '+ data_interrog +' ) ', data)
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

def Search_in_database(self,database_name,table_name, fields):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    # Print the table contents
    for row in c.execute('select '+ fields + ' from ' +table_name):
        print(row)
</code>```

答:
Your code is vulnerable to Sql Injection!

The python pages quote say something like:

Usually your SQL operations will need to use values from Python
variables. You shouldn’t assemble your query using Python’s string
operations because doing so is insecure; it makes your program
vulnerable to an SQL injection attack

As mentioned in other comments, I strongly recommend you use an ORM like SQLAlchemy instead of writing bare sql queries like you did.

I usually use something like this when I'm trying to connect to to an sqlite3 db:

```<code>class SqliteDB:
    def __init__(self):
        self.parent_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        self.db_path = os.path.join(self.parent_directory, 'db.sqlite3')
        self.db_connection = sqlite3.connect(self.db_path)
        self.db_cursor = self.db_connection.cursor()

    def execute(self, query, args=''):
        return self.db_cursor.execute(query, args)

    def commit(self):
        self.db_connection.commit()

    def close(self):
        self.db_connection.close()
</code>```

Based on the above class, you can easily build the other methods you need (update, delete etc).

Body:
I'm trying to do a class to access a database in Sqlite3 in Python 3.
The database was created and when I check if its inserting on the database I get the following error on the second line of the init method:

File "~/implementacao 2/Dabase_Connection.py", line 16, in __init__
    self.insert_in_database('database_name.db','table_name', '(\'111\',\'qqqq\')')
  File "~/implementacao 2/Dabase_Connection.py", line 33, in insert_in_database
    c.execute('INSERT INTO '+ table_name + ' VALUES ( '+ data +' )')# Insert a row of data
sqlite3.OperationalError: near ",": syntax error

The code is this one:

def __init__(self):
        # self.create_database('database_name.db', 'table_name', 'id TEXT, data TEXT')
        self.insert_in_database('database_name.db','table_name', '(\'111\',\'qqqq\')')
        # self.delete_from_database('database_name.db', 'table_name', 'data1')
        # self.update_in_database('database_name.db','table_name', 'data', 'data_nova', 'data1')
        # self.insert_all_in_database('database_name.db', 'table_name', [('data1','data1'),('data2','data2'),('data3','data3'),('data4','data4')])
        # self.Search_in_database('database_name.db', 'table_name', 'data')

def create_database(self,database_name,table_name,table_args):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('CREATE TABLE '+ table_name + '(' + table_args + ')')# Create table
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

# INSERT INTO prontuarios VALUES(id,prontuario);
def insert_in_database(self,database_name,table_name, data):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('INSERT INTO '+ table_name + ' VALUES ( '+ data +' )')# Insert a row of data
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

def delete_from_database(self,database_name,table_name, chave):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('DELETE FROM ' + table_name +' WHERE Id= '+ chave +' ; ')# Insert a row of data
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

def update_in_database(self,database_name,table_name, table_field, data, chave):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.execute('UPDATE ' +table_name+ ' SET ' + table_field + ' = ' + data + ' WHERE id = ' + chave+' ;')# Insert a row of data
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

# persons = [("Hugo", "Boss"),("Calvin", "Klein")]
# Fill the table conn.executemany("'"insert into person(firstname, lastname) values (?, ?)", persons)

def insert_all_in_database(self,database_name,table_name, data):
    data_interrog = self.get_parameters(data)
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    c.executemany('insert into ' + table_sifnature + ' values ( '+ data_interrog +' ) ', data)
    conn.commit() # Save (commit) the changes
    conn.close()# We can also close the connection if we are done with it.

def Search_in_database(self,database_name,table_name, fields):
    conn = sqlite3.connect(database_name)
    c = conn.cursor()
    # Print the table contents
    for row in c.execute('select '+ fields + ' from ' +table_name):
        print(row)

Body:
Your code is vulnerable to Sql Injection!

The python pages quote say something like:

Usually your SQL operations will need to use values from Python
variables. You shouldn’t assemble your query using Python’s string
operations because doing so is insecure; it makes your program
vulnerable to an SQL injection attack

As mentioned in other comments, I strongly recommend you use an ORM like SQLAlchemy instead of writing bare sql queries like you did.

I usually use something like this when I'm trying to connect to to an sqlite3 db:

class SqliteDB:
    def __init__(self):
        self.parent_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        self.db_path = os.path.join(self.parent_directory, 'db.sqlite3')
        self.db_connection = sqlite3.connect(self.db_path)
        self.db_cursor = self.db_connection.cursor()

    def execute(self, query, args=''):
        return self.db_cursor.execute(query, args)

    def commit(self):
        self.db_connection.commit()

    def close(self):
        self.db_connection.close()

Based on the above class, you can easily build the other methods you need (update, delete etc).


问:
How to allow role based login in Laravel 5.4?
Using the function below I was able to add active flag, so that only those users who are active can login.

Now I have another flag called role and I wish to allow only those users with role 1 or 2 to login.

```<code>public function credentials(Request $request)
{
    return [
        'email' => $request->email,
        'password' => $request->password,
        'active' => 1,
    ];
}
</code>```

答:
You may like to use middleware </p>

```<code><?php

namespace App\Http\Middleware;

use Closure;

class CheckRole
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $role
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {
        if (! $request->user()->hasRole($role)) {
            // Redirect...
        }

        return $next($request);
    }

}
</code>```

Body:
Using the function below I was able to add active flag, so that only those users who are active can login.

Now I have another flag called role and I wish to allow only those users with role 1 or 2 to login.

public function credentials(Request $request)
{
    return [
        'email' => $request->email,
        'password' => $request->password,
        'active' => 1,
    ];
}

Body:
You may like to use middleware

<?php

namespace App\Http\Middleware;

use Closure;

class CheckRole
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $role
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {
        if (! $request->user()->hasRole($role)) {
            // Redirect...
        }

        return $next($request);
    }

}


问:
Using Jolt, How do I remove a field "last_update" from everywhere in a JSON string?
I have a JSON array of objects and in many of the objects, at various points, there's a "last_update" field. ("Person" object may have a "Jobs" array and each Job in Jobs array may have an last_update, as well as the parent Person, as well as each Address in the "Addresses" object, etc.  The "last_updated" field is not always at the same depth for various objects and in some objects may appear in multiple places.

I want to remove any mention of "last_update" no matter where in the JSON tree it lands.

If I was editing the JSON in Vim, I'd probably try using something like s/last_updated.*?//g.

答: It does not have OOTB support for that.</p>

Body: It does not have OOTB support for that.


问:
Right way to transfer a CSV file to a BI application?
We are doing a BI application, and our customers send us data files daily. We are doing data exchange using CSV files, because our customers are used to watch data with Excel, and they are not ready yet to use an API on their system (maybe in few years we will be able to use XML/JSON webservice, we hope).

Currently the data transfer is made with FTP (SFTP in fact). Our customers upload file automatically on an FTP server, and we have a CRON task that watches if a file has been sent.

But there are many disadvantages with that:

We cannot know with reliability if the upload is done, or still in progress (we asked them to upload a file with a temporary name, and move it after, but many of them still don't do that)

So, we can try to guess, and consider upload is done if enough time has passed. But FTP protocol doesn't allow to get server time, and time can be desynced. So we can upload an empty file and read it's date to know the time of the server. But we need write permission to do that...

FTP protocol allow to pause upload...

Then, we are considering to transfer files by asking our customer to upload them directly on our application, using HTTPS. This is more reliable, but less convenient:

Our customer cannot check the content of the file after upload

We have to be careful with upload size and timeout on our server

Files can be quite large (up to 300Mo), so it's better to zip them before upload (can reduce size to 10%).

This is more work for us than just an FTP server (we need to create UI, upload progress, list files to download them back, ...)

There is other solutions? How usually BI applications share data? Is HTTPS a good solutions for us?

答:
We found a solution which is a webdav server. We are using Nextcloud, it provides an online interface, and script access with webdav protocol.

It's more reliable than FTP, because the file appear only when upload is done.

And it's better than HTTP upload on our application. We don't have to handle file upload, create interfaces, ...


问:
Lambda variable names - to short name, or not to short name?
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read.  Here is an example:

```<code>var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
                                      .OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
                                                    a => a);
</code>```

Some question this naming, and would prefer to see long typed out names, like this:

```<code>var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
                                      .OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
                                                    theInfoId2 => theInfoId2);
</code>```

Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.

Without getting caught up in the silly naming examples I used above, what is the general consensus on Lambda variable names?  To short name, or not to short name?

答: As a general rule, I think the more explicit you are with variable/object/method names the better.  Since we often spend most of our time reading other people's code, the easier it us to understand the faster you can get your focus off the syntax and onto the logic.  These days with IntelliSense and the like, it's not really a burden to err on the side of clarity whenever possible.</p>

OwnerDisplayName: TheSoftwareJedi

Body:
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read.  Here is an example:

var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
                                      .OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
                                                    a => a);

Some question this naming, and would prefer to see long typed out names, like this:

var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
                                      .OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
                                                    theInfoId2 => theInfoId2);

Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.

Without getting caught up in the silly naming examples I used above, what is the general consensus on Lambda variable names?  To short name, or not to short name?

LastEditorDisplayName: TheSoftwareJedi

OwnerDisplayName: Johnny Wey


问:
Get value from anonymous block inside a procedure in oracle
I have created a stored procedure which calls a function which returns boolean.

We are getting the schema name the function is under at run time, so we are creating the statement as a string by concatenation, and executing the function in an anonymous block dynamically.

```<code>CREATE OR REPLACE PROCEDURE usp_proc
(
        variable declarations
)
as
var1 varchar2(50);
var2 varchar2(50);
var3 varchar3(50);
begin
    execute immediate
        'declare result boolean ; ConversionFactor number; res varchar2(10); begin  result:= '||schemaname||'fn_name('''||var1||''', '''||var2||''',ConversionFactor,'''||var3||''');'||
                    ' if(result=False) then res:=''False'';'||
                    ' ELSE res:=''True''; END IF; end;';

    stmt:='select Weight*ConversionFactor  from table'
       Open cur for stmt;
    END;
</code>```

I need to use the ConversionFactor variable outside the anonymous block. How can I gets its value to use later in the procedure?

答:
Rather than define ConversionFactor as a local variable inside your dynamic PL/SQL block, you can declare it in your procedure and pass it as an OUT bind variable. You can get the res value back the same way too. Your var1, var2 and var3 values can/should be passed as bind variables as well, rather than concatenating them into the call.

Demo using an anonymous block instead of a procedure, as yours has some other things wrong anyway, and a dummy function in the specified schema:

```<code>declare
  var1 varchar2(50);
  var2 varchar2(50);
  var3 varchar2(50);
  schemaname varchar2(30);
  res varchar2(5);
  ConversionFactor number;
begin
  schema := 'SOME_SCHEMA';
  -- also assign values to var1, var2 and var, presumably

  execute immediate
    'declare result boolean;'
      || 'begin'
      || ' result := '||schemaname||'.fn_name(:var1, :var2, :ConversionFactor, :var3);'
      || ' :res := case when result then ''True'' else ''False'' end;'
      || 'end;'
  using var1, var2, out ConversionFactor, var3, out res;

  dbms_output.put_line('Got result: ' || res);
  dbms_output.put_line('Got ConversionFactor: ' || ConversionFactor);
end;
/

Got result: True
Got ConversionFactor: 42

PL/SQL procedure successfully completed.
</code>```

Note the out ConversionFactor, and the out res, so mark them as OUT bind variables. The others are left to default to IN. (I've also added a missing period between the schema and function names).

Body:
I have created a stored procedure which calls a function which returns boolean.

We are getting the schema name the function is under at run time, so we are creating the statement as a string by concatenation, and executing the function in an anonymous block dynamically.

CREATE OR REPLACE PROCEDURE usp_proc
(
        variable declarations
)
as
var1 varchar2(50);
var2 varchar2(50);
var3 varchar3(50);
begin
    execute immediate
        'declare result boolean ; ConversionFactor number; res varchar2(10); begin  result:= '||schemaname||'fn_name('''||var1||''', '''||var2||''',ConversionFactor,'''||var3||''');'||
                    ' if(result=False) then res:=''False'';'||
                    ' ELSE res:=''True''; END IF; end;';

    stmt:='select Weight*ConversionFactor  from table'
       Open cur for stmt;
    END;

I need to use the ConversionFactor variable outside the anonymous block. How can I gets its value to use later in the procedure?

Body:
Rather than define ConversionFactor as a local variable inside your dynamic PL/SQL block, you can declare it in your procedure and pass it as an OUT bind variable. You can get the res value back the same way too. Your var1, var2 and var3 values can/should be passed as bind variables as well, rather than concatenating them into the call.

Demo using an anonymous block instead of a procedure, as yours has some other things wrong anyway, and a dummy function in the specified schema:

declare
  var1 varchar2(50);
  var2 varchar2(50);
  var3 varchar2(50);
  schemaname varchar2(30);
  res varchar2(5);
  ConversionFactor number;
begin
  schema := 'SOME_SCHEMA';
  -- also assign values to var1, var2 and var, presumably

  execute immediate
    'declare result boolean;'
      || 'begin'
      || ' result := '||schemaname||'.fn_name(:var1, :var2, :ConversionFactor, :var3);'
      || ' :res := case when result then ''True'' else ''False'' end;'
      || 'end;'
  using var1, var2, out ConversionFactor, var3, out res;

  dbms_output.put_line('Got result: ' || res);
  dbms_output.put_line('Got ConversionFactor: ' || ConversionFactor);
end;
/

Got result: True
Got ConversionFactor: 42

PL/SQL procedure successfully completed.

Note the out ConversionFactor, and the out res, so mark them as OUT bind variables. The others are left to default to IN. (I've also added a missing period between the schema and function names).


问:
How to get aws instance metadata remotely using CLI?
I am very new to AWS. I have a Windows Server EC2 instance. I installed AWS CLI on my laptop. Then I opened a CMD window, typed in "aws configure", put in the access key credentials, and was able to connect to the EC2.

From here, how do I get the http://169.254.169.254/latest/meta-data working? How do I retrieve some meta data?

答:
On your Laptop

On your local machine you only can use the cli to retrieve metadata about your instance. Simply use this aws cli command:

```<code>aws ec2 describe-instance-attribute --instance-id <your-ec_instance_id e.g. i-ab12345> --attribute instanceType --region <your_region e.g. eu-west-1>
</code>```

Documentation: http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instance-attribute.html

On your EC2-Instance only:
On your instance you can use the cli (like above) and the following:

PowerShell >3.0:

```<code>Invoke-RestMethod -uri http://169.254.169.254/latest/meta-data/instance-type
</code>```

Documentation: http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html

Or you can install "curl for windows" and run:

```<code>curl http://169.254.169.254/latest/meta-data/instance-type
</code>```

Body:
On your Laptop

On your local machine you only can use the cli to retrieve metadata about your instance. Simply use this aws cli command:

aws ec2 describe-instance-attribute --instance-id <your-ec_instance_id e.g. i-ab12345> --attribute instanceType --region <your_region e.g. eu-west-1>

Documentation: http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instance-attribute.html

On your EC2-Instance only:
On your instance you can use the cli (like above) and the following:

PowerShell >3.0:

Invoke-RestMethod -uri http://169.254.169.254/latest/meta-data/instance-type

Documentation: http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html

Or you can install "curl for windows" and run:

curl http://169.254.169.254/latest/meta-data/instance-type