问:
Add different text to the last line of a string - C# LINQ
I want to take an input string and add " ' + " to the end of each line except the last line, on the last line I want to add " ' ; "

The following allows me to add " ' + " to every line:

```<code>string[] outputArr = outputRaw
  .Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
  .Select((stringval, stringindex) => "'" + stringval + " ' + ")
  .ToArray();

this.Output = String.Join(Environment.NewLine, outputArr);
</code>```

Can this be adjusted to identify the last line and add different characters?

答:
Maybe what you are after is</p>

```<code>string[] outputArr = outputRaw
   .Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
   .Select((stringval, stringindex) => "'" + stringval + " '")
   .ToArray();

this.Output = String.Join($" + {Environment.NewLine}", outputArr) + ";";
</code>```

Body:
I want to take an input string and add " ' + " to the end of each line except the last line, on the last line I want to add " ' ; "

The following allows me to add " ' + " to every line:

string[] outputArr = outputRaw
  .Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
  .Select((stringval, stringindex) => "'" + stringval + " ' + ")
  .ToArray();

this.Output = String.Join(Environment.NewLine, outputArr);

Can this be adjusted to identify the last line and add different characters?

Body:
Maybe what you are after is

string[] outputArr = outputRaw
   .Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
   .Select((stringval, stringindex) => "'" + stringval + " '")
   .ToArray();

this.Output = String.Join($" + {Environment.NewLine}", outputArr) + ";";


来源: stackexchange

问:
Search with queries constrained to elements using search:search
What i want to do is similar in the following link but we want it using search:search:

Queries Constrained to Elements

Basically we have 2 xmls like the following:

XML-1

<rootElement>
   <id>7635940284725382300</id>
   <parentElement>
      <childElement1>ce1-A</childElement1>
      <childElement2>ce2-1</childElement2>
   </parentElement>
   <parentElement>
      <childElement1>ce1-B</childElement1>
      <childElement2>ce2-2</childElement2>
      </parentElement>
   <parentElement>
      <childElement1>ce1-C</childElement1>
      <childElement2>ce2-3</childElement2>
   </parentElement>
</rootElement>
```

<h3>XML-2</h3>

<pre class="lang-xml prettyprint-override"><code><rootElement>
   <id>7635940284725382398</id>
   <parentElement>
      <childElement1>ce1-A</childElement1>
      <childElement2>ce2-2</childElement2>
   </parentElement>
   <parentElement>
      <childElement1>ce1-B</childElement1>
      <childElement2>ce2-3</childElement2>
      </parentElement>
   <parentElement>
      <childElement1>ce1-C</childElement1>
      <childElement2>ce2-4</childElement2>
   </parentElement>
</rootElement>
</code>```

So now what i want to do is to have a match for childElement1 and childElement2 within the same parentElement.

For example:

If i search with values childElement1 = ce1-B and childElement2 = ce2-3, it should only give me XML-2 and not return XML-1.

We have achieved this using the cts:search query as explained in the link:

```<code>cts:search (/,
     cts:element-query (
         xs:QName ('parentElement'),
         cts:and-query ((
             cts:element-value-query(xs:QName('childElement1'), 'ce1-B', 'exact'),
             cts:element-value-query(xs:QName('childElement2'), 'ce2-3', 'exact')
         ))
     )
)
</code>```

Question:

We are using search:search with different search:constraints? I have read about using container for this but there are no good examples to show how it can be used.

Here is our sample search:search, so need to tweak this to have the same functionality as that shown by cts:search query shown above:

import module namespace search = "http://marklogic.com/appservices/search" at "/MarkLogic/appservices/search/search.xqy";

search:search("childElement1:ce1-B AND childElement2:ce2-3 sort:childElement2ASC"
    , <options xmlns="http://marklogic.com/appservices/search">
        <term>
            <term-option xmlns="http://marklogic.com/appservices/search">unstemmed</term-option>
            <empty apply="all-results" />
            <term-option>case-insensitive</term-option>
            <term-option>wildcarded</term-option>
        </term>

        <transform-results apply="transformed-result" ns="http://isearchgui/search" at="/customResultSet.xqy" />

        <search:constraint name="childElement1">
            <search:range type="xs:string" facet="false" collation="http://marklogic.com/collation/en">
                <search:path-index ns="http://my.search.com/something">//childElement1</search:path-index>
            </search:range>
        </search:constraint>

        <search:constraint name="childElement2">
            <search:range type="xs:string" facet="false" collation="http://marklogic.com/collation/en">
                <search:path-index ns="http://my.search.com/something">//childElement2</search:path-index>
            </search:range>
        </search:constraint>

        <search:operator name="sort">
            <search:state name="childElement1ASC">
                <search:sort-order direction="ascending" type="xs:string">
                <search:path-index ns="http://my.search.com/something">//childElement1</search:path-index>
                </search:sort-order>
            </search:state>
            <search:state name="childElement1DES">
                <search:sort-order direction="descending" type="xs:string">
                <search:path-index ns="http://my.search.com/something">//childElement1</search:path-index>
                </search:sort-order>
            </search:state>
            <search:state name="childElement2ASC">
                <search:sort-order direction="ascending" type="xs:string">
                <search:path-index ns="http://my.search.com/something">//childElement2</search:path-index>
                </search:sort-order>
            </search:state>
            <search:state name="childElement2DES">
                <search:sort-order direction="descending" type="xs:string">
                <search:path-index ns="http://my.search.com/something">//childElement2</search:path-index>
                </search:sort-order>
            </search:state>
        </search:operator>
    </options>
    , 0
    , 15);
```

Hope this helps to answer.

答:
You are on the right track. Use the container option, which works like any other constraint option, then wrap your nested query in parenthesis.

For example:

```<code>search:parse('contain:(test one two)',
  <options xmlns="http://marklogic.com/appservices/search">
    <constraint name="contain">
      <container>
        <element ns="" name="parentElement"/>
      </container>
    </constraint>
  </options>)
</code>```

=>

```<code>  <cts:element-query xmlns:cts="http://marklogic.com/cts">
    <cts:element>parentElement</cts:element>
    <cts:and-query>
      <cts:word-query>
        <cts:text xml:lang="en">test</cts:text>
      </cts:word-query>
      <cts:word-query>
        <cts:text xml:lang="en">one</cts:text>
      </cts:word-query>
      <cts:word-query>
        <cts:text xml:lang="en">two</cts:text>
      </cts:word-query>
    </cts:and-query>
  </cts:element-query>
</code>```

So in your case you would have the main-search string as :

```<code>search:search('contain:(childElement1:ce1-B AND childElement2:ce2-3) sort:childElement2ASC', <options ....)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What i want to do is similar in the following link but we want it using search:search:

Queries Constrained to Elements

Basically we have 2 xmls like the following:

XML-1

<rootElement>
   <id>7635940284725382300</id>
   <parentElement>
      <childElement1>ce1-A</childElement1>
      <childElement2>ce2-1</childElement2>
   </parentElement>
   <parentElement>
      <childElement1>ce1-B</childElement1>
      <childElement2>ce2-2</childElement2>
      </parentElement>
   <parentElement>
      <childElement1>ce1-C</childElement1>
      <childElement2>ce2-3</childElement2>
   </parentElement>
</rootElement>

XML-2

<rootElement>
   <id>7635940284725382398</id>
   <parentElement>
      <childElement1>ce1-A</childElement1>
      <childElement2>ce2-2</childElement2>
   </parentElement>
   <parentElement>
      <childElement1>ce1-B</childElement1>
      <childElement2>ce2-3</childElement2>
      </parentElement>
   <parentElement>
      <childElement1>ce1-C</childElement1>
      <childElement2>ce2-4</childElement2>
   </parentElement>
</rootElement>

So now what i want to do is to have a match for childElement1 and childElement2 within the same parentElement.

For example:

If i search with values childElement1 = ce1-B and childElement2 = ce2-3, it should only give me XML-2 and not return XML-1.

We have achieved this using the cts:search query as explained in the link:

cts:search (/,
     cts:element-query (
         xs:QName ('parentElement'),
         cts:and-query ((
             cts:element-value-query(xs:QName('childElement1'), 'ce1-B', 'exact'),
             cts:element-value-query(xs:QName('childElement2'), 'ce2-3', 'exact')
         ))
     )
)

Question:

We are using search:search with different search:constraints? I have read about using container for this but there are no good examples to show how it can be used.

Here is our sample search:search, so need to tweak this to have the same functionality as that shown by cts:search query shown above:

import module namespace search = "http://marklogic.com/appservices/search" at "/MarkLogic/appservices/search/search.xqy";

search:search("childElement1:ce1-B AND childElement2:ce2-3 sort:childElement2ASC"
    , <options xmlns="http://marklogic.com/appservices/search">
        <term>
            <term-option xmlns="http://marklogic.com/appservices/search">unstemmed</term-option>
            <empty apply="all-results" />
            <term-option>case-insensitive</term-option>
            <term-option>wildcarded</term-option>
        </term>

        <transform-results apply="transformed-result" ns="http://isearchgui/search" at="/customResultSet.xqy" />

        <search:constraint name="childElement1">
            <search:range type="xs:string" facet="false" collation="http://marklogic.com/collation/en">
                <search:path-index ns="http://my.search.com/something">//childElement1</search:path-index>
            </search:range>
        </search:constraint>

        <search:constraint name="childElement2">
            <search:range type="xs:string" facet="false" collation="http://marklogic.com/collation/en">
                <search:path-index ns="http://my.search.com/something">//childElement2</search:path-index>
            </search:range>
        </search:constraint>

        <search:operator name="sort">
            <search:state name="childElement1ASC">
                <search:sort-order direction="ascending" type="xs:string">
                <search:path-index ns="http://my.search.com/something">//childElement1</search:path-index>
                </search:sort-order>
            </search:state>
            <search:state name="childElement1DES">
                <search:sort-order direction="descending" type="xs:string">
                <search:path-index ns="http://my.search.com/something">//childElement1</search:path-index>
                </search:sort-order>
            </search:state>
            <search:state name="childElement2ASC">
                <search:sort-order direction="ascending" type="xs:string">
                <search:path-index ns="http://my.search.com/something">//childElement2</search:path-index>
                </search:sort-order>
            </search:state>
            <search:state name="childElement2DES">
                <search:sort-order direction="descending" type="xs:string">
                <search:path-index ns="http://my.search.com/something">//childElement2</search:path-index>
                </search:sort-order>
            </search:state>
        </search:operator>
    </options>
    , 0
    , 15);

Hope this helps to answer.

Body:
You are on the right track. Use the container option, which works like any other constraint option, then wrap your nested query in parenthesis.

For example:

search:parse('contain:(test one two)',
  <options xmlns="http://marklogic.com/appservices/search">
    <constraint name="contain">
      <container>
        <element ns="" name="parentElement"/>
      </container>
    </constraint>
  </options>)

=>

  <cts:element-query xmlns:cts="http://marklogic.com/cts">
    <cts:element>parentElement</cts:element>
    <cts:and-query>
      <cts:word-query>
        <cts:text xml:lang="en">test</cts:text>
      </cts:word-query>
      <cts:word-query>
        <cts:text xml:lang="en">one</cts:text>
      </cts:word-query>
      <cts:word-query>
        <cts:text xml:lang="en">two</cts:text>
      </cts:word-query>
    </cts:and-query>
  </cts:element-query>

So in your case you would have the main-search string as :

search:search('contain:(childElement1:ce1-B AND childElement2:ce2-3) sort:childElement2ASC', <options ....)


问:
How to use Google libphonenumber in Typescript?
I want to use Google libphonenumber in my angular project using Typescript. I have searched a lot on the internet and found a lot of stuff but could not find anything that could serve my purpose.

Most of the content available shows the code in JavaScript. If I use the same code in typescript, it shows a lot of errors like cannot find name require or module not found. Please tell me how/where/what to write the code.

Also, plz tell me which package to install as there are many - libphonenumber, google-libphonenumber, angular-libphonenumber

答:
When dealing with CommonJS libraries, in TypeScript just like this google-libphonenumber, I'd like to suggest 2 ways about it (Tested by me and works well).

Initially, I'd like to suggest to install from NPM just like this: npm install --save google-libphonenumber.

Then, here we go both ways of using it:

1st Method

Just import it directly

```<code>import libphonenumber from 'google-libphonenumber';
class Something {
    constructor() {//Just example, you can chose any method
        const phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
        console.log( phoneUtil.getSupportedRegions() );//It should works and give you some output
    }
}
</code>```

2nd Method

You still can make the power of Typescript typing or just use the existing one by: npm install --save-dev @types/google-libphonenumber.

Since you said that you using Angular, so you can declare that typing just installed at src/tsconfig.app.json ( I am using Angular Version 7 ). Here is an example I have made:

```<code>{
  ...
  "compilerOptions": {
    ...
    "types": [
      "google-libphonenumber"
    ]
  },
  ...
}
</code>```

Then you can just import it like usual, in Typescript "typings" way like follow:

```<code>import { PhoneNumberUtil } from 'google-libphonenumber';

class Something {
    constructor() {//Just example, you can chose any method
        const phoneUtil: PhoneNumberUtil = PhoneNumberUtil.getInstance();
        console.log( phoneUtil.getSupportedRegions() );//It should works and give you some output
    }
}
</code>```

Body:
When dealing with CommonJS libraries, in TypeScript just like this google-libphonenumber, I'd like to suggest 2 ways about it (Tested by me and works well).

Initially, I'd like to suggest to install from NPM just like this: npm install --save google-libphonenumber.

Then, here we go both ways of using it:

1st Method

Just import it directly

import libphonenumber from 'google-libphonenumber';
class Something {
    constructor() {//Just example, you can chose any method
        const phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
        console.log( phoneUtil.getSupportedRegions() );//It should works and give you some output
    }
}

2nd Method

You still can make the power of Typescript typing or just use the existing one by: npm install --save-dev @types/google-libphonenumber.

Since you said that you using Angular, so you can declare that typing just installed at src/tsconfig.app.json ( I am using Angular Version 7 ). Here is an example I have made:

{
  ...
  "compilerOptions": {
    ...
    "types": [
      "google-libphonenumber"
    ]
  },
  ...
}

Then you can just import it like usual, in Typescript "typings" way like follow:

import { PhoneNumberUtil } from 'google-libphonenumber';

class Something {
    constructor() {//Just example, you can chose any method
        const phoneUtil: PhoneNumberUtil = PhoneNumberUtil.getInstance();
        console.log( phoneUtil.getSupportedRegions() );//It should works and give you some output
    }
}


问:
How to get day month and year in integer from given string date in pattern dd-MMM-yyyy
I have a string date in format (dd-MMM-yyyy) like (23-SEP-2019). I want to seperate day month and year from above string in integer like day = 23, month = 09, year = 2019.

答:
String pattern = "dd-MMM-yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = simpelDateFormat.parse(yourdateString);
Calendar now = Calendar.getInstance();
now.setTime(date);
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
```


问:
Drupal 8 Do Something After Dialog Close
I have this link which trigger open dialog using Drupal 8

i need do something in JS when dialog close

What i should write?

```<code><div class="fullcalendar-bottom-btn add-event-btn">
<a id="calendar-add-event"  href="{{ language }}fullcalendar-view-event-add?entity={{ entity_id }}&bundle={{ options.bundle_type }}&start_field={{ options.start }}&end_field={{ options.end }}&destination={{ path('<current>') }}" class="use-ajax" data-dialog-type="dialog" data-dialog-renderer="off_canvas" data-dialog-options="{"width":400}">{{ 'Add event'|t }}</a>
</div>
</code>```

答:
I'm struggling with this right now.

In theory, data-dialog-options should accept any valid options accepted by jQuery UI Dialog , but there aren't any examples in core that use close or beforeClose.

Body:
I have this link which trigger open dialog using Drupal 8

i need do something in JS when dialog close

What i should write?

<a id="calendar-add-event"  href="{{ language }}fullcalendar-view-event-add?entity={{ entity_id }}&bundle={{ options.bundle_type }}&start_field={{ options.start }}&end_field={{ options.end }}&destination={{ path('<current>') }}" class="use-ajax" data-dialog-type="dialog" data-dialog-renderer="off_canvas" data-dialog-options="{"width":400}">{{ 'Add event'|t }}


问:
jquery scroll to div and focus a textbox
I am trying to achieve two things with a single onclick of anchor tag. First, when I click on search, I am scrolling to a particular div, and then trying to focus on the textbox within that div. Below is the link to the sample code. I am able to scroll to the div, but somehow the textbox is losing focus. What is wrong with the code?

http://jsfiddle.net/e9tJ5/1/

答: Works fine in all browsers tested except Firefox.  See here for more info: http://www.symphonious.net/2010/11/24/controlling-focus-in-firefox/</p>

ContentLicense: CC BY-SA 3.0


问:
How to parse variable length command line arguments with regex?
I have a large number of files that each contain a bash command with a variable amount of parameters. I need to replace these with a corresponding API call.

Example bash command in file (Note: number of '-p' arguments vary, some have none):

```<code>./some_script.sh http://some.server.com -p a=value -p b=value -p c=value
</code>```

Example corresponding API call

```<code>http://some.server.com/api/some/endpoint?a=value&b=value&c=value
</code>```

My issue is I can't seem to group each parameter, given that the number of parameters is variable.

Basic regex (this will match above example, but only group first parameter):

```<code>.\/some_script.sh\s([\w\/:\.]*)(\s-\w\s[\w=]*)
</code>```

And I tried:

```<code>.\/some_script.sh\s([\w\/:\.]*)(\s-\w\s[\w=]*)*
</code>```

However, this seems to only group the last parameter.
(tested with regex101)

Ideally, I would like this regex to be able to group an indefinite number of arguments in these files so that I can easily rebuild the command as an API call.

If more detail is required please let me know, any suggestions are welcome.

答:
Here, maybe we could find another approach, and step by step collect our desired data from our inputs. We would then likely start with an expression similar to:

```<code>.+\.sh.+?(https?:\/\/[^\s]*)|\s+-[a-z]+\s+([\w=]+)
</code>```

which has our link in here:

```<code>(https?:\/\/[^\s]*)
</code>```

and our variables in:

```<code>([\w=]+)
</code>```

altered with a logical OR.

We can also modify and add other boundaries or reduce our boundaries, if that might be desired.

DEMO

Test

This snippet just shows that how the capturing groups work:

const regex = /.+\.sh.+?(https?:\/\/[^\s]*)|\s+-[a-z]+\s+([\w=]+)/gm;
const str = `./some_script.sh http://some.server.com -p a=value -p b=value -p c=value
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I have a large number of files that each contain a bash command with a variable amount of parameters. I need to replace these with a corresponding API call.

Example bash command in file (Note: number of '-p' arguments vary, some have none):

./some_script.sh http://some.server.com -p a=value -p b=value -p c=value

Example corresponding API call

http://some.server.com/api/some/endpoint?a=value&b=value&c=value

My issue is I can't seem to group each parameter, given that the number of parameters is variable.

Basic regex (this will match above example, but only group first parameter):

.\/some_script.sh\s([\w\/:\.]*)(\s-\w\s[\w=]*)

And I tried:

.\/some_script.sh\s([\w\/:\.]*)(\s-\w\s[\w=]*)*

However, this seems to only group the last parameter.
(tested with regex101)

Ideally, I would like this regex to be able to group an indefinite number of arguments in these files so that I can easily rebuild the command as an API call.

If more detail is required please let me know, any suggestions are welcome.

Body:
Here, maybe we could find another approach, and step by step collect our desired data from our inputs. We would then likely start with an expression similar to:

.+\.sh.+?(https?:\/\/[^\s]*)|\s+-[a-z]+\s+([\w=]+)

which has our link in here:

(https?:\/\/[^\s]*)

and our variables in:

([\w=]+)

altered with a logical OR.

We can also modify and add other boundaries or reduce our boundaries, if that might be desired.

DEMO

Test

This snippet just shows that how the capturing groups work:

const regex = /.+\.sh.+?(https?:\/\/[^\s]*)|\s+-[a-z]+\s+([\w=]+)/gm;
const str = `./some_script.sh http://some.server.com -p a=value -p b=value -p c=value
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

RegEx Circuit

jex.im visualizes regular expressions:


问:
Declare and initialize a typed array from a range
I recently tried my Array @a = 'a'..'z'; and my Array @a = @('a'..'z');.

Both will produce the following error:

```<code>Type check failed in assignment to @a; expected Array but got Str ("a")
in block <unit> at <unknown file> line 1
</code>```

However initializing without the type works and seems to ultimately produce an Array:

```<code>> my @a = 'a'..'z';
> @a.^name
Array
</code>```

Why is this the case?

答:
When you declare an array, you can easily specify what type the elements of the array are.

my Str @a = 'a'..'z';
```

<p>You can specify the exact class that is used for the storage as well.<br>
The following line is exactly the same as the above line; since <code>Array</code> is the default storage class.</p>

<pre class="lang-perl6 prettyprint-override"><code>my @a is Array[Str] = 'a'..'z';
</code>```

You can even combine the two.

This following is also exactly the same.

my Str @a is Array = 'a'..'z';
```

<hr>

<p>When you wrote the following line.</p>

<pre class="lang-perl6 prettyprint-override"><code>my Array @a = 'a'..'z';
</code>```

What you were actually saying was:

my @a is Array[Array] = 'a'..'z';
```

<p>I assume you thought you were writing this.</p>

<pre class="lang-perl6 prettyprint-override"><code>my @a is Array = 'a'..'z';
</code>```

This can be useful if you don't want the elements to change.

my @a is List = 'a'..'z';
```

<p>Or if you have specific needs that aren't satisfied by the default <code>Array</code> class.</p>

<pre class="lang-perl6 prettyprint-override"><code>use Array::Unique; # doesn't really exist yet (afaik)

my @a is Array::Unique[Str] = 'a'..'z';

my Str @b is Array::Unique  = 'a'..'z';
</code>```

Body:
I recently tried my Array @a = 'a'..'z'; and my Array @a = @('a'..'z');.

Both will produce the following error:

Type check failed in assignment to @a; expected Array but got Str ("a")
in block <unit> at <unknown file> line 1

However initializing without the type works and seems to ultimately produce an Array:

> my @a = 'a'..'z';
> @a.^name
Array

Why is this the case?

Body:
When you declare an array, you can easily specify what type the elements of the array are.

my Str @a = 'a'..'z';

You can specify the exact class that is used for the storage as well.

The following line is exactly the same as the above line; since Array is the default storage class.

my @a is Array[Str] = 'a'..'z';

You can even combine the two.

This following is also exactly the same.

my Str @a is Array = 'a'..'z';

When you wrote the following line.

my Array @a = 'a'..'z';

What you were actually saying was:

my @a is Array[Array] = 'a'..'z';

I assume you thought you were writing this.

my @a is Array = 'a'..'z';

This can be useful if you don't want the elements to change.

my @a is List = 'a'..'z';

Or if you have specific needs that aren't satisfied by the default Array class.

use Array::Unique; # doesn't really exist yet (afaik)

my @a is Array::Unique[Str] = 'a'..'z';

my Str @b is Array::Unique  = 'a'..'z';


问:
iPad Safari popup issue
I am using window.open to open a popup in my page...

Now the issue is the popup gets displayed only if the user has changed the settings to allow popups...

What is the fix if I want to show the popup whether or not the user has blocked/allowed it ?

答: If a user has blocked popups, your website will not be able to launch them.</p>

Title: iPad Safari popup issue


问:
Lagom: is number of read side shards set per node or within the whole cluster?
Lagom allows splitting read side processor into shards to scale events processing.

```<code>object BlogEvent {
  val NumShards = 20
  val Tag       = AggregateEventTag.sharded[BlogEvent](NumShards)
}

sealed trait BlogEvent extends AggregateEvent[BlogEvent] {
  override def aggregateTag: AggregateEventShards[BlogEvent] = BlogEvent.Tag
}
</code>```

Let's say, I have 5 nodes, does it mean that the total number of shards will be 20 x 5 = 100, or will the total number of shards be 20 within the whole cluster?

答:
Let's say, I have 5 nodes, does it mean that the total number of shards will be 20 x 5 = 100, or will the total number of shards be 20 within the whole cluster?

number_of_shards = 20 * numer_of_processors

Using your example:

object BlogEvent {
  val NumShards = 20
  val Tag       = AggregateEventTag.sharded[BlogEvent](NumShards)
}
```

in your cluster, no matter how big or small, there will always be 20 instances of each read side processor consuming the stream of BlogEvents. This means that if you created a BlogRSSReadSideProcessor and a BlogAtomReadSideProcessor and a BlogTopicProducer  you would have a total of 60 shards each consuming a particular tag of the stream for its own purposes (RSS, Atom or emitting to a Topic). This means your database will hold 60 connections polling the Journal table.

Body:
Lagom allows splitting read side processor into shards to scale events processing.

object BlogEvent {
  val NumShards = 20
  val Tag       = AggregateEventTag.sharded[BlogEvent](NumShards)
}

sealed trait BlogEvent extends AggregateEvent[BlogEvent] {
  override def aggregateTag: AggregateEventShards[BlogEvent] = BlogEvent.Tag
}

Let's say, I have 5 nodes, does it mean that the total number of shards will be 20 x 5 = 100, or will the total number of shards be 20 within the whole cluster?

Body:
Let's say, I have 5 nodes, does it mean that the total number of shards will be 20 x 5 = 100, or will the total number of shards be 20 within the whole cluster?

number_of_shards = 20 * numer_of_processors

Using your example:

object BlogEvent {
  val NumShards = 20
  val Tag       = AggregateEventTag.sharded[BlogEvent](NumShards)
}

in your cluster, no matter how big or small, there will always be 20 instances of each read side processor consuming the stream of BlogEvents. This means that if you created a BlogRSSReadSideProcessor and a BlogAtomReadSideProcessor and a BlogTopicProducer  you would have a total of 60 shards each consuming a particular tag of the stream for its own purposes (RSS, Atom or emitting to a Topic). This means your database will hold 60 connections polling the Journal table.


问:
Merging a list of maps (of list of string)
Baby Kotlin dev here :)

Considering the following structure:

```<code>[
  { "color": ["red", "blue"] },
  { "color": ["red", "green"] },
  { "shape": ["square", "circle"] },
  { "shape": ["rectangle"] }
]
</code>```

I'd like to obtain the following results where keys and their respective values are merged:

```<code>[
  { "color": ["red", "blue", "green"] },
  { "shape": ["square", "circle", "rectangle"] }
]
</code>```

After some research I was thinking of something like this (doesn't work/compile), but I'm missing some pieces:

```<code>val colors1 = mapOf("color" to listOf("red", "blue"))
val colors2 = mapOf("color" to listOf("red", "green"))
val shapes1 = mapOf("color" to listOf("square", "circle"))
val shapes2 = mapOf("color" to listOf("rectangle"))
var mainList = mutableListOf(colors1, colors2, shapes1, shapes2)

mainList.reduce { acc, it -> (acc.asSequence() + it.asSequence())
    .distinct()
    .groupBy({it.key}, {it.value})
    .mapValues { (_, values) -> values.flatten().distinct() }
</code>```

Any help would be greatly appreciated.

答:
Instead of merging the maps with reduce, you can use flatMap with the map entries. So it should work this way:

```<code>mainList
    .flatMap { it.entries }
    .groupBy({ it.key }, { it.value })
    .mapValues { (_, values) -> values.flatten().toSet() }
</code>```

(runnable sample)

Also, a little bit more efficient way to flatten the values in the last line is:

```<code>    .mapValues { (_, values) -> values.flatMapTo(mutableSetOf()) { it } }
</code>```

This removes the overhead of the intermediate collection that was created to store the values between flatten() and distinct()/toSet(), but still ensures that the items are unique because they are added to a mutableSet().

Sample with reassigning the mainList: (link)

Body:
Baby Kotlin dev here :)

Considering the following structure:

[
  { "color": ["red", "blue"] },
  { "color": ["red", "green"] },
  { "shape": ["square", "circle"] },
  { "shape": ["rectangle"] }
]

I'd like to obtain the following results where keys and their respective values are merged:

[
  { "color": ["red", "blue", "green"] },
  { "shape": ["square", "circle", "rectangle"] }
]

After some research I was thinking of something like this (doesn't work/compile), but I'm missing some pieces:

val colors1 = mapOf("color" to listOf("red", "blue"))
val colors2 = mapOf("color" to listOf("red", "green"))
val shapes1 = mapOf("color" to listOf("square", "circle"))
val shapes2 = mapOf("color" to listOf("rectangle"))
var mainList = mutableListOf(colors1, colors2, shapes1, shapes2)

mainList.reduce { acc, it -> (acc.asSequence() + it.asSequence())
    .distinct()
    .groupBy({it.key}, {it.value})
    .mapValues { (_, values) -> values.flatten().distinct() }

Any help would be greatly appreciated.

Body:
Instead of merging the maps with reduce, you can use flatMap with the map entries. So it should work this way:

mainList
    .flatMap { it.entries }
    .groupBy({ it.key }, { it.value })
    .mapValues { (_, values) -> values.flatten().toSet() }

<a href="https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS4zLjExIiwicGxhdGZvcm0iOiJqYXZhIiwiYXJncyI6IlNhbXBsZUlucHV0MSBTYW1wbGVJbnB1dDIiLCJqc0NvZGUiOiIiLCJub25lTWFya2VycyI6dHJ1ZSwidGhlbWUiOiJpZGVhIiwiZm9sZGVkQnV0dG9uIjp0cnVlLCJyZWFkT25seSI6ZmFsc2UsImNvZGUiOiJ2YWwgY29sb3JzMSA9IG1hcE9mKFwiY29sb3JcIiB0byBsaXN0T2YoXCJyZWRcIiwgXCJibHVlXCIpKVxudmFsIGNvbG9yczIgPSBtYXBPZihcImNvbG9yXCIgdG8gbGlzdE9mKFwicmVkXCIsIFwiZ3JlZW5cIikpXG52YWwgc2hhcGVzMSA9IG1hcE9mKFwic2hhcGVcIiB0byBsaXN0T2YoXCJzcXVhcmVcIiwgXCJjaXJjbGVcIikpXG52YWwgc2hhcGVzMiA9IG1hcE9mKFwic2hhcGVcIiB0byBsaXN0T2YoXCJyZWN0YW5nbGVcIikpXG52YXIgbWFpbkxpc3QgPSBsaXN0T2YoY29sb3JzMSwgY29sb3JzMiwgc2hhcGVzMSwgc2hhcGVzMilcblxuZnVuIG1haW4oKSB7XG4gICAgdmFsIHJlc3VsdCA9IG1haW5MaXN0XG4gICAgICAgIC5mbGF0TWFwIHsgaXQuZW50cmllcyB9XG4gICAgICAgIC5ncm91cEJ5KHsgaXQua2V5IH0sIHsgaXQudmFsdWV9KVxuICAgICAgICAubWFwVmFsdWVzIHsgKF8sIHZhbHVlcykgLT4gdmFsdWVzLmZsYXR0ZW4oKS50b1NldCgpIH1cblxuICAgIHByaW50bG4ocmVzdWx0KVxufSIsInRvIjoiIiwiZnJvbSI6IiJ9" rel="nofollow noreferrer">(runnable sample)

Also, a little bit more efficient way to flatten the values in the last line is:

    .mapValues { (_, values) -> values.flatMapTo(mutableSetOf()) { it } }

This removes the overhead of the intermediate collection that was created to store the values between flatten() and distinct()/toSet(), but still ensures that the items are unique because they are added to a mutableSet().

Sample with reassigning the mainList: <a href="https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS4zLjExIiwicGxhdGZvcm0iOiJqYXZhIiwiYXJncyI6IlNhbXBsZUlucHV0MSBTYW1wbGVJbnB1dDIiLCJqc0NvZGUiOiIiLCJub25lTWFya2VycyI6dHJ1ZSwidGhlbWUiOiJpZGVhIiwiZm9sZGVkQnV0dG9uIjp0cnVlLCJyZWFkT25seSI6ZmFsc2UsImNvZGUiOiJ2YWwgY29sb3JzMSA9IG1hcE9mKFwiY29sb3JcIiB0byBsaXN0T2YoXCJyZWRcIiwgXCJibHVlXCIpKVxudmFsIGNvbG9yczIgPSBtYXBPZihcImNvbG9yXCIgdG8gbGlzdE9mKFwicmVkXCIsIFwiZ3JlZW5cIikpXG52YWwgc2hhcGVzMSA9IG1hcE9mKFwic2hhcGVcIiB0byBsaXN0T2YoXCJzcXVhcmVcIiwgXCJjaXJjbGVcIikpXG52YWwgc2hhcGVzMiA9IG1hcE9mKFwic2hhcGVcIiB0byBsaXN0T2YoXCJyZWN0YW5nbGVcIikpXG52YXIgbWFpbkxpc3QgPSBsaXN0T2YoY29sb3JzMSwgY29sb3JzMiwgc2hhcGVzMSwgc2hhcGVzMilcblxuZnVuIG1haW4oKSB7XG4gICAgbWFpbkxpc3QgPSBtdXRhYmxlTGlzdE9mKFxuICAgICAgICBtYWluTGlzdFxuICAgICAgICAuZmxhdE1hcCB7IGl0LmVudHJpZXMgfVxuICAgICAgICAuZ3JvdXBCeSh7IGl0LmtleSB9LCB7IGl0LnZhbHVlIH0pXG4gICAgICAgIC5tYXBWYWx1ZXMgeyAoXywgdmFsdWVzKSAtPiB2YWx1ZXMuZmxhdHRlbigpLmRpc3RpbmN0KCkgfVxuICAgIClcbiAgICAgICAgXG4gICAgcHJpbnRsbihtYWluTGlzdClcbn0iLCJ0byI6IiIsImZyb20iOiIifQ==" rel="nofollow noreferrer">(link)


问:
Prevent pointerdown event from triggering on mobile when user tapholds and scrolls
Hello I have implemented a long press javascript event handler which is working perfectly fine. However, on mobile, users tap...hold... in order to scroll up or down. This scrolling interaction on mobile is unintentionally triggering my 'pointerdown' event. I've tried inserting a pointermove event in the chain of event handlers but that seems to trigger an arbitrary amount of times, depending on how long the user is moving their pointer while pointerdown, therefore I am unable to set a boolean that is reliable and doesn't flip back and forth.

```<code>let pressTimer;
this.myElements.on('pointerup', (e) => {
  clearTimeout(pressTimer);
}).on('pointerdown', (e) => {
  let myEl = $(e.currentTarget);
  let checkbox= myEl.find('.checkbox');
  pressTimer = window.setTimeout(() => {
    checkbox.click();
  }, 750)
});
</code>```

答:
You could add a global boolean variable which holds the current status of the pointer (maybe isPointerDown) and act accordingly. e.g. if it's true don't react to pointerdown and if there's a pointerup event reset this variable to false.

```<code>let pressTimer;
var isPointerDown = false;
this.myElements.on('pointerup', (e) => {
  clearTimeout(pressTimer);
  isPointerDown = false;
}).on('pointerdown', (e) => {
  if (!isPointerDown) {
    let myEl = $(e.currentTarget);
    let checkbox = myEl.find('.checkbox');
    pressTimer = window.setTimeout(() => {
      isPointerDown = true;
      checkbox.click();
    }, 750)
  }
});
</code>```

Body:
Hello I have implemented a long press javascript event handler which is working perfectly fine. However, on mobile, users tap...hold... in order to scroll up or down. This scrolling interaction on mobile is unintentionally triggering my 'pointerdown' event. I've tried inserting a pointermove event in the chain of event handlers but that seems to trigger an arbitrary amount of times, depending on how long the user is moving their pointer while pointerdown, therefore I am unable to set a boolean that is reliable and doesn't flip back and forth.

let pressTimer;
this.myElements.on('pointerup', (e) => {
  clearTimeout(pressTimer);
}).on('pointerdown', (e) => {
  let myEl = $(e.currentTarget);
  let checkbox= myEl.find('.checkbox');
  pressTimer = window.setTimeout(() => {
    checkbox.click();
  }, 750)
});

Body:
You could add a global boolean variable which holds the current status of the pointer (maybe isPointerDown) and act accordingly. e.g. if it's true don't react to pointerdown and if there's a pointerup event reset this variable to false.

let pressTimer;
var isPointerDown = false;
this.myElements.on('pointerup', (e) => {
  clearTimeout(pressTimer);
  isPointerDown = false;
}).on('pointerdown', (e) => {
  if (!isPointerDown) {
    let myEl = $(e.currentTarget);
    let checkbox = myEl.find('.checkbox');
    pressTimer = window.setTimeout(() => {
      isPointerDown = true;
      checkbox.click();
    }, 750)
  }
});


问:
Why the code doesn't recognize the assigned variable?
I am trying to write a program in Python 3 that takes an int year larger than 1970 as an input and returns the increase in temperature from 1970 until that year. The formulas and constants are given. Python throws me an error:

```<code>File "4.5.py", line 28, in <module>
    int_years = int_year - 1970
NameError: name 'int_year' is not defined
</code>```

I am a beginner in Python so I have browsed possible solutions, but could not find any working ones.

```<code>def user_input():
    while True:
        int_year = int(input("Please enter a year greater than 1970 " ))
        try:
            if int_year > 1970:
                break
            else:
                print("Please enter a year greater than 1970")
        except ValueError:
            print ("It is not a valid year. Try again. ")
    return int_year

"""CO2 level of January 1970"""
c0 = 325.03

"""Current levels of CO2"""
c1 = 411.97

"""Difference in CO2 levels between 1970 and now"""
differenceCO = c1-c0

"""The average CO2 increase per year since 1970"""
per_year_changedCO = ((differenceCO)/(2019-1970))

"""Diffrence in years between 1970 and user input year"""
int_years = int_year - 1970

"""A projected CO2 level in user input year"""
int_year_changedCO = c0+((int_years)*(per_year_changedCO))

"""A projected RF in any year"""
RF = 5.35*(math.log((int_year_changedCO)/(c0)))

"""Increase in temperature from 1970 to user input year"""
def predict_increase():
  temp_int_year = 0.5 * RF
  return temp_int_year

print(temp_int_year)
</code>```

I expect the program to recognize the variables I use in functions. Overall, I will appreciate any comments on the code.

答:
You define int_year within the scope of the user_input, but that is not accessible outwith that function (more info about that here)

Rather than reference the variable directly you want to get the return value of the function (which is the value of int_year because of the line 'return int_year'):

```<code>int_years = user_input() - 1970
</code>```

Edit for comment above

```<code>def user_input():
    try:
        int_year = int(input("Please enter a year greater than 1970"))
        if int_year < 1970:
            print("Invalid year, please enter a value greater than 1970")
            int_year = user_input()
    except ValueError:
        print("Invalid input. Please enter a number")
        int_year = user_input()
    return int_year
</code>```

Body:
I am trying to write a program in Python 3 that takes an int year larger than 1970 as an input and returns the increase in temperature from 1970 until that year. The formulas and constants are given. Python throws me an error:

File "4.5.py", line 28, in <module>
    int_years = int_year - 1970
NameError: name 'int_year' is not defined

I am a beginner in Python so I have browsed possible solutions, but could not find any working ones.

def user_input():
    while True:
        int_year = int(input("Please enter a year greater than 1970 " ))
        try:
            if int_year > 1970:
                break
            else:
                print("Please enter a year greater than 1970")
        except ValueError:
            print ("It is not a valid year. Try again. ")
    return int_year

"""CO2 level of January 1970"""
c0 = 325.03

"""Current levels of CO2"""
c1 = 411.97

"""Difference in CO2 levels between 1970 and now"""
differenceCO = c1-c0

"""The average CO2 increase per year since 1970"""
per_year_changedCO = ((differenceCO)/(2019-1970))

"""Diffrence in years between 1970 and user input year"""
int_years = int_year - 1970

"""A projected CO2 level in user input year"""
int_year_changedCO = c0+((int_years)*(per_year_changedCO))

"""A projected RF in any year"""
RF = 5.35*(math.log((int_year_changedCO)/(c0)))

"""Increase in temperature from 1970 to user input year"""
def predict_increase():
  temp_int_year = 0.5 * RF
  return temp_int_year

print(temp_int_year)

I expect the program to recognize the variables I use in functions. Overall, I will appreciate any comments on the code.

Body:
You define int_year within the scope of the user_input, but that is not accessible outwith that function (more info about that here)

Rather than reference the variable directly you want to get the return value of the function (which is the value of int_year because of the line 'return int_year'):

int_years = user_input() - 1970

Edit for comment above

def user_input():
    try:
        int_year = int(input("Please enter a year greater than 1970"))
        if int_year < 1970:
            print("Invalid year, please enter a value greater than 1970")
            int_year = user_input()
    except ValueError:
        print("Invalid input. Please enter a number")
        int_year = user_input()
    return int_year


问:
Use aggregation only on rows where count(ID) is greater than one
Hi I have the following table

Cash_table

```<code>ID          Cash   Rates
1           50   3
2           100  4
3           70   10
3           60   10
4           13   7
5           20   8
5           10   10
6           10   5
</code>```

What I want as a result is to cumulate all the entries that have a Count(id)>1 like this:

```<code>ID          New_Cash            New_Rates
1           50                  3
2           100                 4
3           (70+60)/(10+10)     10+10
4           13                  7
5           (20+10)/(8+10)      8+10
6           10                  5
</code>```

So I only want to change the rows where Count(id)>1 and leave the rest like it was.

For the rows with count(id)>1 I want to sum up the rates and take the sum of the cash and divide it by the sum of the rates. The Rates alone aren't a problem since I can sum them up and group by id and get the desired result.

The problem is with the cash column:

I am trying to do it with a case statement but it isn't working:

```<code>   select id, sum(rates) as new_rates, case
   when count(id)>1 then sum(cash)/nullif(sum(rates),0))
   else cash
   end as new_cash
   from Cash_table
   group by id
</code>```

答:
You can aggregate rate and cash columns by sum() function with grouping by id

```<code>select
       id,
       sum(cash)/decode( sum( nvl(rates,0) ), 0 ,1, sum( nvl(rates,0) )) as new_cash,
       sum(rates) as new_rates
  from cash_table
 group by id
</code>```

there's no nullif() function in Oracle, use nvl() instead

switch case part ( where decode() function is used ) against the
possibility of division by zero

Body:
Hi I have the following table

Cash_table

ID          Cash   Rates
1           50   3
2           100  4
3           70   10
3           60   10
4           13   7
5           20   8
5           10   10
6           10   5

What I want as a result is to cumulate all the entries that have a Count(id)>1 like this:

ID          New_Cash            New_Rates
1           50                  3
2           100                 4
3           (70+60)/(10+10)     10+10
4           13                  7
5           (20+10)/(8+10)      8+10
6           10                  5

So I only want to change the rows where Count(id)>1 and leave the rest like it was.

For the rows with count(id)>1 I want to sum up the rates and take the sum of the cash and divide it by the sum of the rates. The Rates alone aren't a problem since I can sum them up and group by id and get the desired result.

The problem is with the cash column:

I am trying to do it with a case statement but it isn't working:

   select id, sum(rates) as new_rates, case
   when count(id)>1 then sum(cash)/nullif(sum(rates),0))
   else cash
   end as new_cash
   from Cash_table
   group by id

Body:
You can aggregate rate and cash columns by sum() function with grouping by id

select
       id,
       sum(cash)/decode( sum( nvl(rates,0) ), 0 ,1, sum( nvl(rates,0) )) as new_cash,
       sum(rates) as new_rates
  from cash_table
 group by id

there's no nullif() function in Oracle, use nvl() instead

switch case part ( where decode() function is used ) against the
possibility of division by zero


问:
"Return without GoSub" when using subforms in Access
Why do I get a

"Return without GoSub"

error when using subforms in Access 2007?

答: I had something similar (not specifically in VBA, but with using a form to update a subform). I just added a "StopAllMacros" step at the end of the screen updating object and it seemed to work.


问:
browser and web server comm
how does a web server identify that the request is from a specific client? i know the communication happens through http protocol but what is it that tells the server that, for a particular request, the response needs to be sent to this client?

(i am not sure if this is too simple a question but i just want to learn something here and may benefit others like me as well)

答: The HTTP server starts a new process (in most cases, it actually starts a new thread, but for simplicity's sake we can assume it's a process) for every client that connects, so from code the program sees only this client that caused it to start. HTTP is stateless, which means that after it's done replying to the query, the http server program ends - it looks like a function with the query as the parameter and the web page as the return value. The connection itself is identified by Source IP, Destination IP, Source Port and Destination Port (all of them). </p>

Title: browser and web server comm


问:
How to check if contents of string qualify as a string in C#
I am trying to make a C# .NET core console application that can run like a simple command line OS. (not an actual OS just a mimic). I would like to check if the contents of a string that I have as a variable would qualify as a string themselves. If need-be I can write my own parser thingy, but I would much prefer a simpler solution.

I have not tried anything, because I have no idea whatsoever of how to even go about starting.

答: If I've understood correctly, you're looking for something like this: https://github.com/natemcmaster/CommandLineUtils .. It allows you to parse the command line and call off different methods depending on the input?</p>


问:
Angular Material Dropdown with Create Option
I am using Angular material to create select Dropdown of Religion. But the options I provided might not cover all the religion of the world. But I want to give option for the user to enter his/her religion in the field if not found. So, What I want to do, give an option named 'other option' and when he clicks on the option, an input field will be given to the option which will be treated as the 'formcontrolName' value for the the field.

If you provide the code at Stackblitz, it would be great to see clearly.

答:
This question has been answered before. Here's an answer using an autocomplete: Angular Material Autocomplete - How to allow user to add item not in suggested list?. StackBlitz here.

If you want to use a standard select instead of autocomplete, it would be easier since you would only have to place a "other" option in your list and have special handling for that perhaps via a dialog. Some of the techniques in the autocomplete example might be useful with a select as well.


问:
Laravel some questions (pagination, if - foreach)
I'm laravel newbie. I'm created simple code and I have some questions:
I think this code bad (it works, but I use @forelse($forums as $forum) and anywhere use $forum)

```<code>@extends('layouts.main')
@section('content')
@forelse($forums as $forum) <-- I don't like this line, it works but i think it's possible with if or something else
@forelse($topics as $topic)
{{ $topic->title }}<br>
@empty
Sorry but this forums empty.
@endforelse
@empty
Sorry but this forum not found
@endforelse
@stop
</code>```

And second question how to make pagination? I'm tried this:

```<code><?php

namespace App\Http\Controllers;
use DB;
use View;

class viewForum extends Controller
{
    public function showForum($fname, $fid)
    {
        return View::make('forum', [
            'forums'    => DB::table('forums')
                ->where('id', $fid)
                ->where('seo_name', $fname)
                ->select()
                ->get()
                ->simplePagination(5)
        ]);
    }
}
</code>```

But not work's, I'm tried tutorials..etc, how to? Thanks so much in advance ! :)

答:
you can use @foreach() @endforeach and probably @if @else @endif
see sample:</p>

```<code>@foreach($forums as $forum)
  @if($forum==0)
    {{'empty'}}
  @else
    {{ 'Not empty' }}
  @endif

@endforeach
</code>```

Body:
I'm laravel newbie. I'm created simple code and I have some questions:
I think this code bad (it works, but I use @forelse($forums as $forum) and anywhere use $forum)

@extends('layouts.main')
@section('content')
@forelse($forums as $forum) <-- I don't like this line, it works but i think it's possible with if or something else
@forelse($topics as $topic)
{{ $topic->title }}

@empty
Sorry but this forums empty.
@endforelse
@empty
Sorry but this forum not found
@endforelse
@stop

And second question how to make pagination? I'm tried this:

<?php

namespace App\Http\Controllers;
use DB;
use View;

class viewForum extends Controller
{
    public function showForum($fname, $fid)
    {
        return View::make('forum', [
            'forums'    => DB::table('forums')
                ->where('id', $fid)
                ->where('seo_name', $fname)
                ->select()
                ->get()
                ->simplePagination(5)
        ]);
    }
}

But not work's, I'm tried tutorials..etc, how to? Thanks so much in advance ! :)

Body:
you can use @foreach() @endforeach and probably @if @else @endif
see sample:

@foreach($forums as $forum)
  @if($forum==0)
    {{'empty'}}
  @else
    {{ 'Not empty' }}
  @endif

@endforeach


问:
Making all possible combinations of a list
I need to be able to make a list that contains all possible combinations of an inputted list.
For example the list [1,2,3] should return [1 [1,2] [1,3] 2 [2,3] 3 [1,2,3]]
The list doesn't have to be in any particular order. On this site I've found lots of functions using the itertools but those are returning objects when I need just a list.

答:
I think it's worth boiling down the other answers here into a simple Python 3 example:

```<code>from itertools import chain, combinations

def all_combinations(array):
    return chain(*(list(combinations(array, i + 1)) for i in range(len(array))))
</code>```

This returns an iterable, to view the values:

```<code>>>> print(list(all_combinations((1, 2, 3))))
[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
</code>```

Body:
I think it's worth boiling down the other answers here into a simple Python 3 example:

from itertools import chain, combinations

def all_combinations(array):
    return chain(*(list(combinations(array, i + 1)) for i in range(len(array))))

This returns an iterable, to view the values:

>>> print(list(all_combinations((1, 2, 3))))
[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]


问:
How to continue sequence / parallel actions from cachedActions Libgdx
I have a clicklistener extended class which aims to cached any current actions of the actor during touchDown, and assigns it back when touchUp is triggered. However, it does not works for sequence or parallel actions.

```<code>public class MyClickListener extends ClickListener {

    public Actor actor;
    private final Array<Action> cachedActions = new Array<Action>();

    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        super.touchUp(event, x, y, pointer, button);
        actor = event.getListenerActor();
        actor.addAction(btnScaleBackActions());
        for(Action action:cachedActions)
        {
            //action.reset(); // i wants the actor to continue at where it stop
            action.setTarget(actor);
            action.setActor(actor);
            actor.addAction(action);
        }
        cachedActions.clear();
    }

    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        if(pointer==0)
        {
            actor = event.getListenerActor();
            actor.setScale(0.9f);
            cachedActions.addAll(actor.getActions());
            actor.clearActions();
            return super.touchDown(event, x, y, pointer, button);
        }
        else
        {
            return false;
        }
    }
</code>```

My buttons testing:

```<code>// button touchUp continue its previous action at where it stop
btn1.addAction(Actions.scaleBy(1,1,3));

// button touchUp not continue it previous actions and complete stop
btn2.addAction(sequence(Actions.scaleBy(1,1,3)));

// button touchUp give nullException error
btn3.addAction(forever(Actions.scaleBy(1,1,3)));

//error :
Exception in thread "LWJGL Application" java.lang.NullPointerException
        at com.badlogic.gdx.scenes.scene2d.actions.RepeatAction.delegate(RepeatAction.java:29)
        at com.badlogic.gdx.scenes.scene2d.actions.DelegateAction.act(DelegateAction.java:43)
</code>```

Is it possible to continue sequence/parallel actions at where it stop at myClickListener class?

答:
The default behavior of actions that came from a pool (like from the Actions class) is to restart themselves when they are removed from an actor. It's actually not safe for you to be reusing these instances because they have also been returned to the pool and might get attached to some other actor unexpectedly.

So before you remove them from your actor, you need to set their pools to null.

```<code>private static void clearPools (Array<Action> actions){
    for (Action action : actions){
        action.setPool(null);
        if (action instanceof ParallelAction) //SequenceActions are also ParallelActions
            clearPools(((ParallelAction)action).getActions());
        else if (action instanceof DelegateAction)
            ((DelegateAction)action).getAction().setPool(null);
    }
}

//And right before actor.clearActions();
clearPools(actor.getActions());
</code>```

Then, when you add them back to the actor, you'll want to add their pools back so they can go back to the Actions pools and be reused later to avoid GC churn.

```<code>private static void assignPools (Array<Action> actions){
    for (Action action : actions){
        action.setPool(Pools.get(action.getClass()));
        if (action instanceof ParallelAction)
            assignPools(((ParallelAction)action).getActions());
        else if (action instanceof DelegateAction){
            Action innerAction = ((DelegateAction)action).getAction();
            innerAction.setPool(Pools.get(innerAction.getClass()));
        }
    }
}

//And call it on your actor right after adding the actions back:
assignPools(actor.getActions);
</code>```

Body:
I have a clicklistener extended class which aims to cached any current actions of the actor during touchDown, and assigns it back when touchUp is triggered. However, it does not works for sequence or parallel actions.

public class MyClickListener extends ClickListener {

    public Actor actor;
    private final Array<Action> cachedActions = new Array<Action>();

    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        super.touchUp(event, x, y, pointer, button);
        actor = event.getListenerActor();
        actor.addAction(btnScaleBackActions());
        for(Action action:cachedActions)
        {
            //action.reset(); // i wants the actor to continue at where it stop
            action.setTarget(actor);
            action.setActor(actor);
            actor.addAction(action);
        }
        cachedActions.clear();
    }

    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        if(pointer==0)
        {
            actor = event.getListenerActor();
            actor.setScale(0.9f);
            cachedActions.addAll(actor.getActions());
            actor.clearActions();
            return super.touchDown(event, x, y, pointer, button);
        }
        else
        {
            return false;
        }
    }

My buttons testing:

// button touchUp continue its previous action at where it stop
btn1.addAction(Actions.scaleBy(1,1,3));

// button touchUp not continue it previous actions and complete stop
btn2.addAction(sequence(Actions.scaleBy(1,1,3)));

// button touchUp give nullException error
btn3.addAction(forever(Actions.scaleBy(1,1,3)));

//error :
Exception in thread "LWJGL Application" java.lang.NullPointerException
        at com.badlogic.gdx.scenes.scene2d.actions.RepeatAction.delegate(RepeatAction.java:29)
        at com.badlogic.gdx.scenes.scene2d.actions.DelegateAction.act(DelegateAction.java:43)

Is it possible to continue sequence/parallel actions at where it stop at myClickListener class?

Body:
The default behavior of actions that came from a pool (like from the Actions class) is to restart themselves when they are removed from an actor. It's actually not safe for you to be reusing these instances because they have also been returned to the pool and might get attached to some other actor unexpectedly.

So before you remove them from your actor, you need to set their pools to null.

private static void clearPools (Array<Action> actions){
    for (Action action : actions){
        action.setPool(null);
        if (action instanceof ParallelAction) //SequenceActions are also ParallelActions
            clearPools(((ParallelAction)action).getActions());
        else if (action instanceof DelegateAction)
            ((DelegateAction)action).getAction().setPool(null);
    }
}

//And right before actor.clearActions();
clearPools(actor.getActions());

Then, when you add them back to the actor, you'll want to add their pools back so they can go back to the Actions pools and be reused later to avoid GC churn.

private static void assignPools (Array<Action> actions){
    for (Action action : actions){
        action.setPool(Pools.get(action.getClass()));
        if (action instanceof ParallelAction)
            assignPools(((ParallelAction)action).getActions());
        else if (action instanceof DelegateAction){
            Action innerAction = ((DelegateAction)action).getAction();
            innerAction.setPool(Pools.get(innerAction.getClass()));
        }
    }
}

//And call it on your actor right after adding the actions back:
assignPools(actor.getActions);


问:
PHP __get and __set magic methods
Unless I'm completely mistaken, the __get and __set methods are supposed to allow overloading of the → get and set.

For example, the following statements should invoke the __get method:

```<code>echo $foo->bar;
$var = $foo->bar;
</code>```

And the following should use the __set method:

```<code>$foo->bar = 'test';
</code>```

This was not working in my code, and is reproducible with this simple example:

```<code>class foo {

    public $bar;
    public function __get($name) {

        echo "Get:$name";
        return $this->$name;
    }

    public function __set($name, $value) {

        echo "Set:$name to $value";
        $this->$name = $value;
    }
}

$foo = new foo();

echo $foo->bar;
$foo->bar = 'test';

echo "[$foo->bar]";
</code>```

This only results in:

```<code>[test]
</code>```

Putting some die() calls in there shows that it is not hitting it at all.

For now, I just said screw it, and am manually using __get where it's needed for now, but that's not very dynamic and requires knowledge that the 'overloaded' code is in fact not being called unless specifically called. I'd like to know if this is either not supposed to function the way I've understood that it should or why this is not working.

This is running on php 5.3.3.

答:
Intenta con: </p>

```<code>__GET($k){
 return $this->$k;
}

_SET($k,$v){
 return $this->$k = $v;
}
</code>```

Title: PHP __get and __set magic methods

Body:
Unless I'm completely mistaken, the __get and __set methods are supposed to allow overloading of the → get and set.

For example, the following statements should invoke the __get method:

echo $foo->bar;
$var = $foo->bar;

And the following should use the __set method:

$foo->bar = 'test';

This was not working in my code, and is reproducible with this simple example:

class foo {

    public $bar;
    public function __get($name) {

        echo "Get:$name";
        return $this->$name;
    }

    public function __set($name, $value) {

        echo "Set:$name to $value";
        $this->$name = $value;
    }
}

$foo = new foo();

echo $foo->bar;
$foo->bar = 'test';

echo "[$foo->bar]";

This only results in:

[test]

Putting some die() calls in there shows that it is not hitting it at all.

For now, I just said screw it, and am manually using __get where it's needed for now, but that's not very dynamic and requires knowledge that the 'overloaded' code is in fact not being called unless specifically called. I'd like to know if this is either not supposed to function the way I've understood that it should or why this is not working.

This is running on php 5.3.3.

Body:
Intenta con:

__GET($k){
 return $this->$k;
}

_SET($k,$v){
 return $this->$k = $v;
}


问:
Algolia: restore scroll down position
I scroll down algolia search page. After I click on some prodct and go to the product page. After I click Back button on browser and i see again algolia search page. I am excepting to see scroll down position(as it was before), but have Top.

I use Magento2 + Algolia(1.9.0)

Does anyone know what may be solution?

答:
Currently, your best option is to save the scroll position:

```<code>$(window).scroll(function () {
//set scroll position in session storage
sessionStorage.scrollPos = $(window).scrollTop();
});
var init = function () {
//return scroll position in session storage
$(window).scrollTop(sessionStorage.scrollPos || 0);
$(’.ap-dropdown-menu’).remove();

};
window.onload = init;
</code>```

As described:

https://discourse.algolia.com/t/instant-search-positioning-on-returning-to-page/4656

https://discourse.algolia.com/t/instantsearch-vanilla-js-save-scroll-position-on-back-button/7401

Title: Algolia: restore scroll down position

Body:
Currently, your best option is to save the scroll position:

$(window).scroll(function () {
//set scroll position in session storage
sessionStorage.scrollPos = $(window).scrollTop();
});
var init = function () {
//return scroll position in session storage
$(window).scrollTop(sessionStorage.scrollPos || 0);
$(’.ap-dropdown-menu’).remove();

};
window.onload = init;

As described:

https://discourse.algolia.com/t/instant-search-positioning-on-returning-to-page/4656

https://discourse.algolia.com/t/instantsearch-vanilla-js-save-scroll-position-on-back-button/7401


问:
Determining/accessing the type of a generic parameter?
I need to refactor a function that hydrates values from localStorage:

```<code>export function hydrateFromLocalStorage<T>(key: string): T {
  try {
    return JSON.parse(localStorage.getItem(key))
  }
  catch (error) {
    return null;
  }
}
</code>```

If the type T is anything other than an object, it doesn't need to be passed through the JSON parser.

I have seen many examples of using ReturnType, but not within the function body. Is it possible to determine T within the function?

答:
I was overthinking the problem, as usual.

If you simply use JSON.stringify() to set the value before attempting to re-hydrate the value, it's not necessary to know the return type of the generic parameter.

Body:
I need to refactor a function that hydrates values from localStorage:

export function hydrateFromLocalStorage<T>(key: string): T {
  try {
    return JSON.parse(localStorage.getItem(key))
  }
  catch (error) {
    return null;
  }
}

If the type T is anything other than an object, it doesn't need to be passed through the JSON parser.

I have seen many examples of using ReturnType, but not within the function body. Is it possible to determine T within the function?


问:
Convert ZonedDateTime to LocalDateTime at time zone
I have an object of ZonedDateTime that is constructed like this

```<code>ZonedDateTime z = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);
</code>```

How can I convert it to LocalDateTime at time zone of Switzerland? Expected result should be 16 april 2018 13:30.

答:
Another option that seems a little more intuitive is to convert the zoned date to an instant, then use LocalDateTime.ofInstant:

```<code>ZonedDateTime zdt = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);
ZoneId zId = ZoneId.of("US/Central");
LocalDateTime l = LocalDateTime.ofInstant(zdt.toInstant(), zId);
</code>```

I prefer this to withZoneSameInstant because that solution little more opaque - you're getting a ZonedDateTime that has to be in a particular internal state (the correct time zone). Using ofInstant can be used on any ZonedDateTime in any time zone.

Body:
I have an object of ZonedDateTime that is constructed like this

ZonedDateTime z = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);

How can I convert it to LocalDateTime at time zone of Switzerland? Expected result should be 16 april 2018 13:30.

Body:
Another option that seems a little more intuitive is to convert the zoned date to an instant, then use LocalDateTime.ofInstant:

ZonedDateTime zdt = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC);
ZoneId zId = ZoneId.of("US/Central");
LocalDateTime l = LocalDateTime.ofInstant(zdt.toInstant(), zId);

I prefer this to withZoneSameInstant because that solution little more opaque - you're getting a ZonedDateTime that has to be in a particular internal state (the correct time zone). Using ofInstant can be used on any ZonedDateTime in any time zone.


问:
React Native - Unable to resolve module `@babel/runtime/helpers/interopRequireDefault`
I upgraded my react native application from 0.48.3 to 0.59.8 everything works fine until lauching the emulator . Then this error appears :

```<code>   error: bundling failed: Error: Unable to resolve module
   `@babel/runtime/helpers/interopRequireDefault` from
    `E:\als\variant\generic\index.android.js`: Module
    `@babel/runtime/helpers/interopRequireDefault` does not exist in the
    Haste module map
</code>```

Here is my Package.json :

```<code>  "dependencies": {
  "@babel/polyfill": "^7.4.4",
  "@babel/runtime": "^7.0.0-beta.55",
   "babel-loader": "^8.0.5",
   "content-disposition": "^0.5.2",
   "core-js": "^3.0.1",
   "react": "16.8.6",
   "react-dom": "16.8.6",
   "react-loader": "^2.4.5",
   "react-native": "0.59.8",
   "react-redux": "^5.0.6",
    "react-router-dom": "^5.0.0",
    "redux": "^3.7.2",
   "redux-thunk": "^2.2.0",

},
 "devDependencies": {
   "@babel/plugin-proposal-class-properties": "^7.4.4",
  "@babel/plugin-proposal-decorators": "^7.4.4",
  "@babel/plugin-proposal-nullish-coalescing-operator": "^7.4.4",
  "@babel/plugin-transform-block-scoping": "^7.0.0",
  "@babel/plugin-transform-flow-strip-types": "^7.4.4",
   "@babel/plugin-transform-react-jsx-source": "^7.2.0",
   "@babel/plugin-transform-runtime": "^7.4.4",
   "@babel/preset-env": "^7.4.3",
    "@babel/preset-flow": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
      "babel-eslint": "^10.0.1",
     "babel-jest": "^24.8.0",
    "babel-preset-react-native": "^5.0.2",
 }
</code>```

I have tried all solutions found in similar questions but not working .Have you any idea please ?

答:
Try to reset cache with</p>

```<code>npm run start --reset-cache
</code>```

Body:
I upgraded my react native application from 0.48.3 to 0.59.8 everything works fine until lauching the emulator . Then this error appears :

   error: bundling failed: Error: Unable to resolve module
   `@babel/runtime/helpers/interopRequireDefault` from
    `E:\als\variant\generic\index.android.js`: Module
    `@babel/runtime/helpers/interopRequireDefault` does not exist in the
    Haste module map

Here is my Package.json :

  "dependencies": {
  "@babel/polyfill": "^7.4.4",
  "@babel/runtime": "^7.0.0-beta.55",
   "babel-loader": "^8.0.5",
   "content-disposition": "^0.5.2",
   "core-js": "^3.0.1",
   "react": "16.8.6",
   "react-dom": "16.8.6",
   "react-loader": "^2.4.5",
   "react-native": "0.59.8",
   "react-redux": "^5.0.6",
    "react-router-dom": "^5.0.0",
    "redux": "^3.7.2",
   "redux-thunk": "^2.2.0",

},
 "devDependencies": {
   "@babel/plugin-proposal-class-properties": "^7.4.4",
  "@babel/plugin-proposal-decorators": "^7.4.4",
  "@babel/plugin-proposal-nullish-coalescing-operator": "^7.4.4",
  "@babel/plugin-transform-block-scoping": "^7.0.0",
  "@babel/plugin-transform-flow-strip-types": "^7.4.4",
   "@babel/plugin-transform-react-jsx-source": "^7.2.0",
   "@babel/plugin-transform-runtime": "^7.4.4",
   "@babel/preset-env": "^7.4.3",
    "@babel/preset-flow": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
      "babel-eslint": "^10.0.1",
     "babel-jest": "^24.8.0",
    "babel-preset-react-native": "^5.0.2",
 }

I have tried all solutions found in similar questions but not working .Have you any idea please ?

Body:
Try to reset cache with

npm run start --reset-cache


问:
Is there any method like __init_subclass__() before python 3.6
When I read Python Cookbook 3rd Edition recipe 9.18, I ran into a class definition with parent Class and some optional argument, and I looked it up. I know that Python 3.6 added a new feature __init_subclass__() method for parent class, but the book is written based on Python 3.3, so what method will take these arguments other than a metaclass?

The class definition is here:

```<code>class Spam(Base, debug=True, typecheck=False):
    ...
</code>```

I know that metaclass can accept other optional arguments in its' __prepare__, __new__, __init__ method, but Base is a parent class, where do these arguments go?

答:
They go to the metaclass's __prepare__ method, just like always. Just because Base hasn't specified a metaclass doesn't mean it doesn't have one. The default metaclass is type.

The addition of __init_subclass__ to type in Python 3.6 just saves you the effort of defining a custom metaclass in order to implement an equivalent to __init_subclass__ yourself.

Body:
When I read Python Cookbook 3rd Edition recipe 9.18, I ran into a class definition with parent Class and some optional argument, and I looked it up. I know that Python 3.6 added a new feature __init_subclass__() method for parent class, but the book is written based on Python 3.3, so what method will take these arguments other than a metaclass?

The class definition is here:

class Spam(Base, debug=True, typecheck=False):
    ...

I know that metaclass can accept other optional arguments in its' __prepare__, __new__, __init__ method, but Base is a parent class, where do these arguments go?


问:
How to fetch all from table1 and attach count of rows from table2 in a single query by laravel eloquent
I'm using Laravel 5.8, and I have 2 tables in a (one-to-many) relationship as below:

Contacts DB

id

name

number

Send DB

id

user_id

text

to

time

what I want to achieve is a list of all (Contacts) along with how many (send) they've made that related to that (contact) by matching Contacts.id with Send.user_id,

here is the result of the query that I'm looking for:

Query result:

id

name

number

count of Sends

Thank you :)

答:
Worked like charm!
I did tweak it to make it return a signal (contact)

```<code>Contact::where('id', $id)->withCount('sends')->get();
</code>```

here is another way as (Jonathan K) suggested

```<code>Contact::where('id', $id)->withCount('sends')->first();
</code>```

Thanks, Jonathan K

Body:
Worked like charm!
I did tweak it to make it return a signal (contact)

Contact::where('id', $id)->withCount('sends')->get();

here is another way as (Jonathan K) suggested

Contact::where('id', $id)->withCount('sends')->first();

Thanks, Jonathan K


问:
How to deep-link to SoundCloud iOS App search without losing query?
When I try to deep link to the Soundcloud iOS app using the following URL scheme:

"https://soundcloud.com/search?q=\(query)"

the app opens to the search screen, but the query parameters are lost. If you uninstall the Soundcloud iOS app, the search works properly on the web. Is there any way to deep link to search in the SoundCloud iOS app while keeping the query?

答:
SoundCloud is using Universal Links.  If you look at their apple-app-site-association file, you will see that they do not support deep linking from the /search web endpoint:

```<code>{
  "webcredentials" : {
    "apps" : [
      "33KQ7TW725.com.soundcloud.TouchApp",
      "PBQEYM9L4Z.com.soundcloud.RAC.EnterpriseAlpha",
      "PBQEYM9L4Z.com.soundcloud.rac",
      "3XW8MM2T22.com.soundcloud.pulse.production",
      "3XW8MM2T22.com.soundcloud.pulse.debug",
      "PBQEYM9L4Z.com.soundcloud.pulse.alpha"
    ]
  },
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "3XW8MM2T22.com.soundcloud.pulse.production",
        "paths": [
          "/notifications",
          "/you/stats",
          "/you/stats/*",
          "/you/tracks"
        ]
      },
      {
        "appID": "33KQ7TW725.com.soundcloud.TouchApp",
        "paths": [
          "NOT /-",
          "NOT /-/*",
          "NOT /connect",
          "NOT /connect/*",
          "NOT /imprint",
          "NOT /jobs",
          "NOT /jobs/*",
          "NOT /login",
          "NOT /login/*",
          "NOT /mobile",
          "NOT /pages/*",
          "NOT /pro",
          "NOT /pro/*",
          "NOT /settings",
          "NOT /signin",
          "NOT /signin/*",
          "NOT /student",
          "NOT /student/*",
          "NOT /terms-of-use",
          "/you/collection",
          "/you/library",
          "/you/likes",
          "/you",
          "NOT /you/*",
          "/",
          "*"
        ]
      }
    ]
  }
}
</code>```

This could of course change at any time, but based on SoundCloud mobile development history, unlikely to.

Body:
SoundCloud is using Universal Links.  If you look at their apple-app-site-association file, you will see that they do not support deep linking from the /search web endpoint:

{
  "webcredentials" : {
    "apps" : [
      "33KQ7TW725.com.soundcloud.TouchApp",
      "PBQEYM9L4Z.com.soundcloud.RAC.EnterpriseAlpha",
      "PBQEYM9L4Z.com.soundcloud.rac",
      "3XW8MM2T22.com.soundcloud.pulse.production",
      "3XW8MM2T22.com.soundcloud.pulse.debug",
      "PBQEYM9L4Z.com.soundcloud.pulse.alpha"
    ]
  },
  "applinks": {
    "apps": [],
    "details": [
      {
        "appID": "3XW8MM2T22.com.soundcloud.pulse.production",
        "paths": [
          "/notifications",
          "/you/stats",
          "/you/stats/*",
          "/you/tracks"
        ]
      },
      {
        "appID": "33KQ7TW725.com.soundcloud.TouchApp",
        "paths": [
          "NOT /-",
          "NOT /-/*",
          "NOT /connect",
          "NOT /connect/*",
          "NOT /imprint",
          "NOT /jobs",
          "NOT /jobs/*",
          "NOT /login",
          "NOT /login/*",
          "NOT /mobile",
          "NOT /pages/*",
          "NOT /pro",
          "NOT /pro/*",
          "NOT /settings",
          "NOT /signin",
          "NOT /signin/*",
          "NOT /student",
          "NOT /student/*",
          "NOT /terms-of-use",
          "/you/collection",
          "/you/library",
          "/you/likes",
          "/you",
          "NOT /you/*",
          "/",
          "*"
        ]
      }
    ]
  }
}

This could of course change at any time, but based on SoundCloud mobile development history, unlikely to.


问:
How to proper use YouTube iOS Player Helper?
I am trying to load videos/playlists from YouTube (personal account) using Swift. I added the YTPlayerView class and iframe HTML file to do so but the videos are not loading.

 I added a UIView in the storyboard and changed its class to YTPlayerView and created an IBOutlet.

Here's the code:

```<code>import UIKit
import youtube_ios_player_helper

class YTViewController: UIViewController, YTPlayerViewDelegate {

    @IBOutlet var videoPlayer: YTPlayerView!

    override func viewDidLoad() {

        let videoID = "https://www.youtube.com/watch?v=M7lc1UVf-VE"
    videoPlayer.loadVideoByURL(videoID, startSeconds: 0.0, suggestedQuality: .Small)
        videoPlayer.playVideo()

    }

}
</code>```

As far as I read in the documentation this is what it takes to show a video. But when I run the app the UIView does nothing. How can I get this working?

答:
Make sure that YTPlayerView-iframe-player.html is added to your project as well as added to your bundle under "Copy Bundle Resources." also YTPlayerView.m this file also added to your project.

If still don't work than replace the following code

```<code>NSString *path = [[NSBundle mainBundle] pathForResource:@"YTPlayerView-iframe-player" ofType:@"html" inDirectory:@"Assets"];
</code>```

with this

```<code>NSString *path = [[NSBundle mainBundle] pathForResource:@"YTPlayerView-iframe-player" ofType:@"html"];
</code>```

Body:
I am trying to load videos/playlists from YouTube (personal account) using Swift. I added the YTPlayerView class and iframe HTML file to do so but the videos are not loading.

 I added a UIView in the storyboard and changed its class to YTPlayerView and created an IBOutlet.

Here's the code:

import UIKit
import youtube_ios_player_helper

class YTViewController: UIViewController, YTPlayerViewDelegate {

    @IBOutlet var videoPlayer: YTPlayerView!

    override func viewDidLoad() {

        let videoID = "https://www.youtube.com/watch?v=M7lc1UVf-VE"
    videoPlayer.loadVideoByURL(videoID, startSeconds: 0.0, suggestedQuality: .Small)
        videoPlayer.playVideo()

    }

}

As far as I read in the documentation this is what it takes to show a video. But when I run the app the UIView does nothing. How can I get this working?

Body:
Make sure that YTPlayerView-iframe-player.html is added to your project as well as added to your bundle under "Copy Bundle Resources." also YTPlayerView.m this file also added to your project.

If still don't work than replace the following code

NSString *path = [[NSBundle mainBundle] pathForResource:@"YTPlayerView-iframe-player" ofType:@"html" inDirectory:@"Assets"];

with this

NSString *path = [[NSBundle mainBundle] pathForResource:@"YTPlayerView-iframe-player" ofType:@"html"];


问:
Is it possible to you use something from database in a class tag in JSP?
Im trying to get something out of my database to add to a class in my JSP.</p>

```<code><div class="selection <c:out value='${bill.category}'/>">

<c:forEach items="${bills}" var="bill">
        <div class="selection <c:out value='${bill.category}'/>">
            <p><c:out value="${bill.name}"/></p>
            <div class="plus-icon">
                <ion-icon size="large" name="add-circle-outline</ion-icon
            </div>
        </div>
    </c:forEach>
</code>```

答:
Yes , you can do that by using jstl tag like below :

```<code><c:set var="category" value="${bill.category}"/>
</code>```

And then use above in div like below :

```<code>   <!--will print whatever is there in category-->
    <div class="selection${category}">
    </div>
</code>```

Body:
Im trying to get something out of my database to add to a class in my JSP.

<div class="selection <c:out value='${bill.category}'/>">

<c:forEach items="${bills}" var="bill">
        <div class="selection <c:out value='${bill.category}'/>">

<c:out value="${bill.name}"/>

                <ion-icon size="large" name="add-circle-outline</ion-icon

    </c:forEach>

Body:
Yes , you can do that by using jstl tag like below :

<c:set var="category" value="${bill.category}"/>

And then use above in div like below :

   <!--will print whatever is there in category-->
    <div class="selection${category}">
    </div>


问:
django select_for_update and select_related on same query?
Does anyone know if you can do both the .select_for_update() and .select_related() statements in a single query? Such as:

```<code>employee = get_object_or_404(Employee.objects.select_for_update().
                              select_related(‘company’), pk=3)
</code>```

It seemed to work fine in one place in my code, but a second usage threw an "InternalError: current transaction is aborted" for a series of unit tests. Removing the .select_related and leaving just .select_for_update made the error go away, but I don't know why. I'd like to use them both to optimize my code, but if forced to choose, I'll pick select_for_update.  Wondering if there's a way I can use both. Using postgres and django 1.9. Thanks!

答:
Since Django 2.0, you can use select_for_update together with select_related even on nullable relations - by using new parameter of=...

Using their Person example from docs, you could do

```<code>Person.objects.select_related('hometown').select_for_update(of=('self',))
</code>```

which would lock only the Person object

Body:
Does anyone know if you can do both the .select_for_update() and .select_related() statements in a single query? Such as:

employee = get_object_or_404(Employee.objects.select_for_update().
                              select_related(‘company’), pk=3)

It seemed to work fine in one place in my code, but a second usage threw an "InternalError: current transaction is aborted" for a series of unit tests. Removing the .select_related and leaving just .select_for_update made the error go away, but I don't know why. I'd like to use them both to optimize my code, but if forced to choose, I'll pick select_for_update.  Wondering if there's a way I can use both. Using postgres and django 1.9. Thanks!

Body:
Since Django 2.0, you can use select_for_update together with select_related even on nullable relations - by using new parameter of=...

Using their Person example from docs, you could do

Person.objects.select_related('hometown').select_for_update(of=('self',))

which would lock only the Person object


问:
How I can attach screenshot of failed Cucumber step to Allure report exactly in step, not in Tear Down section?
I can't add screenshot of failed cucumber step under the step in Allure report.

I use allure-cucumber4-jvm:2.12.1, cucumber-java:4.3.1 and try to add screenshot of tested web app to allure report EXACTLY under failed cucumber step. So I tried to use cucumber's @AfterStep and @After annotations and add screenshot in annotated methods under scenario.isFailed() conditions. But the problem is that screenshots are added after all steps in Tear Down section. The only difference is that @After method is called once and @AfterStep methods is called by every step.

```<code>@AfterStep
public void addScreenshotOnFailed(Scenario scenario) throws IOException {
        if (scenario.isFailed()) {
            try {
                Allure.addAttachment("Failed step", new FileInputStream(Screenshots.takeScreenShotAsFile()));
            } catch (FileNotFoundException ignored) {}
        }
    }
</code>```

I expect screenshot of tested web app exactly under failed cucumber step? but actually I have it in Tear Down section after all scenario

答:
Idea is using the events to capture the step status and embed the screenshot. If I am correct, As per current design AfterStep does not execute when the step is failed. So we have to use AfterConfiguration in hooks.

Ruby:
Here is the ruby implementation.

```<code>AfterConfiguration do |scenario, config|
    config.on_event :test_step_finished do |event|
        if event.result.failed?
          # get screenshot
        end
    end
  end
</code>```

Check this thread regarding the allure implementation.

Body:
I can't add screenshot of failed cucumber step under the step in Allure report.

I use allure-cucumber4-jvm:2.12.1, cucumber-java:4.3.1 and try to add screenshot of tested web app to allure report EXACTLY under failed cucumber step. So I tried to use cucumber's @AfterStep and @After annotations and add screenshot in annotated methods under scenario.isFailed() conditions. But the problem is that screenshots are added after all steps in Tear Down section. The only difference is that @After method is called once and @AfterStep methods is called by every step.

@AfterStep
public void addScreenshotOnFailed(Scenario scenario) throws IOException {
        if (scenario.isFailed()) {
            try {
                Allure.addAttachment("Failed step", new FileInputStream(Screenshots.takeScreenShotAsFile()));
            } catch (FileNotFoundException ignored) {}
        }
    }

I expect screenshot of tested web app exactly under failed cucumber step? but actually I have it in Tear Down section after all scenario

Body:
Idea is using the events to capture the step status and embed the screenshot. If I am correct, As per current design AfterStep does not execute when the step is failed. So we have to use AfterConfiguration in hooks.

Ruby:
Here is the ruby implementation.

AfterConfiguration do |scenario, config|
    config.on_event :test_step_finished do |event|
        if event.result.failed?
          # get screenshot
        end
    end
  end

Check this thread regarding the allure implementation.


问:
How to filter on a Option[Boolean] column in slick
I have the following column in my db, thats a Boolean, but also accepts NULL, so true, false, and NULL are all valid:

```<code>def rtb = column[Option[Boolean]]("rtb")
</code>```

and have the following optional input from the client that I'd like to filter on:

```<code>rtbFromClient: Option[Boolean] = ...
</code>```

I have the following (based on this answer on how to do queries in slick:  https://stackoverflow.com/a/40888918/5300930):

```<code>val query = userTable.
      filter(row =>
          if (rtbFromClient.isDefined)
              row.rtb.get === rtbFromClient.get
          else
              LiteralColumn(true)
      )
</code>```

but am getting this error when the code runs:

```<code>Caught exception while computing default value for Rep[Option[_]].getOrElse -- This cannot be done lazily when the value is needed on the database side
</code>```

I thought it may be because row.rtb.get was throwing exception on call to get because the value in the db was null, so tried changing it to row.rtb.getOrElse(null) and row.rtb.getOrElse(None) but neither of these worked either)

Also tried the following:

```<code>if (rtbFromClient.isDefined) {
    val query = query.filter(_.rtb.isDefined).filter(_.rtb.get === rtbFromClient.get)
}
</code>```

But this also throws the same error at runtime:

```<code>Caught exception while computing default value for Rep[Option[_]].getOrElse -- This cannot be done lazily when the value is needed on the database side
</code>```

To summarise:

I have an Option[Boolean] column in my db that can contain true, false or NULL (the actual mysql type is a tinyint(1), which is mapped to a slick Option[Boolean])

I have an optional filter provided by the user, rtbFromClient that I'd like to filter on if present. If present, this will be either true or false

I have other optional filters (not shown here) that have similar behavior so I'd like to be able to combine them easily

答:
I was facing the same issue. After playing around I realised one can filter by the option directly, so if we have the column

```<code>def rtb = column[Option[Boolean]]("rtb")
</code>```

and we're trying to filter by

```<code>rtbFromClient: Option[Boolean] = ...
</code>```

then we can do:

```<code>val query: DBIO[Seq[TableElementType]] =
  if (rtbFromClient.isDefined)
    userTable.filter(_.rtb === rtbFromClient).result
  else
    userTable.result
</code>```

Body:
I have the following column in my db, thats a Boolean, but also accepts NULL, so true, false, and NULL are all valid:

def rtb = column[Option[Boolean]]("rtb")

and have the following optional input from the client that I'd like to filter on:

rtbFromClient: Option[Boolean] = ...

I have the following (based on this answer on how to do queries in slick:  https://stackoverflow.com/a/40888918/5300930):

val query = userTable.
      filter(row =>
          if (rtbFromClient.isDefined)
              row.rtb.get === rtbFromClient.get
          else
              LiteralColumn(true)
      )

but am getting this error when the code runs:

Caught exception while computing default value for Rep[Option[_]].getOrElse -- This cannot be done lazily when the value is needed on the database side

I thought it may be because row.rtb.get was throwing exception on call to get because the value in the db was null, so tried changing it to row.rtb.getOrElse(null) and row.rtb.getOrElse(None) but neither of these worked either)

Also tried the following:

if (rtbFromClient.isDefined) {
    val query = query.filter(_.rtb.isDefined).filter(_.rtb.get === rtbFromClient.get)
}

But this also throws the same error at runtime:

Caught exception while computing default value for Rep[Option[_]].getOrElse -- This cannot be done lazily when the value is needed on the database side

To summarise:

I have an Option[Boolean] column in my db that can contain true, false or NULL (the actual mysql type is a tinyint(1), which is mapped to a slick Option[Boolean])

I have an optional filter provided by the user, rtbFromClient that I'd like to filter on if present. If present, this will be either true or false

I have other optional filters (not shown here) that have similar behavior so I'd like to be able to combine them easily

Body:
I was facing the same issue. After playing around I realised one can filter by the option directly, so if we have the column

def rtb = column[Option[Boolean]]("rtb")

and we're trying to filter by

rtbFromClient: Option[Boolean] = ...

then we can do:

val query: DBIO[Seq[TableElementType]] =
  if (rtbFromClient.isDefined)
    userTable.filter(_.rtb === rtbFromClient).result
  else
    userTable.result