问:
javascript Cannot pass variables between 2 functions
I am wondering how to pass a variable between 2 functions.

I have looked on Stackoverflow but all examples I tried did not work for me.

I have function, which calculates an array: arrR.

Now, I would like to call this variable somewhere else:

```<code>function my_function(arrR) {
    return(arrR[1]);
}

function onRefresh(chart) {
    chart.config.data.datasets.forEach(function(dataset) {
        dataset.data.push({
            x: Date.now(),
            y: myfunction(arrR)
        });
    });
}
</code>```

But y: myfunction(arrR) gives notting. I have checked that if I put some number say y: 1 this works.

Any clue ?

Many thanks

答: your arrR variable is inside a function. It might be that the scope of that variable will be inside the function only.Try declaring this variable outside the function to use it globally.Hope it helps.:)</p>

Body:
I am wondering how to pass a variable between 2 functions.

I have looked on Stackoverflow but all examples I tried did not work for me.

I have function, which calculates an array: arrR.

Now, I would like to call this variable somewhere else:

function my_function(arrR) {
    return(arrR[1]);
}

function onRefresh(chart) {
    chart.config.data.datasets.forEach(function(dataset) {
        dataset.data.push({
            x: Date.now(),
            y: myfunction(arrR)
        });
    });
}

But y: myfunction(arrR) gives notting. I have checked that if I put some number say y: 1 this works.

Any clue ?

Many thanks


来源: stackexchange

问:
PHP block shortcut in Visual Studio Code
How can I open a basic PHP block in Visual Studio Code, like so - <?php ?>?

In Sublime Text I simply type php and press Tab, and the block is created. But I can't find the same shortcut for Visual Studio Code.

答:
Use:

Open Visual Studio Code

Open menu File → Preferences → User Snippets

Search and select "html.json"

Now paste this code in {}:

```<code> "php": {
     "prefix": ["<?", "<? ", "php"],
     "body": [ "<?php $1 ?>" ],
     "description": "php tag"
 }
</code>```

Now you can use "<?" or "<? " or "php".

ContentLicense: CC BY-SA 4.0

Body:
Use:

Open Visual Studio Code

Open menu File → Preferences → User Snippets

Search and select "html.json"

Now paste this code in {}:

 "php": {
     "prefix": ["<?", "<? ", "php"],
     "body": [ "<?php $1 ?>" ],
     "description": "php tag"
 }

Now you can use "<?" or "<? " or "php".


问:
Tomcat behind Nginx: how to proxy both HTTP and HTTPS, possibly on non-standard ports?

Description

We're installing some application running Tomcat 6 behind Nginx for different clients. Some of those installations are HTTP only, some HTTPS only, somewhere both. One of those installations has HTTP and HTTPS working on non-standard ports (8070 and 8071) due to lack of public IPs. Application at hand is displayed as an iframe in another app.

Current behaviour

Tomcat redirects all HTTPS requests to HTTP (so nothing displayed in iframe due to browser restrictions for mixed content).

Current configuration

Iframe code:

```

<p>Tomcat's <code>server.xml</code>:</p>

<pre class="lang-xml prettyprint-override"><code><Connector port="8080" protocol="HTTP/1.1"/>
<!-- A bit later... -->
<Valve className="org.apache.catalina.valves.RemoteIpValve"
      remoteIpHeader="x-forwarded-for"
      protocolHeader="x-forwarded-proto"
    />
</code>```

Nginx vhost:

```<code>server {
  listen 80;
  listen 443 ssl spdy;

  location /saiku-ui {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://saiku-server; # This is upstream name
    proxy_redirect off;
  }
}

upstream saiku-server {
  server ip.of.tomcat.server:8080;
}
</code>```

Desired behaviour

Tomcat should listen on one single port for both HTTP and HTTPS requests.

If there will be two <Connector> tags it will be much harder to configure Nginx.

Tomcat should not redirect between schemas.

Nginx may listen on arbitrary ports (e.g. listen 8071 ssl spdy;).

Links, generated by Tomcat should be either relative or include schema, host, and port as provided by Nginx.

Additional info

I've tried to add schema and proxyPort attributes to <Connector>, after that Tomcat will always redirect from HTTP to HTTPS (at least it's better).

I can't google such a configuration and not experienced with Tomcat. Please help.

答:
If you are using Spring and don't want to change the tomcat configuration, there is another solution based on this answer.

After a few hours of google, I found there is no standard solution like a officially supported configuration, refer this comment.

See the java doc HttpServletResponse.sendRedirect.

Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading '/' the container interprets it as relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative to the servlet container root.

HttpServletResponseWrapper

```<code>import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

public class SendRedirectOverloadedResponseBasedOnXForwardedProtocol extends HttpServletResponseWrapper {

    private HttpServletRequest request;

    public SendRedirectOverloadedResponseBasedOnXForwardedProtocol(HttpServletRequest request,
                                                                   HttpServletResponse response) {
        super(response);
        this.request = request;
    }

    public void sendRedirect(String location) throws IOException {

        String xForwardedProtocol = request.getHeader("X-Forwarded-Protocol");
        String host = request.getHeader("Host");
        if (StringUtils.isNotBlank(xForwardedProtocol) && StringUtils.isNotBlank(host) && !isUrlAbsolute(location)) {
            location = xForwardedProtocol + "://" + host + location;
        }
        super.sendRedirect(location);
    }

    public boolean isUrlAbsolute(String location) {
        location = location == null ? "" : location;
        return location.toLowerCase().startsWith("http");
    }
}
</code>```

Filter

```<code>import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SendRedirectBasedOnXForwardedProtocolFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, new SendRedirectOverloadedResponseBasedOnXForwardedProtocol((HttpServletRequest) request, (HttpServletResponse) response));
    }

    @Override
    public void destroy() {
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Description

We're installing some application running Tomcat 6 behind Nginx for different clients. Some of those installations are HTTP only, some HTTPS only, somewhere both. One of those installations has HTTP and HTTPS working on non-standard ports (8070 and 8071) due to lack of public IPs. Application at hand is displayed as an iframe in another app.

Current behaviour

Tomcat redirects all HTTPS requests to HTTP (so nothing displayed in iframe due to browser restrictions for mixed content).

Current configuration

Iframe code:

Tomcat's server.xml:

<Connector port="8080" protocol="HTTP/1.1"/>

<Valve className="org.apache.catalina.valves.RemoteIpValve"
      remoteIpHeader="x-forwarded-for"
      protocolHeader="x-forwarded-proto"
    />

Nginx vhost:

server {
  listen 80;
  listen 443 ssl spdy;

  location /saiku-ui {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://saiku-server; # This is upstream name
    proxy_redirect off;
  }
}

upstream saiku-server {
  server ip.of.tomcat.server:8080;
}

Desired behaviour

Tomcat should listen on one single port for both HTTP and HTTPS requests.

If there will be two <Connector> tags it will be much harder to configure Nginx.

Tomcat should not redirect between schemas.

Nginx may listen on arbitrary ports (e.g. listen 8071 ssl spdy;).

Links, generated by Tomcat should be either relative or include schema, host, and port as provided by Nginx.

Additional info

I've tried to add schema and proxyPort attributes to <Connector>, after that Tomcat will always redirect from HTTP to HTTPS (at least it's better).

I can't google such a configuration and not experienced with Tomcat. Please help.

Body:
If you are using Spring and don't want to change the tomcat configuration, there is another solution based on this answer.

After a few hours of google, I found there is no standard solution like a officially supported configuration, refer this comment.

See the java doc HttpServletResponse.sendRedirect.

Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading '/' the container interprets it as relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative to the servlet container root.

HttpServletResponseWrapper

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

public class SendRedirectOverloadedResponseBasedOnXForwardedProtocol extends HttpServletResponseWrapper {

    private HttpServletRequest request;

    public SendRedirectOverloadedResponseBasedOnXForwardedProtocol(HttpServletRequest request,
                                                                   HttpServletResponse response) {
        super(response);
        this.request = request;
    }

    public void sendRedirect(String location) throws IOException {

        String xForwardedProtocol = request.getHeader("X-Forwarded-Protocol");
        String host = request.getHeader("Host");
        if (StringUtils.isNotBlank(xForwardedProtocol) && StringUtils.isNotBlank(host) && !isUrlAbsolute(location)) {
            location = xForwardedProtocol + "://" + host + location;
        }
        super.sendRedirect(location);
    }

    public boolean isUrlAbsolute(String location) {
        location = location == null ? "" : location;
        return location.toLowerCase().startsWith("http");
    }
}

Filter

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SendRedirectBasedOnXForwardedProtocolFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, new SendRedirectOverloadedResponseBasedOnXForwardedProtocol((HttpServletRequest) request, (HttpServletResponse) response));
    }

    @Override
    public void destroy() {
    }
}


问:
Windows PSQL command line: is there a way to allow for passwordless login?
My goal is to be able to fire off a command without having to be prompted for my password. Is there any way to achieve this from the windows command line? In Linux I feel I could send the password to standard in or something, but I am not sure if I could do this for windows.

Thanks!

答:
There are two ways:

Set environment variable PGPASSWORD e.g. set PGPASSWORD=yoursecretpassword

Use password file %APPDATA%\postgresql\pgpass.conf as described in documentation

Within password file (my location is C:\Users\Grzesiek\AppData\Roaming\postgresql\pgpass.conf) use specified in doc format. For example to connect database postgres as role postgres on local 5432 server add:

```<code>localhost:5432:postgres:postgres:12345
</code>```

I checked this and it works well (for me), but don't use 127.0.0.1).

Body:
There are two ways:

Set environment variable PGPASSWORD e.g. set PGPASSWORD=yoursecretpassword

Use password file %APPDATA%\postgresql\pgpass.conf as described in documentation

Within password file (my location is C:\Users\Grzesiek\AppData\Roaming\postgresql\pgpass.conf) use specified in doc format. For example to connect database postgres as role postgres on local 5432 server add:

localhost:5432:postgres:postgres:12345

I checked this and it works well (for me), but don't use 127.0.0.1).


问:
How to simplify many if else statements
I want to simplify this code and want to make it smarter, there are about 80 singleS and multipleS's. I considered State design pattern usage but it seems that it wont be simpler. Can anybody help me with the below lines:</p>

```<code>void spy::run(string num, SingleS single, MultipleS multipleS)
{
if(num == "1")
{singleS.runS1}
else if(num == "2")
{singleS.runS2}
else if(num == "3")
{singleS.runS3}
else if(num == "4")
{singleS.runS4}
else if(num == "5")
{singleS.runS5}
else if(num == "6")
{singleS.runS6}
else if(num == "7")
{singleS.runS7}
else if(num == "8")
{singleS.runS8}
else if(num == "9")
{singleS.runS9}
else if(num == "10")
{multipleS.runS10}
else if(num == "11")
{multipleS.runS11}
else if(num == "12")
{multipleS.runS12}
else if(num == "13")
{multipleS.runS13}
}
}

</code>```

答:
You can try nested ternary :</p>

```<code>void spy::run(string num, SingleS single, MultipleS multipleS)
{

    (num=="1")?singleS.runS1:(num=="2")?singleS.runS2:(num=="3")?singleS.runS3:(num=="4")...;
}
</code>```

Title: How to simplify many if else statements

Body:
I want to simplify this code and want to make it smarter, there are about 80 singleS and multipleS's. I considered State design pattern usage but it seems that it wont be simpler. Can anybody help me with the below lines:

void spy::run(string num, SingleS single, MultipleS multipleS)
{
if(num == "1")
{singleS.runS1}
else if(num == "2")
{singleS.runS2}
else if(num == "3")
{singleS.runS3}
else if(num == "4")
{singleS.runS4}
else if(num == "5")
{singleS.runS5}
else if(num == "6")
{singleS.runS6}
else if(num == "7")
{singleS.runS7}
else if(num == "8")
{singleS.runS8}
else if(num == "9")
{singleS.runS9}
else if(num == "10")
{multipleS.runS10}
else if(num == "11")
{multipleS.runS11}
else if(num == "12")
{multipleS.runS12}
else if(num == "13")
{multipleS.runS13}
}
}

Body:
You can try nested ternary :

void spy::run(string num, SingleS single, MultipleS multipleS)
{

    (num=="1")?singleS.runS1:(num=="2")?singleS.runS2:(num=="3")?singleS.runS3:(num=="4")...;
}


问:
SimpleInjector force Lifestyle.Transient for Unregistered-Type
I have a wrapper class as below:

```<code>// this is not used for IoC purposes, but by code to cast object to known T
internal interface ITaskCompletionSourceWrapper
{
    void SetResult(object result);
    /* snip */
}

internal class TaskCompletionSourceGenericWrapper<TResult> : ITaskCompletionSourceWrapper
{
    readonly TaskCompletionSource<TResult> tcs;
    public TaskCompletionSourceGenericWrapper() =>
        this.tcs = new TaskCompletionSource<TResult>(TaskCreationOptions.RunContinuationsAsynchronously);
    public void SetResult(object result) => tcs.SetResult((TResult)result);
    /* snip */
}
</code>```

Where i currently instantiate using Activator:

```<code>var responseType = request
                     .GetType()
                     .GetInterfaces()
                     .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRequest<>))
                     GetGenericArguments()[0];

var wrapperType = typeof(TaskCompletionSourceGenericWrapper<>).MakeGenericType(responseType);
var tcsWrapper = this.container.GetInstance(wrapperType) as ITaskCompletionSourceWrapper;
</code>```

I switched this to SimpleInjector (as may use logging and other IOC goodness) and thought all was well until I found an issue (which was due to lifestyle being shared):

```<code>/* snip responseType code from above */
var wrapperType = typeof(TaskCompletionSourceGenericWrapper<>).MakeGenericType(responseType);
var tcsWrapper = this.container.GetInstance(wrapperType) as ITaskCompletionSourceWrapper;

// i can see the type has been registered as scoped, but we need it to be unique
[30] = ServiceType = TaskCompletionSourceGenericWrapper<Object>, Lifestyle = Async Scoped
</code>```

The above is being called within a AsyncScopedLifestyle.BeginScope block.

I would like to instantiate this wrapper at runtime using SimpleInjector (but ensuring Lifestyle.Transient):

The types for the wrapper are pretty much arbitrary from int, string, bool etc but could also be simple POCO classes.

This is similar to a case of open generic registration but I would rather avoid having other developers specify assemblies for the simple types (as for sure they will forget, and their classes are simple anyways - command/query POCOs and the like).

How can I achieve the above please or am I forced to register collection?

Or is this deeper with lifestyle mismatches - I hope not, since the wrapper has no dependencies (and will not other than ILogger perhaps) is only doing something instantiation of a simple class (which I want to replace Activator rather than decouple components IoC style).

答:
Based on their docs Batch-Registration / Auto-Registration and experience, you need to register the implementation of the interface when using dependency injection.

```<code>var container = new Container();
// If related classes exist in a different assembly then add them here
var assemblies = new[] { typeof(TaskCompletionSourceGenericWrapper<>).Assembly };

container.Collection.Register(typeof(TaskCompletionSourceGenericWrapper<>), assemblies, Lifestyle.Transient);

DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
</code>```

One hack that I can think of but haven't tested is to create a wrapper class that returns a deep copy a.k.a clone of your wrapper. Returning a clone of an object is similar to transient as it returns a new instance every time you request for it but the downside on this approach is that you can only do it for serializable classes so you may need to add [Serializable()]. Refer to Deep cloning objects for more info.

```<code>public interface IUglyDuckling
{
    ITaskCompletionSourceWrapper GetITaskCompletionSourceWrapper(Type type);
}
public class UglyDuckling : IUglyDuckling
{
    public ITaskCompletionSourceWrapper GetITaskCompletionSourceWrapper(Type type)
    {
        var wrapperType = typeof(TaskCompletionSourceGenericWrapper<>).MakeGenericType(type);
        var tcsWrapper = this.container.GetInstance(wrapperType) as ITaskCompletionSourceWrapper;
        return ObjectCopier.Clone<ITaskCompletionSourceWrapper>(tcsWrapper);
    }
}
</code>```

Body:
I have a wrapper class as below:

// this is not used for IoC purposes, but by code to cast object to known T
internal interface ITaskCompletionSourceWrapper
{
    void SetResult(object result);
    /* snip */
}

internal class TaskCompletionSourceGenericWrapper<TResult> : ITaskCompletionSourceWrapper
{
    readonly TaskCompletionSource<TResult> tcs;
    public TaskCompletionSourceGenericWrapper() =>
        this.tcs = new TaskCompletionSource<TResult>(TaskCreationOptions.RunContinuationsAsynchronously);
    public void SetResult(object result) => tcs.SetResult((TResult)result);
    /* snip */
}

Where i currently instantiate using Activator:

var responseType = request
                     .GetType()
                     .GetInterfaces()
                     .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRequest<>))
                     GetGenericArguments()[0];

var wrapperType = typeof(TaskCompletionSourceGenericWrapper<>).MakeGenericType(responseType);
var tcsWrapper = this.container.GetInstance(wrapperType) as ITaskCompletionSourceWrapper;

I switched this to SimpleInjector (as may use logging and other IOC goodness) and thought all was well until I found an issue (which was due to lifestyle being shared):

/* snip responseType code from above */
var wrapperType = typeof(TaskCompletionSourceGenericWrapper<>).MakeGenericType(responseType);
var tcsWrapper = this.container.GetInstance(wrapperType) as ITaskCompletionSourceWrapper;

// i can see the type has been registered as scoped, but we need it to be unique
[30] = ServiceType = TaskCompletionSourceGenericWrapper<Object>, Lifestyle = Async Scoped

The above is being called within a AsyncScopedLifestyle.BeginScope block.

I would like to instantiate this wrapper at runtime using SimpleInjector (but ensuring Lifestyle.Transient):

The types for the wrapper are pretty much arbitrary from int, string, bool etc but could also be simple POCO classes.

This is similar to a case of open generic registration but I would rather avoid having other developers specify assemblies for the simple types (as for sure they will forget, and their classes are simple anyways - command/query POCOs and the like).

How can I achieve the above please or am I forced to register collection?

Or is this deeper with lifestyle mismatches - I hope not, since the wrapper has no dependencies (and will not other than ILogger perhaps) is only doing something instantiation of a simple class (which I want to replace Activator rather than decouple components IoC style).

Body:
Based on their docs Batch-Registration / Auto-Registration and experience, you need to register the implementation of the interface when using dependency injection.

var container = new Container();
// If related classes exist in a different assembly then add them here
var assemblies = new[] { typeof(TaskCompletionSourceGenericWrapper<>).Assembly };

container.Collection.Register(typeof(TaskCompletionSourceGenericWrapper<>), assemblies, Lifestyle.Transient);

DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

One hack that I can think of but haven't tested is to create a wrapper class that returns a deep copy a.k.a clone of your wrapper. Returning a clone of an object is similar to transient as it returns a new instance every time you request for it but the downside on this approach is that you can only do it for serializable classes so you may need to add [Serializable()]. Refer to Deep cloning objects for more info.

public interface IUglyDuckling
{
    ITaskCompletionSourceWrapper GetITaskCompletionSourceWrapper(Type type);
}
public class UglyDuckling : IUglyDuckling
{
    public ITaskCompletionSourceWrapper GetITaskCompletionSourceWrapper(Type type)
    {
        var wrapperType = typeof(TaskCompletionSourceGenericWrapper<>).MakeGenericType(type);
        var tcsWrapper = this.container.GetInstance(wrapperType) as ITaskCompletionSourceWrapper;
        return ObjectCopier.Clone<ITaskCompletionSourceWrapper>(tcsWrapper);
    }
}


问:
I'm looking for a way to turn output into an Octet
I'm writing a program that handles binary numbers in C#, after i convert the decimal numbers to binary, it will only take as much space as needed, but i need all 4 outputs to be octets (8 characters).

Let's say i convert 255.255.255.0 to binary i get the following outputs

```<code>11111111
11111111
11111111
0
</code>```

what i would want is to get 7 zeroes behind the 0, as it needs to fill out all 8 spaces.
It is always 8 since I'm working with Subnet masks

I hope any of you can help, thank you. :)

答:
You can use the below code. You can split the string and pad left each string.</p>

```<code>string binary = String.Join(Environment.NewLine, (input.Split('.').Select(x => Convert.ToString(Int32.Parse(x), 2).PadLeft(8, '0'))).ToArray());
</code>```

Body:
I'm writing a program that handles binary numbers in C#, after i convert the decimal numbers to binary, it will only take as much space as needed, but i need all 4 outputs to be octets (8 characters).

Let's say i convert 255.255.255.0 to binary i get the following outputs

11111111
11111111
11111111
0

what i would want is to get 7 zeroes behind the 0, as it needs to fill out all 8 spaces.
It is always 8 since I'm working with Subnet masks

I hope any of you can help, thank you. :)

Body:
You can use the below code. You can split the string and pad left each string.

string binary = String.Join(Environment.NewLine, (input.Split('.').Select(x => Convert.ToString(Int32.Parse(x), 2).PadLeft(8, '0'))).ToArray());


问:
What is "System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection"?
I wanted to find consecutive and non-consecutive numbers separated by hyphens.
Once i ran this given code it gave me an error as "System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'". What is wrong with this code, please explain if anyone knows..</p>

```<code>    public static void Main(string[] args)
    {
        Console.Write("Enter a few numbers (eg 1-2-3-4): ");

        var input = Console.ReadLine();
        var numArray = new List<int>();

        foreach (var number in input.Split('-'))
        {
            numArray.Add(Convert.ToInt32(number));
        }
        numArray.Sort();

        var isConsecutive = true;
        for (int i = 0; i < numArray.Count; i++)
        {
            if (numArray[i] != numArray[i + 1] - 1)
            {
                isConsecutive = false;
                break;
            }
        }

        if (isConsecutive)
        {
            Console.WriteLine("Consecutive");
            Console.ReadLine();
        }
        else
        {
            Console.WriteLine("Not Consecutive");
            Console.ReadLine();
        }
    }
</code>```

答:
The problem is :

```<code>numArray[i + 1]
</code>```

when your i reaches the last index, there is no item left at i+1 which ends up in index out of range exception.

You need to rethink about the logic if you really need i + 1 and safe guard so that you don't access the index that does not exists actually.

probably you want :

```<code>for (int i = 0; i < numArray.Count - 1; i++)
</code>```

so that it stops at the second last item of the array.

Body:
I wanted to find consecutive and non-consecutive numbers separated by hyphens.
Once i ran this given code it gave me an error as "System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'". What is wrong with this code, please explain if anyone knows..

    public static void Main(string[] args)
    {
        Console.Write("Enter a few numbers (eg 1-2-3-4): ");

        var input = Console.ReadLine();
        var numArray = new List<int>();

        foreach (var number in input.Split('-'))
        {
            numArray.Add(Convert.ToInt32(number));
        }
        numArray.Sort();

        var isConsecutive = true;
        for (int i = 0; i < numArray.Count; i++)
        {
            if (numArray[i] != numArray[i + 1] - 1)
            {
                isConsecutive = false;
                break;
            }
        }

        if (isConsecutive)
        {
            Console.WriteLine("Consecutive");
            Console.ReadLine();
        }
        else
        {
            Console.WriteLine("Not Consecutive");
            Console.ReadLine();
        }
    }

Body:
The problem is :

numArray[i + 1]

when your i reaches the last index, there is no item left at i+1 which ends up in index out of range exception.

You need to rethink about the logic if you really need i + 1 and safe guard so that you don't access the index that does not exists actually.

probably you want :

for (int i = 0; i < numArray.Count - 1; i++)

so that it stops at the second last item of the array.


问:
Spliting paragraph into sub - paragraphs which have meaningfull
Normally, a paragraph contain many sub - paragraph and each sub - paragraph has the certain meaning.

In NLP, How can I split paragraph into sub - paragraph which have meaning or in other words, I would like to detect the boundaries between sub-paragraphs

答:
The problem you are stating is interesting, but poorly defined, because "meaning" itself is defined poorly, and we actually don't know how to tell a good partition of the paragraph from a bad one.

However, we can simplify the problem as this: we want to group together adjacent sentences, if their topic is similar, i.e. if they are about the same or similar objects, or contain otherwise similar words or phrases. Thus we can describe our algorithm formally:

Split the paragraph into sentences.

Represent each sentence as some formal object (e.g. a bag of words, or a bag of word embeddings from w2v, fasttext, ELMO or BERT, or a sentence embedding from some neural network, such as USE).

Compute the distances between each pair of sentences (e.g. cosine distance between sentence embeddings or word counts, or word mover distance between word embeddings).

Run an agglomerative clustering algorithm on this distance matrix, with one additional restriction: only adjacent clusters can be merged together.

Try the clustering on different paragraphs with different stopping criteria (usually thresholds) and choose the threshold which produces the most meaningful partitions.

If this algorithm looks like what you want, I could provide its baseline implementation in Python.

Upd Please take a loog at this gist with my basic implementation: Spacy sentenizer + cosine similarity of Spacy sentence vectors + naive clustering based only on neighbouring sentences.
https://gist.github.com/avidale/e4450da902d36bb14c595987943120dc


问:
Build Gradle Local Dependency
How do you declare a local dependency for gradle 4.10.3 to not use the github project and use your own custom build of the project? Open source project I'm trying to compile https://github.com/kami-blue/client

My build is at /Users/macbook/Desktop/baritone-master/dist/baritone-api-1.2.14.jar

I've tried changing the file path to it and commenting out the two compile commands but that didn't work.

```<code>//compile 'com.github.cabaletta:baritone:1.2.14'
//compile 'cabaletta:baritone-api:1.2'
include(dependency('/Users/macbook/Desktop/baritone-master/dist/baritone-api-1.2.14.jar'))
</code>```

Using these either of these two methods do not work either:

```<code>implementation files('/Users/macbook/Desktop/baritone-master/dist/baritone-api-1.2.14.jar')
compile fileTree(dir: '/Users/macbook/Desktop/baritone-master/dist', include: ['*.jar'])
</code>```

build.gradle file:

```<code>buildscript {
    repositories {
        jcenter()
        maven {
            name = 'forge'
            url = 'http://files.minecraftforge.net/maven'
        }
        maven {
            name = 'SpongePowered'
            url = 'http://repo.spongepowered.org/maven'
        }
    }
    dependencies {
        classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
        classpath 'org.spongepowered:mixingradle:0.6-SNAPSHOT'
        classpath 'com.github.jengelman.gradle.plugins:shadow:4.0.3'
        classpath group: 'org.jetbrains.kotlin', name: 'kotlin-gradle-plugin', version: "${kotlin_version}"    }
}

apply plugin: 'kotlin'
apply plugin: 'net.minecraftforge.gradle.forge'
apply plugin: 'org.spongepowered.mixin'
apply plugin: 'com.github.johnrengelman.shadow'

version project.modVersion
group project.modGroup // http://maven.apache.org/guides/mini/guide-naming-conventions.html

compileKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}
compileTestKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

sourceCompatibility = targetCompatibility = '1.8'
compileJava {
    sourceCompatibility = targetCompatibility = '1.8'
}

minecraft {
    version = project.forgeVersion
    runDir = 'run'
    mappings = project.mcpVersion
    coreMod = 'me.zeroeightsix.kami.mixin.MixinLoaderForge'
    makeObfSourceJar = false
}

repositories {
    maven {
        name = 'spongepowered-repo'
        url = 'http://repo.spongepowered.org/maven/'
    }
    maven {
        name = 'impactdevelopment-repo'
        url = 'https://impactdevelopment.github.io/maven/'
    }
    maven {
        name = 'swt-repo'
        url = "http://maven-eclipse.github.io/maven"
    }
    maven {
        name = "jitpack.io"
        url = "https://jitpack.io"
    }
    maven {
        name = "forgelin-repo"
        url "http://maven.shadowfacts.net/"
    }
    mavenCentral()
    jcenter()
}

dependencies {
    // mixin needs to be distributed with the mod, very important
    compile("org.spongepowered:mixin:0.7.11-SNAPSHOT") { // do NOT update this to 8.0 or above, it breaks compatibility with future client
        exclude module: 'launchwrapper'
        exclude module: 'guava'
        exclude module: 'gson'
        exclude module: 'commons-io'
        exclude module: 'log4j-core' // we want to exclude this as well because 0.7.11 includes it too new for MC
    }
    compile "com.github.ZeroMemes:Alpine:1.7"
    compile group: 'net.jodah', name: 'typetools', version: '0.6.2'
    compile group: 'org.yaml', name: 'snakeyaml', version: '1.26'
    compile(group: 'org.reflections', name: 'reflections', version: '0.9.12') {
        exclude group: 'com.google.guava', module: 'guava'
    }
    compile 'club.minnced:java-discord-rpc:2.0.2'
    compile 'com.github.MrPowerGamerBR:TemmieWebhook:-SNAPSHOT'
    compile 'com.github.kevinsawicki:http-request:http-request-6.0'
    compile 'com.github.cabaletta:baritone:1.2.14'
    compile 'cabaletta:baritone-api:1.2'
    compile group: "net.shadowfacts", name: "Forgelin", version: "1.8.4"
    compile group: "org.jetbrains.kotlin", name: "kotlin-stdlib", version: kotlin_version
    compile group: "org.jetbrains.kotlin", name: "kotlin-stdlib-jdk7", version: kotlin_version
    compile group: "org.jetbrains.kotlin", name: "kotlin-stdlib-jdk8", version: kotlin_version
    compile group: "org.jetbrains.kotlin", name: "kotlin-reflect", version: kotlin_version
    compile group: "org.jetbrains", name: "annotations", version: annotations_version
    compile group: "org.jetbrains.kotlinx", name: "kotlinx-coroutines-core", version: coroutines_version
    compile group: "org.jetbrains.kotlinx", name: "kotlinx-coroutines-jdk8", version: coroutines_version
}

processResources {
    // this will ensure that this task is redone when the versions change.
    inputs.property 'version', project.version
    inputs.property 'mcversion', project.minecraft.version

    // replace stuff in mcmod.info, nothing else
    from(sourceSets.main.resources.srcDirs) {
        include 'mcmod.info'

        // replace version and mcversion
        expand 'version': project.version, 'mcversion': project.minecraft.version
    }

    // copy everything else, thats not the mcmod.info
    from(sourceSets.main.resources.srcDirs) {
        exclude 'mcmod.info'
    }

    // move _at.cfg into META-INF
    rename '(.+_at.cfg)', 'META-INF/$1'
}

shadowJar {
    dependencies {
        include(dependency('org.spongepowered:mixin'))
        include(dependency('com.github.ZeroMemes:Alpine'))
        include(dependency('club.minnced:java-discord-rpc'))
        include(dependency('net.jodah:typetools'))
        include(dependency('org.yaml:snakeyaml'))
        include(dependency('org.reflections:reflections'))
        include(dependency('org.javassist:javassist'))
        include(dependency('com.github.MrPowerGamerBR:TemmieWebhook'))
        include(dependency('com.github.kevinsawicki:http-request'))
        include(dependency('cabaletta:baritone-api'))
        include(dependency("org.jetbrains.kotlin:kotlin-stdlib:${kotlin_version}"))
        include(dependency("org.jetbrains.kotlin:kotlin-stdlib-jdk7:${kotlin_version}"))
        include(dependency("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlin_version}"))
        include(dependency("org.jetbrains.kotlin:kotlin-reflect:${kotlin_version}"))
        include(dependency("org.jetbrains:annotations:${annotations_version}"))
        include(dependency("org.jetbrains.kotlinx:kotlinx-coroutines-core:${coroutines_version}"))
        include(dependency("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:${coroutines_version}"))
        include(dependency('net.shadowfacts:Forgelin'))
    }
    exclude 'dummyThing' // can someone explain why this is here
    classifier = 'release'
}

mixin {
    defaultObfuscationEnv searge
    add sourceSets.main, 'mixins.kami.refmap.json'
}

reobf {
    shadowJar {
        mappingType = 'SEARGE'
        classpath = sourceSets.main.compileClasspath
    }
}

// Don't put baritone mixin here please c:
jar {
    manifest {
        attributes(
                'MixinConfigs': 'mixins.kami.json',
                'tweakClass': 'org.spongepowered.asm.launch.MixinTweaker',
                'TweakOrder': 0,
                'FMLCorePluginContainsFMLMod': 'true',
                'FMLCorePlugin': 'me.zeroeightsix.kami.mixin.MixinLoaderForge',
                'ForceLoadAsMod': 'true',
                'FMLAT': 'kami_at.cfg'
        )
    }
}

build.dependsOn(shadowJar)
</code>```

答:
Please try this. Should fix your problem.

In this case gradle will try to use a relative path for a local jar dependency.

Read those documentaries for more information

```<code>dependencies {
    implementation files('/Users/macbook/Desktop/baritone-master/dist/baritone-api-1.2.14.jar')
}
</code>```

Additionally you can add all jars in X directory.

```<code>dependencies {
    compile fileTree(dir: 'yourDirection', include: ['*.jar'])
}
</code>```

Title: Build Gradle Local Dependency

Body:
How do you declare a local dependency for gradle 4.10.3 to not use the github project and use your own custom build of the project? Open source project I'm trying to compile https://github.com/kami-blue/client

My build is at /Users/macbook/Desktop/baritone-master/dist/baritone-api-1.2.14.jar

I've tried changing the file path to it and commenting out the two compile commands but that didn't work.

//compile 'com.github.cabaletta:baritone:1.2.14'
//compile 'cabaletta:baritone-api:1.2'
include(dependency('/Users/macbook/Desktop/baritone-master/dist/baritone-api-1.2.14.jar'))

Using these either of these two methods do not work either:

implementation files('/Users/macbook/Desktop/baritone-master/dist/baritone-api-1.2.14.jar')
compile fileTree(dir: '/Users/macbook/Desktop/baritone-master/dist', include: ['*.jar'])

build.gradle file:

buildscript {
    repositories {
        jcenter()
        maven {
            name = 'forge'
            url = 'http://files.minecraftforge.net/maven'
        }
        maven {
            name = 'SpongePowered'
            url = 'http://repo.spongepowered.org/maven'
        }
    }
    dependencies {
        classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
        classpath 'org.spongepowered:mixingradle:0.6-SNAPSHOT'
        classpath 'com.github.jengelman.gradle.plugins:shadow:4.0.3'
        classpath group: 'org.jetbrains.kotlin', name: 'kotlin-gradle-plugin', version: "${kotlin_version}"    }
}

apply plugin: 'kotlin'
apply plugin: 'net.minecraftforge.gradle.forge'
apply plugin: 'org.spongepowered.mixin'
apply plugin: 'com.github.johnrengelman.shadow'

version project.modVersion
group project.modGroup // http://maven.apache.org/guides/mini/guide-naming-conventions.html

compileKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}
compileTestKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

sourceCompatibility = targetCompatibility = '1.8'
compileJava {
    sourceCompatibility = targetCompatibility = '1.8'
}

minecraft {
    version = project.forgeVersion
    runDir = 'run'
    mappings = project.mcpVersion
    coreMod = 'me.zeroeightsix.kami.mixin.MixinLoaderForge'
    makeObfSourceJar = false
}

repositories {
    maven {
        name = 'spongepowered-repo'
        url = 'http://repo.spongepowered.org/maven/'
    }
    maven {
        name = 'impactdevelopment-repo'
        url = 'https://impactdevelopment.github.io/maven/'
    }
    maven {
        name = 'swt-repo'
        url = "http://maven-eclipse.github.io/maven"
    }
    maven {
        name = "jitpack.io"
        url = "https://jitpack.io"
    }
    maven {
        name = "forgelin-repo"
        url "http://maven.shadowfacts.net/"
    }
    mavenCentral()
    jcenter()
}

dependencies {
    // mixin needs to be distributed with the mod, very important
    compile("org.spongepowered:mixin:0.7.11-SNAPSHOT") { // do NOT update this to 8.0 or above, it breaks compatibility with future client
        exclude module: 'launchwrapper'
        exclude module: 'guava'
        exclude module: 'gson'
        exclude module: 'commons-io'
        exclude module: 'log4j-core' // we want to exclude this as well because 0.7.11 includes it too new for MC
    }
    compile "com.github.ZeroMemes:Alpine:1.7"
    compile group: 'net.jodah', name: 'typetools', version: '0.6.2'
    compile group: 'org.yaml', name: 'snakeyaml', version: '1.26'
    compile(group: 'org.reflections', name: 'reflections', version: '0.9.12') {
        exclude group: 'com.google.guava', module: 'guava'
    }
    compile 'club.minnced:java-discord-rpc:2.0.2'
    compile 'com.github.MrPowerGamerBR:TemmieWebhook:-SNAPSHOT'
    compile 'com.github.kevinsawicki:http-request:http-request-6.0'
    compile 'com.github.cabaletta:baritone:1.2.14'
    compile 'cabaletta:baritone-api:1.2'
    compile group: "net.shadowfacts", name: "Forgelin", version: "1.8.4"
    compile group: "org.jetbrains.kotlin", name: "kotlin-stdlib", version: kotlin_version
    compile group: "org.jetbrains.kotlin", name: "kotlin-stdlib-jdk7", version: kotlin_version
    compile group: "org.jetbrains.kotlin", name: "kotlin-stdlib-jdk8", version: kotlin_version
    compile group: "org.jetbrains.kotlin", name: "kotlin-reflect", version: kotlin_version
    compile group: "org.jetbrains", name: "annotations", version: annotations_version
    compile group: "org.jetbrains.kotlinx", name: "kotlinx-coroutines-core", version: coroutines_version
    compile group: "org.jetbrains.kotlinx", name: "kotlinx-coroutines-jdk8", version: coroutines_version
}

processResources {
    // this will ensure that this task is redone when the versions change.
    inputs.property 'version', project.version
    inputs.property 'mcversion', project.minecraft.version

    // replace stuff in mcmod.info, nothing else
    from(sourceSets.main.resources.srcDirs) {
        include 'mcmod.info'

        // replace version and mcversion
        expand 'version': project.version, 'mcversion': project.minecraft.version
    }

    // copy everything else, thats not the mcmod.info
    from(sourceSets.main.resources.srcDirs) {
        exclude 'mcmod.info'
    }

    // move _at.cfg into META-INF
    rename '(.+_at.cfg)', 'META-INF/$1'
}

shadowJar {
    dependencies {
        include(dependency('org.spongepowered:mixin'))
        include(dependency('com.github.ZeroMemes:Alpine'))
        include(dependency('club.minnced:java-discord-rpc'))
        include(dependency('net.jodah:typetools'))
        include(dependency('org.yaml:snakeyaml'))
        include(dependency('org.reflections:reflections'))
        include(dependency('org.javassist:javassist'))
        include(dependency('com.github.MrPowerGamerBR:TemmieWebhook'))
        include(dependency('com.github.kevinsawicki:http-request'))
        include(dependency('cabaletta:baritone-api'))
        include(dependency("org.jetbrains.kotlin:kotlin-stdlib:${kotlin_version}"))
        include(dependency("org.jetbrains.kotlin:kotlin-stdlib-jdk7:${kotlin_version}"))
        include(dependency("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlin_version}"))
        include(dependency("org.jetbrains.kotlin:kotlin-reflect:${kotlin_version}"))
        include(dependency("org.jetbrains:annotations:${annotations_version}"))
        include(dependency("org.jetbrains.kotlinx:kotlinx-coroutines-core:${coroutines_version}"))
        include(dependency("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:${coroutines_version}"))
        include(dependency('net.shadowfacts:Forgelin'))
    }
    exclude 'dummyThing' // can someone explain why this is here
    classifier = 'release'
}

mixin {
    defaultObfuscationEnv searge
    add sourceSets.main, 'mixins.kami.refmap.json'
}

reobf {
    shadowJar {
        mappingType = 'SEARGE'
        classpath = sourceSets.main.compileClasspath
    }
}

// Don't put baritone mixin here please c:
jar {
    manifest {
        attributes(
                'MixinConfigs': 'mixins.kami.json',
                'tweakClass': 'org.spongepowered.asm.launch.MixinTweaker',
                'TweakOrder': 0,
                'FMLCorePluginContainsFMLMod': 'true',
                'FMLCorePlugin': 'me.zeroeightsix.kami.mixin.MixinLoaderForge',
                'ForceLoadAsMod': 'true',
                'FMLAT': 'kami_at.cfg'
        )
    }
}

build.dependsOn(shadowJar)

Body:
Please try this. Should fix your problem.

In this case gradle will try to use a relative path for a local jar dependency.

Read those documentaries for more information

dependencies {
    implementation files('/Users/macbook/Desktop/baritone-master/dist/baritone-api-1.2.14.jar')
}

Additionally you can add all jars in X directory.

dependencies {
    compile fileTree(dir: 'yourDirection', include: ['*.jar'])
}


答:
As far as I understand, you want to count distinct dates for is_valid = 1 for a user.
You can use window function count with distinct parameter for date.

```<code>select
    acc_num, user_id, date, is_valid,
    count(distinct case when is_valid then date end) over (partition by acc_num, user_id, is_valid)
from FunkyUsers
</code>```

I'm told it's not possible to use distinct in window functions in Redshift.
So, you can use this query:

```<code>with
counts as
(
    SELECT acc_num, user_id, is_valid, COUNT(DISTINCT CASE WHEN is_valid THEN date END) as count
    FROM FunkyUsers
    GROUP BY acc_num, user_id, is_valid
)
SELECT f.*, c.count
FROM FunkyUsers f
LEFT JOIN counts c
    ON f.acc_num = c.acc_num
    AND f.user_id = c.user_id
    AND f.is_valid = c.is_valid
</code>```

Title: SQL Windowing Aggregation and Counts

Body:
I am using Redshift/Postgres DB. Consider the following table:

    +---------------------------------------+
    |              FunkyUsers               |
    +-------+---------+----------+----------+
    |acc_num| user_id |   date   | is_valid |
    +-------+---------+----------+----------+
    |   a1  |    u1   | 20200201 |    true  |
    |   a1  |    u1   | 20200201 |    true  |
    |   a1  |    u1   | 20200311 |    true  |
    |   a1  |    u2   | 20200201 |   false  |
    |   a1  |    u2   | 20200201 |   false  |
    |   a1  |    u2   | 20200201 |   false  |
    |   a1  |    u3   | 20111201 |    true  |
    |   a1  |    u3   | 20111201 |    true  |
    |   a1  |    u3   | 20111201 |    true  |
    +-------+---------+----------+----------+

I like to have the following output:

    +--------------------------------------------------+
    |                  FunkyUsers                      |
    +-------+---------+----------+----------+----------+
    |acc_num| user_id |   date   | is_valid |  count   |
    +-------+---------+----------+----------+----------+
    |   a1  |    u1   | 20200201 |    true  |    2     |
    |   a1  |    u1   | 20200201 |    true  |    2     |
    +-------+---------+----------+----------+----------+
    |   a1  |    u1   | 20200311 |    true  |    2     |
    +-------+---------+----------+----------+----------+
    |   a1  |    u2   | 20200201 |   false  |    0     |
    |   a1  |    u2   | 20200201 |   false  |    0     |
    |   a1  |    u2   | 20200201 |   false  |    0     |
    +-------+---------+----------+----------+----------+
    |   a1  |    u2   | 20111201 |    true  |    1     |
    |   a1  |    u2   | 20111201 |    true  |    1     |
    |   a1  |    u2   | 20111201 |    true  |    1     |
    +-------+---------+----------+----------+----------+

Description:

Please note the partition acc_num, user_id

Please note the subpartition within the above partition which is the date

When is_valid is true for a (partition, subpartition) increment the count for that (partition)

Finally the is_valid will have the same value for each row within the same (partition, subpartition)

Body:
As far as I understand, you want to count distinct dates for is_valid = 1 for a user.
You can use window function count with distinct parameter for date.

select
    acc_num, user_id, date, is_valid,
    count(distinct case when is_valid then date end) over (partition by acc_num, user_id, is_valid)
from FunkyUsers

I'm told it's not possible to use distinct in window functions in Redshift.
So, you can use this query:

with
counts as
(
    SELECT acc_num, user_id, is_valid, COUNT(DISTINCT CASE WHEN is_valid THEN date END) as count
    FROM FunkyUsers
    GROUP BY acc_num, user_id, is_valid
)
SELECT f.*, c.count
FROM FunkyUsers f
LEFT JOIN counts c
    ON f.acc_num = c.acc_num
    AND f.user_id = c.user_id
    AND f.is_valid = c.is_valid


问:
Jquery Each Problem
So the server is giving me a block of html within a hidden input. I need to take this block (which contains multiple divs) and move those divs, but with some logic.

My approach is to take the value of the hidden input (html block) and append it into a newly created hidden div:

```<code>  var history = $("input[name=history]").val();
  $("#global_wrapper").after("<div id='history_temp' style='display:none;'></div>");
  $("#history_temp").html(history);
</code>```

Here is an example of what the HTML block looks like:

```<code><div class="off 1"></div>
<div class="off 1"></div>
<div class="off 2"></div>
<div class="off 3"></div>
</code>```

The .off will always be there and the number class will range from 1-9

Based on the number class, I need to move each of these divs into an existing html block that looks like this:

```<code><div class="on 1"></div>
<div class="on 2"></div>
<div class="on 3"></div>
</code>```

The logic is that each .off div needs to be appended after the .on div with the same number class so that the end result would look like this:

```<code><div class="on 1"></div>
<div class="off 1"></div>
<div class="off 1"></div>
<div class="on 2"></div>
<div class="off 2"></div>
<div class="on 3"></div>
<div class="off 3"></div>
</code>```

My attempt was to run an each function for each .off div and then set up an if this.hasClass for each number div, but it was duplicating the .off divs and there were like 12 .off divs when there should have been just 3. Here is my code:

```<code>   $("#history_temp .off").each(function(){
    if ($(this).hasClass("1")) {
      $(this).clone().insertAfter(".on.1");
    }
    else if ($(this).hasClass("2")) {
      $(this).clone().insertAfter(".on.2");
    }
    else if ($(this).hasClass("3")) {
      $(this).clone().insertAfter(".on.3");
    }
    else if ($(this).hasClass("4")) {
      $(this).clone().insertAfter(".on.4");
    }
    else if ($(this).hasClass("5")) {
      $(this).clone().insertAfter(".on.5");
    }
    else if ($(this).hasClass("6")) {
      $(this).clone().insertAfter(".on.6");
    }
    else if ($(this).hasClass("7")) {
      $(this).clone().insertAfter(".on.7");
    }
    else if ($(this).hasClass("8")) {
      $(this).clone().insertAfter(".on.8");
    }
    else if ($(this).hasClass("9")) {
      $(this).clone().insertAfter(".on.9");
    }
    else {
      return false;
    }
  });
</code>```

Could anyone point me in the right direction? I'm curious as to what the most efficient solution would be.

Thanks,
Brian

EDIT: Fixed an error in my example code (was missing the "." before each on class)

答:
I like Felix Klings answer better but Ill post mine as well just because I finished it. Mine just assumes you have classes named 1-9, his is more encompassing if you happen to go beyond 9, and is more optimized.

Live Demo

```<code>   $("#history_temp .off").each(function(){
       for(var i=1; i < 10; i++){
             if ($(this).hasClass(i)) {
               $(this).clone().insertAfter(".on." + i);
             }
       }
  });
</code>```

Title: Jquery Each Problem

Body:
So the server is giving me a block of html within a hidden input. I need to take this block (which contains multiple divs) and move those divs, but with some logic.

My approach is to take the value of the hidden input (html block) and append it into a newly created hidden div:

  var history = $("input[name=history]").val();
  $("#global_wrapper").after("

");
  $("#history_temp").html(history);

Here is an example of what the HTML block looks like:

The .off will always be there and the number class will range from 1-9

Based on the number class, I need to move each of these divs into an existing html block that looks like this:

The logic is that each .off div needs to be appended after the .on div with the same number class so that the end result would look like this:

My attempt was to run an each function for each .off div and then set up an if this.hasClass for each number div, but it was duplicating the .off divs and there were like 12 .off divs when there should have been just 3. Here is my code:

   $("#history_temp .off").each(function(){
    if ($(this).hasClass("1")) {
      $(this).clone().insertAfter(".on.1");
    }
    else if ($(this).hasClass("2")) {
      $(this).clone().insertAfter(".on.2");
    }
    else if ($(this).hasClass("3")) {
      $(this).clone().insertAfter(".on.3");
    }
    else if ($(this).hasClass("4")) {
      $(this).clone().insertAfter(".on.4");
    }
    else if ($(this).hasClass("5")) {
      $(this).clone().insertAfter(".on.5");
    }
    else if ($(this).hasClass("6")) {
      $(this).clone().insertAfter(".on.6");
    }
    else if ($(this).hasClass("7")) {
      $(this).clone().insertAfter(".on.7");
    }
    else if ($(this).hasClass("8")) {
      $(this).clone().insertAfter(".on.8");
    }
    else if ($(this).hasClass("9")) {
      $(this).clone().insertAfter(".on.9");
    }
    else {
      return false;
    }
  });

Could anyone point me in the right direction? I'm curious as to what the most efficient solution would be.

Thanks,
Brian

EDIT: Fixed an error in my example code (was missing the "." before each on class)

Body:
I like Felix Klings answer better but Ill post mine as well just because I finished it. Mine just assumes you have classes named 1-9, his is more encompassing if you happen to go beyond 9, and is more optimized.

Live Demo

   $("#history_temp .off").each(function(){
       for(var i=1; i < 10; i++){
             if ($(this).hasClass(i)) {
               $(this).clone().insertAfter(".on." + i);
             }
       }
  });


问:
Browsing a db file
I create a button on click of that button a perticular location will open and I have to select the db file from that location.
Like we use to do in the data dictionary if we want to connect to the database we used to click on the browse button after that we select the db file from the location and the database will connect. I need to create a utiliy like data dictionary's connect db option. Is there any command for it?</p>

答:
Why not just use the DataDictionary?

Otherwise:
1. First you need to connect to the DB. Check the CONNECT method.
2. To look at tables and fields in the database you can used "Virtual System Tables".

Just a short snippet to get you started:

```<code>FOR EACH _file NO-LOCK:

    IF _file._file-name BEGINS "_" THEN NEXT.

    DISPLAY _file._file-name.

    FOR EACH _field OF _file NO-LOCK :

        DISPLAY _field._field-name.

    END.

END.
</code>```

Title: Browsing a db file

Body:
Why not just use the DataDictionary?

Otherwise:
1. First you need to connect to the DB. Check the CONNECT method.
2. To look at tables and fields in the database you can used "Virtual System Tables".

Just a short snippet to get you started:

FOR EACH _file NO-LOCK:

    IF _file._file-name BEGINS "_" THEN NEXT.

    DISPLAY _file._file-name.

    FOR EACH _field OF _file NO-LOCK :

        DISPLAY _field._field-name.

    END.

END.


问:
Is calling a function considered a context switching?
When I call a function as below

```<code>void main(void){
    Function();
}
</code>```

Is it considered context switching because I save registers before go to the function ?

答:
Before we ask ourselves whether we consider this "context switch", we should clear up what it means, or rather what it can mean.

When we are talking about the OS kernel and processes, we can "switch" between multiple things:

Privilege levels/Rings/Modes

CPU Register Set

Virtual Memory Areas

Often, not just one of these happens alone. A mode switch is something that is rather frequent, supervisor calls / exceptions or hardware interrupts (e.g. a timer for scheduling or an external device) necessarily trigger these. In almost every scenario we need to acquire higher privileges to actually "do something".

Storing all of the CPUs registers is needed when we have some kind of asynchronous interruption of the execution. This is not necessarily needed for supervisor calls, as there we can define a calling-convention between the caller and the callee, which registers who is responsible to backup before executing the instruction1. This is simply not possible with hardware interrupts, as we do not know when they will trigger: How should a process be able to foresee that it will be interrupted in the next t nanoseconds and has to backup all used registers?

A switch between virtual memory areas is needed when we e.g. switch between processes (every process has their own address space) or between a process and the kernel address space (and so does the kernel). However, it's often not needed for supervisor calls as these are usually mapped into the processes address space and thus only execute with higher privilege (kernel mode) without "leaving the process" (processes' address space).2

While switches between privilege levels are rather cheap (performance wise), switching out the complete CPU register set is already quite expensive. However, unloading the complete page table, flushing the TLB etc. is the most expensive and we try to keep this down as much as possible. This is also a reason why threads are far more performant (in general) than processes: Switching between them only needs a switch between CPU registers (and, depending on the implementation, a short mode switch) but not a switch between address spaces!

When we read about "context switch" in literature, it's unfortunately not always clear what of these three, or which combination, is actually referred to as "switching the context". From what I can gather, the term comes from a very simplified machine model that has no distinction between interrupts, exceptions / supervisor calls, nor between switching CPU registers or address spaces. In this model we only see "the kernel [mode/space/...]" and "the user [mode/space/...]" and any switch between these is considered a "context switch".

Fortunately, your posted scenario does not fit into any of these switches as it is a synchronous, unprivileged, function call within the same address space, thus not needing any switch but a simple calling convention that only saves those registers that need saving suffices.

1 But this might have security implications, as correctly pointed out by @BenVoigt.  This is no issue for calls like gettimeofday() (cf. this LWN.net article), but in other cases this might result into spilling confidential data to the user process.

2 Some microkernel designs dispatch a process which actually handles the supervisor call implementation, thus making a switch to this processes address space necessary.

OwnerDisplayName: Amr Tarek

Body:
When I call a function as below

void main(void){
    Function();
}

Is it considered context switching because I save registers before go to the function ?


问:
Can I use my Service Mesh for Event-Driven Messaging?
Since Service Meshes like Istio and Linkerd focuses on inter-service communication, instead of using Kafka for Event Driven Messaging, can I extend service mesh to achieve Event Driven Messaging?

Nathan Aw (Singapore)

答:
Event driven messaging is possible with Istio (and I guess with Linkerd too). Basically, the service proxies will intercept events traffic like any other TCP traffic[1] and forward them to the services, and that still works with Kafka in the middle.

However, as you put it, service meshes are focused on service-to-service communication so you might not be able to regulate traffic between a producer and a consumer as easily as with HTTP communication, as this communication passes through a message broker. So, some features of service mesh perhaps won't make so much sense, like traffic shifting. While other features continue to be relevant, such as having a consistent observability or security.

There's an interesting blog post about scaling Istio + Kafka here, which might give you some ideas: https://itnext.io/scalable-microservice-demo-k8s-istio-kafka-344a2610eba3

[1]: "Like any other TCP traffic" might not entirely be true if you use Envoy's Kafka protocol filter, which might add new capabilities in dealing with kafka messages: https://www.envoyproxy.io/docs/envoy/latest/configuration/listeners/network_filters/kafka_broker_filter (e.g. more telemetry). But that's not required to just make it work.


问:
Wish to observe stored procedures that exist on multiple database and across multiple servers
Having an issue on MS SQL 2005 Enterprise multiple servers where I want to get a collection of meta data across multiple servers and multiple databases.  I saw on Stack Overflow a good example on using the magical sp_MSforeachdb that I altered a little bit below.  Basically a MS stored procedure is being ran dynamically and it's looking for anytime a database (?) is like a name like 'Case(fourspaces)'.  This is great and it gives me what I want but for only a single server.  I want to do this for more, is it possible SQL gurus?

Example thus far:

```<code>SET NOCOUNT ON
DECLARE @AllTables table (CompleteTableName varchar(256))
INSERT INTO @AllTables (CompleteTableName)
    EXEC sp_msforeachdb 'select distinct @@SERVERNAME+''.''+ ''?'' + ''.'' + p.name from [?].sys.procedures p (nolock) where ''?'' like ''Case____'''
SELECT * FROM @AllTables ORDER BY 1
</code>```

Is there a way though to do this in SQL, Linq, or ADO.NET to perform this clever built in stored procedure that inserts into a table variable to do this multiple times across servers BUT......  Put that in one set.  As far as I know you CANNOT switch servers in a single session in SQL Management Studio but I would love to be proved wrong on that one.

EG: I have a production environment with 8 Servers, each of those servers has many databases.  I could run this multiple times but I was hoping that if the servers were linked already I could do this from the sys views somehow.  However I am on an environment using SQL 2005 and got MS's download for the sys views and it looks like the sys.servers is on an island unto itself where the SERVERID does not seem to join to anything else.

I would be willing to use an ADO.NET reader or LINQ in a C# environment and possibly call the above TSQL code multiple times but ......  Is there a more efficient way to get the info directly in TSQL IF the servers are LINKED SERVERS?  Just curious.

The overall purpose of this operation is for deployment purposes to see how many procedures exist across all servers and databases.  Now we do have SQL compare from Redgate but I am unaware if it can script procs that don't exist to exist the same as set A.  Even if it could I would like to try to make something on my own if feasible.

Any help is much appreciated and if you need further clarification please ask.

答:
I figured it out, once you set up linked servers you can merely extend the linked server name to the left of the object to qualify it more distinctly.

EG instead of sp_msforeachdb I can do (Servername).MASTER..sp_msforeachdb.  I can then iterate through my servers if they are LINKED(they are in my case) from the sys.servers table.

I did some things that would slow things down with my left join and that I store everything at once and then examine with a 'like' statement instead of an explicit qualifier.  But overall I think this solution will provide an end user with flexibility to not know the exact name of an object to hunt for.  I also like that I can now use this with SSIS, SSRS and ADO.NET as the procedure can do the hunting iteration for me and I do not have to do something in an apps memory but on the SQL server's.  I'm sure others may have better ideas but I did not hear anything so this is mine:

Complete solution below:

```<code>Create PROC [PE].[DeployChecker]
    (
        @DB     VARCHAR(128)
    ,   @Proc   VARCHAR(128)
    )

AS
    BEGIN

    --declare variable for dynamic SQL
    DECLARE
        @SQL    VARCHAR(512)
    ,   @x      int

    -- remove temp table if it exists as it should not be prepopulated.
    IF object_ID('tempdb..#Procs') IS NOT NULL
        DROP TABLE tempdb..#Procs

    -- Create temp table to catch built in sql stored procedure
    CREATE TABLE #Procs --DECLARE @Procs table
        (
            ServerName      varchar(64)
        ,   DatabaseName    VARCHAR(128)
        ,   ObjectName      VARCHAR(256)
        )

    SET @X = 1

    -- Loops through the linked servers with matching criteria to examine how MANY there are.  Do a while loop while they exist.
    -- in our case the different servers are merely incrementing numbers so I merely do a while loop, you could be more explicit if needed.
    WHILE @X <= (SELECT count(*) FROM sys.servers WHERE name LIKE 'PCTRSQL_')
    BEGIN
        -- for some reason I can't automate the 'sp_msforeachdb' proc to take dynamic sql but I can set a variable to do it and then run it.
        SET @SQL = 'Insert Into #Procs Exec PCTRSQL' + CAST(@X AS VARCHAR(2)) + '.MASTER..sp_msforeachdb ' +
        '''select @@SERVERNAME, ''''?'''', name from [?].sys.procedures (nolock) where ''''?'''' like ''''%' + @DB + '%'''' '''

        Exec (@SQL)

        SET @X = @X + 1
    END
    ;

    -- Find distinct Server detail
    WITH s AS
        (
        SELECT Distinct
            ServerName
        ,   DatabaseName
        FROM #Procs
        )
    -- do logic search in the select statement to see if there is a proc like what is searched for
    , p AS
        (
        SELECT
            ServerName
        ,   DatabaseName
        ,   CASE WHEN ObjectName LIKE '%' + @Proc + '%' THEN ObjectName END AS ProcName
        FROM #Procs
        where  ObjectName LIKE '%' + @Proc + '%'
        )
    --  now do a left join from the distinct server cte to the lookup for the proc cte, we want to examine ALL the procs that match a critera
    --  however if nothing eixsts we wish to show a NULL value of a single row for a reference to the Servername and Database

    SELECT
        s.ServerName
    ,   s.DatabaseName
    ,   p.ProcName
    ,   CAST(CASE WHEN ProcName IS NOT NULL THEN 1 ELSE 0 END AS bit) AS ExistsInDB
    FROM s
        LEFT JOIN p ON s.ServerName = p.ServerName
            AND s.DatabaseName = p.DatabaseName
        ORDER BY DatabaseName, ServerName, ProcName

END
</code>```

Body:
Having an issue on MS SQL 2005 Enterprise multiple servers where I want to get a collection of meta data across multiple servers and multiple databases.  I saw on Stack Overflow a good example on using the magical sp_MSforeachdb that I altered a little bit below.  Basically a MS stored procedure is being ran dynamically and it's looking for anytime a database (?) is like a name like 'Case(fourspaces)'.  This is great and it gives me what I want but for only a single server.  I want to do this for more, is it possible SQL gurus?

Example thus far:

SET NOCOUNT ON
DECLARE @AllTables table (CompleteTableName varchar(256))
INSERT INTO @AllTables (CompleteTableName)
    EXEC sp_msforeachdb 'select distinct @@SERVERNAME+''.''+ ''?'' + ''.'' + p.name from [?].sys.procedures p (nolock) where ''?'' like ''Case____'''
SELECT * FROM @AllTables ORDER BY 1

Is there a way though to do this in SQL, Linq, or ADO.NET to perform this clever built in stored procedure that inserts into a table variable to do this multiple times across servers BUT......  Put that in one set.  As far as I know you CANNOT switch servers in a single session in SQL Management Studio but I would love to be proved wrong on that one.

EG: I have a production environment with 8 Servers, each of those servers has many databases.  I could run this multiple times but I was hoping that if the servers were linked already I could do this from the sys views somehow.  However I am on an environment using SQL 2005 and got MS's download for the sys views and it looks like the sys.servers is on an island unto itself where the SERVERID does not seem to join to anything else.

I would be willing to use an ADO.NET reader or LINQ in a C# environment and possibly call the above TSQL code multiple times but ......  Is there a more efficient way to get the info directly in TSQL IF the servers are LINKED SERVERS?  Just curious.

The overall purpose of this operation is for deployment purposes to see how many procedures exist across all servers and databases.  Now we do have SQL compare from Redgate but I am unaware if it can script procs that don't exist to exist the same as set A.  Even if it could I would like to try to make something on my own if feasible.

Any help is much appreciated and if you need further clarification please ask.

Body:
I figured it out, once you set up linked servers you can merely extend the linked server name to the left of the object to qualify it more distinctly.

EG instead of sp_msforeachdb I can do (Servername).MASTER..sp_msforeachdb.  I can then iterate through my servers if they are LINKED(they are in my case) from the sys.servers table.

I did some things that would slow things down with my left join and that I store everything at once and then examine with a 'like' statement instead of an explicit qualifier.  But overall I think this solution will provide an end user with flexibility to not know the exact name of an object to hunt for.  I also like that I can now use this with SSIS, SSRS and ADO.NET as the procedure can do the hunting iteration for me and I do not have to do something in an apps memory but on the SQL server's.  I'm sure others may have better ideas but I did not hear anything so this is mine:

Complete solution below:

Create PROC [PE].[DeployChecker]
    (
        @DB     VARCHAR(128)
    ,   @Proc   VARCHAR(128)
    )

AS
    BEGIN

    --declare variable for dynamic SQL
    DECLARE
        @SQL    VARCHAR(512)
    ,   @x      int

    -- remove temp table if it exists as it should not be prepopulated.
    IF object_ID('tempdb..#Procs') IS NOT NULL
        DROP TABLE tempdb..#Procs

    -- Create temp table to catch built in sql stored procedure
    CREATE TABLE #Procs --DECLARE @Procs table
        (
            ServerName      varchar(64)
        ,   DatabaseName    VARCHAR(128)
        ,   ObjectName      VARCHAR(256)
        )

    SET @X = 1

    -- Loops through the linked servers with matching criteria to examine how MANY there are.  Do a while loop while they exist.
    -- in our case the different servers are merely incrementing numbers so I merely do a while loop, you could be more explicit if needed.
    WHILE @X <= (SELECT count(*) FROM sys.servers WHERE name LIKE 'PCTRSQL_')
    BEGIN
        -- for some reason I can't automate the 'sp_msforeachdb' proc to take dynamic sql but I can set a variable to do it and then run it.
        SET @SQL = 'Insert Into #Procs Exec PCTRSQL' + CAST(@X AS VARCHAR(2)) + '.MASTER..sp_msforeachdb ' +
        '''select @@SERVERNAME, ''''?'''', name from [?].sys.procedures (nolock) where ''''?'''' like ''''%' + @DB + '%'''' '''

        Exec (@SQL)

        SET @X = @X + 1
    END
    ;

    -- Find distinct Server detail
    WITH s AS
        (
        SELECT Distinct
            ServerName
        ,   DatabaseName
        FROM #Procs
        )
    -- do logic search in the select statement to see if there is a proc like what is searched for
    , p AS
        (
        SELECT
            ServerName
        ,   DatabaseName
        ,   CASE WHEN ObjectName LIKE '%' + @Proc + '%' THEN ObjectName END AS ProcName
        FROM #Procs
        where  ObjectName LIKE '%' + @Proc + '%'
        )
    --  now do a left join from the distinct server cte to the lookup for the proc cte, we want to examine ALL the procs that match a critera
    --  however if nothing eixsts we wish to show a NULL value of a single row for a reference to the Servername and Database

    SELECT
        s.ServerName
    ,   s.DatabaseName
    ,   p.ProcName
    ,   CAST(CASE WHEN ProcName IS NOT NULL THEN 1 ELSE 0 END AS bit) AS ExistsInDB
    FROM s
        LEFT JOIN p ON s.ServerName = p.ServerName
            AND s.DatabaseName = p.DatabaseName
        ORDER BY DatabaseName, ServerName, ProcName

END


问:
Driver info: driver.version: unknown (Behat\Mink\Exception\DriverException) error with Selenium and Geckodriver
Here's the situation: I'm using Behat to run acceptance tests on Symfony. To do so, I start a Selenium instance with the Geckodriver, then I run Behat. Everything works fine on local (great!).

But when it runs on Github action, it fails. I've check the versions, I've even versioned the geckodriver and selenium.jar files to use exactly the same (despite they already exist on github action), but nothing works.

So I'm looking for any help to debug this error. Here's the commands and their results:

```<code>$ java -jar -Dwebdriver.gecko.driver=/usr/local/share/gecko_driver /usr/share/java/selenium-server-standalone.jar &

14:19:46.106 INFO [GridLauncherV3.parse] - Selenium server version: 3.141.59, revision: e82be7d358
14:19:46.369 INFO [GridLauncherV3.lambda$buildLaunchers$3] - Launching a standalone Selenium Server on port 4444
2020-05-29 14:19:46.780:INFO::main: Logging initialized @1350ms to org.seleniumhq.jetty9.util.log.StdErrLog
14:19:47.657 INFO [WebDriverServlet.<init>] - Initialising WebDriverServlet
14:19:47.758 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 4444
</code>```

```<code>./vendor/bin/behat -s acceptance

Could not open connection: Unable to create new service: GeckoDriverService
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'fv-az33', ip: '10.1.0.4', os.name: 'Linux', os.arch: 'amd64', os.version: '5.3.0-1022-azure', java.version: '1.8.0_252'
Driver info: driver.version: unknown (Behat\Mink\Exception\DriverException)
</code>```

答:
Ok, I've just solved my problem. I think this is due to two things:

First, I was not using the headless mode. I don't know to set it using Geckodriver because I'm finally using Chromedriver

Second, the github action's doc is misleading. It says 'Chrome Driver is available via CHROMEWEBDRIVER environment variable', but in fact it's only the directory which is in the env var. So the path of the driver is $CHROMEWEBDRIVER/chromedriver (same for $GECKOWEBDRIVER)

For info, here's my config of behat:

javascript_session:
  selenium2:
  browser: chrome
  capabilities:
    chrome:
      switches:
        - "--headless"
        - "--disable-gpu"
```

<p>And to run Selenium:</p>

```java -Dwebdriver.chrome.driver=$CHROMEWEBDRIVER/chromedriver -jar $SELENIUM_JAR_PATH &
```

Body:
Here's the situation: I'm using Behat to run acceptance tests on Symfony. To do so, I start a Selenium instance with the Geckodriver, then I run Behat. Everything works fine on local (great!).

But when it runs on Github action, it fails. I've check the versions, I've even versioned the geckodriver and selenium.jar files to use exactly the same (despite they already exist on github action), but nothing works.

So I'm looking for any help to debug this error. Here's the commands and their results:

$ java -jar -Dwebdriver.gecko.driver=/usr/local/share/gecko_driver /usr/share/java/selenium-server-standalone.jar &

14:19:46.106 INFO [GridLauncherV3.parse] - Selenium server version: 3.141.59, revision: e82be7d358
14:19:46.369 INFO [GridLauncherV3.lambda$buildLaunchers$3] - Launching a standalone Selenium Server on port 4444
2020-05-29 14:19:46.780:INFO::main: Logging initialized @1350ms to org.seleniumhq.jetty9.util.log.StdErrLog
14:19:47.657 INFO [WebDriverServlet.<init>] - Initialising WebDriverServlet
14:19:47.758 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 4444

./vendor/bin/behat -s acceptance

Could not open connection: Unable to create new service: GeckoDriverService
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'fv-az33', ip: '10.1.0.4', os.name: 'Linux', os.arch: 'amd64', os.version: '5.3.0-1022-azure', java.version: '1.8.0_252'
Driver info: driver.version: unknown (Behat\Mink\Exception\DriverException)

Body:
Ok, I've just solved my problem. I think this is due to two things:

First, I was not using the headless mode. I don't know to set it using Geckodriver because I'm finally using Chromedriver

Second, the github action's doc is misleading. It says 'Chrome Driver is available via CHROMEWEBDRIVER environment variable', but in fact it's only the directory which is in the env var. So the path of the driver is $CHROMEWEBDRIVER/chromedriver (same for $GECKOWEBDRIVER)

For info, here's my config of behat:

javascript_session:
  selenium2:
  browser: chrome
  capabilities:
    chrome:
      switches:
        - "--headless"
        - "--disable-gpu"

And to run Selenium:

java -Dwebdriver.chrome.driver=$CHROMEWEBDRIVER/chromedriver -jar $SELENIUM_JAR_PATH &


问:
Append text in the end of line if search pattern is found
This is my first question on this forum :).

I have a file something like:

```<code>----File--------
XI39/XM79 XI39/XM79#G XI39/XM79#S XI39/XM79#D XI39/XM79#B XI39/XM79#DN append_text!
+ search_pattern
+ w=5e-07 l=3.85e-07 sa=4.1e-07 sb=4.1e-07 ad=2.05e-13 as=2.05e-13 pd=1.82e-06

XI57/XM0@1 XI57/XM0@1#G XI57/XM0@1#S XI57/XM0@1#D XI57/XM0@1#B XI57/XM0@1#DN
+ search_pattern
+ w=1e-06 l=3.85e-07 sa=4.1e-07 sb=1.215e-06 ad=2.1e-13 as=4.1e-13 pd=1.42e-06
</code>```

I want to search for "search_pattern" and if found look at one line above and append "append_text!" in end of line if its not present.

So the output file should be:-

------------output file------

```<code>XI39/XM79 XI39/XM79#G XI39/XM79#S XI39/XM79#D XI39/XM79#B XI39/XM79#DN append_text!
+ search_pattern
+ w=5e-07 l=3.85e-07 sa=4.1e-07 sb=4.1e-07 ad=2.05e-13 as=2.05e-13 pd=1.82e-06

XI57/XM0@1 XI57/XM0@1#G XI57/XM0@1#S XI57/XM0@1#D XI57/XM0@1#B XI57/XM0@1#DN append_text!
+ search_pattern
+ w=1e-06 l=3.85e-07 sa=4.1e-07 sb=1.215e-06 ad=2.1e-13 as=4.1e-13 pd=1.42e-06
</code>```

I know perl a little so can do file operations but not good at all with pattern matching. Any pointer will be helpful.

答:
We can append the text in more ways.. Lets try this one

Push all your data into array

```<code>push(@allline, <DATA>);
</code>```

Iterate for loop

```<code>for(my $i=0; $i < $#allline; $i++)
{
</code>```

Catch up the Matched line and previous line

```<code>    my $j = $i; $j--;
</code>```

If matches found then go back to the previous line

```<code>    if($allline[$i]=~m/\+\s*search_pattern/)
    {
</code>```

Check the append_text availability

```<code>        if($allline[$j]!~m/append_text/)
        {
            $allline[$j]=~s/$/ \*\*append_text\*\*/;
        }
        elsif($allline[$j]=~m/append_text/)
        {
            $allline[$j]=~s/append_text/\*\*append_text\*\*/;
        }
    }
}
</code>```

Check your output

```<code>print join "", @allline;

__DATA__
XI39/XM79 XI39/XM79#G XI39/XM79#S XI39/XM79#D XI39/XM79#B XI39/XM79#DN append_text!
+ search_pattern
+ w=5e-07 l=3.85e-07 sa=4.1e-07 sb=4.1e-07 ad=2.05e-13 as=2.05e-13 pd=1.82e-06

XI57/XM0@1 XI57/XM0@1#G XI57/XM0@1#S XI57/XM0@1#D XI57/XM0@1#B XI57/XM0@1#DN
+ search_pattern
+ w=1e-06 l=3.85e-07 sa=4.1e-07 sb=1.215e-06 ad=2.1e-13 as=4.1e-13 pd=1.42e-06
</code>```

Output

```<code> XI39/XM79 XI39/XM79#G XI39/XM79#S XI39/XM79#D XI39/XM79#B XI39/XM79#DN \*\*append_text\*\*!
 + search_pattern
 + w=5e-07 l=3.85e-07 sa=4.1e-07 sb=4.1e-07 ad=2.05e-13 as=2.05e-13 pd=1.82e-06

 XI57/XM0@1 XI57/XM0@1#G XI57/XM0@1#S XI57/XM0@1#D XI57/XM0@1#B XI57/XM0@1#DN \*\*append_text\*\*
 + search_pattern
 + w=1e-06 l=3.85e-07 sa=4.1e-07 sb=1.215e-06 ad=2.1e-13 as=4.1e-13 pd=1.42e-06
</code>```

Body:
This is my first question on this forum :).

I have a file something like:

----File--------
XI39/XM79 XI39/XM79#G XI39/XM79#S XI39/XM79#D XI39/XM79#B XI39/XM79#DN append_text!
+ search_pattern
+ w=5e-07 l=3.85e-07 sa=4.1e-07 sb=4.1e-07 ad=2.05e-13 as=2.05e-13 pd=1.82e-06

XI57/XM0@1 XI57/XM0@1#G XI57/XM0@1#S XI57/XM0@1#D XI57/XM0@1#B XI57/XM0@1#DN
+ search_pattern
+ w=1e-06 l=3.85e-07 sa=4.1e-07 sb=1.215e-06 ad=2.1e-13 as=4.1e-13 pd=1.42e-06

I want to search for "search_pattern" and if found look at one line above and append "append_text!" in end of line if its not present.

So the output file should be:-

------------output file------

XI39/XM79 XI39/XM79#G XI39/XM79#S XI39/XM79#D XI39/XM79#B XI39/XM79#DN append_text!
+ search_pattern
+ w=5e-07 l=3.85e-07 sa=4.1e-07 sb=4.1e-07 ad=2.05e-13 as=2.05e-13 pd=1.82e-06

XI57/XM0@1 XI57/XM0@1#G XI57/XM0@1#S XI57/XM0@1#D XI57/XM0@1#B XI57/XM0@1#DN append_text!
+ search_pattern
+ w=1e-06 l=3.85e-07 sa=4.1e-07 sb=1.215e-06 ad=2.1e-13 as=4.1e-13 pd=1.42e-06

I know perl a little so can do file operations but not good at all with pattern matching. Any pointer will be helpful.

Body:
We can append the text in more ways.. Lets try this one

Push all your data into array

push(@allline, <DATA>);

Iterate for loop

for(my $i=0; $i < $#allline; $i++)
{

Catch up the Matched line and previous line

    my $j = $i; $j--;

If matches found then go back to the previous line

    if($allline[$i]=~m/\+\s*search_pattern/)
    {

Check the append_text availability

        if($allline[$j]!~m/append_text/)
        {
            $allline[$j]=~s/$/ \*\*append_text\*\*/;
        }
        elsif($allline[$j]=~m/append_text/)
        {
            $allline[$j]=~s/append_text/\*\*append_text\*\*/;
        }
    }
}

Check your output

print join "", @allline;

__DATA__
XI39/XM79 XI39/XM79#G XI39/XM79#S XI39/XM79#D XI39/XM79#B XI39/XM79#DN append_text!
+ search_pattern
+ w=5e-07 l=3.85e-07 sa=4.1e-07 sb=4.1e-07 ad=2.05e-13 as=2.05e-13 pd=1.82e-06

XI57/XM0@1 XI57/XM0@1#G XI57/XM0@1#S XI57/XM0@1#D XI57/XM0@1#B XI57/XM0@1#DN
+ search_pattern
+ w=1e-06 l=3.85e-07 sa=4.1e-07 sb=1.215e-06 ad=2.1e-13 as=4.1e-13 pd=1.42e-06

Output

 XI39/XM79 XI39/XM79#G XI39/XM79#S XI39/XM79#D XI39/XM79#B XI39/XM79#DN \*\*append_text\*\*!
 + search_pattern
 + w=5e-07 l=3.85e-07 sa=4.1e-07 sb=4.1e-07 ad=2.05e-13 as=2.05e-13 pd=1.82e-06

 XI57/XM0@1 XI57/XM0@1#G XI57/XM0@1#S XI57/XM0@1#D XI57/XM0@1#B XI57/XM0@1#DN \*\*append_text\*\*
 + search_pattern
 + w=1e-06 l=3.85e-07 sa=4.1e-07 sb=1.215e-06 ad=2.1e-13 as=4.1e-13 pd=1.42e-06


问:
Can you explain this JavaScript function for me?
```<code> function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]
</code>```

Could you guys please explain to me how this function works and when the variable "countArray" would push the elements to the array.

答:
This function will check first if the variable n < 1

If it is bigger it will run itself with n-1

If n is 0, the function will return an empty Array and will go one "layer" back to the last function countup(1)
It will now add n (1) to the countArray and return this Array to the "last" function
Now the function countup(2)has recieved the number 1 in its countArray and it will return this. [1, 2]

It will repeate this process until the 'last' / 'first' function (countup(5)) is reached and it will return the countArray with all the numbers [1, 2, 3, 4, 5]

Body:
 function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]

Could you guys please explain to me how this function works and when the variable "countArray" would push the elements to the array.


问:
Where is the Object class or java.lang imported into the scala package or Any class?
From my understanding the ultimate class in Scala is Any class. However, I thought Scala built of the Java, so would not the ultimate class be Object? I have been checking the documentation and I could be wrong but it does not show that Object is the parent class of Any nor can I see anywhere the java.lang package being imported into Scala, which should be its backbone right?

答:
java.lang.Object is not the parent of scala.Any. Consider the following relationships

```<code>implicitly[Any <:< java.lang.Object]     // error
implicitly[AnyVal <:< java.lang.Object]  // error
implicitly[AnyRef <:< java.lang.Object]  // ok
</code>```

However, say you had the following Java class

```<code>public class Foo {
    public void bar(Object o) {}
    public void zar(int o) {}
    public void qux(java.lang.Integer o) {}
}
</code>```

then all of the following would still work when called from Scala

```<code>val foo = new Foo
foo.bar(42.asInstanceOf[Int])
foo.bar(42.asInstanceOf[Any])
foo.bar(42.asInstanceOf[AnyVal])
foo.bar(42.asInstanceOf[AnyRef])
foo.zar(42) // zar takes primitive int
foo.qux(42) // qux takes java.lang.Integer
</code>```

Body:
java.lang.Object is not the parent of scala.Any. Consider the following relationships

implicitly[Any <:< java.lang.Object]     // error
implicitly[AnyVal <:< java.lang.Object]  // error
implicitly[AnyRef <:< java.lang.Object]  // ok

However, say you had the following Java class

public class Foo {
    public void bar(Object o) {}
    public void zar(int o) {}
    public void qux(java.lang.Integer o) {}
}

then all of the following would still work when called from Scala

val foo = new Foo
foo.bar(42.asInstanceOf[Int])
foo.bar(42.asInstanceOf[Any])
foo.bar(42.asInstanceOf[AnyVal])
foo.bar(42.asInstanceOf[AnyRef])
foo.zar(42) // zar takes primitive int
foo.qux(42) // qux takes java.lang.Integer


问:
Use Pipenv to build and publish a Python package
Context: I'm setting up a new Python project and decided to give PEP-517 and PEP-518 ("build systems") a whirl, instead of my usual setup.py-plus-a-bunch-of-shell-scripts configuration. My requirements are: dependency management and being able to create a Python package and publish it to PyPI. I decided to give Pipenv a chance.

Problem: I cannot find any information about how to create a Python package when using Pipenv to manage the dependencies. It appears that Pipenv doesn't provide means for that. So, does it mean that in addition to the Pipfile I still need to create a setup.py? What is the point of having the Pipfile then? Or is it possible to "snapshot" a Pipenv into a setup.py for example? If so, how do I manage other attributes (package description, author, project URL, etc.) in this case?

To avoid any confusion, my question is not to find a library or a tool, but about how to accompilsh a specific task - build and publish a Python package - in the Python project with dependency management based on Pipenv.

答:
Pipenv doesn't allow you to publish a package as you may hope. It is used for development, and for the publishing step you will still need a setup.py file. There's some good news, you can use pipenv-setup to sync your pipenv packages without any manual editing (pipenv-setup sync --dev).

An alternative to Pipenv that also allows you to publish your project is Poetry: it has a simple poetry publish command that does just that. It is also based on pyproject.toml, which is being pushed as a replacement for setup.py


问:
Gunicorn.service unable to read Python3.6 library
I am deploying a flask app on nginx+gunicorn on ubuntu server.

Gunicorn command runs the flask app properly. The following is the command

gunicorn3 --bind=unix:/tmp/gunicorn.sock --workers=4 app:app

When I try to write a service it fails with the error

```<code>gunicorn3.service - gunicorn3 daemon for /var/www/html/my_app/app.py
   Loaded: loaded (/etc/systemd/system/gunicorn3.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Wed 2020-06-03 13:26:57 IST; 6s ago
  Process: 19575 ExecStart=/usr/bin/gunicorn3 --bind=unix:/tmp/gunicorn3.sock --workers=4 app:app (code=exited, status=3)
 Main PID: 19575 (code=exited, status=3)

Jun 03 13:26:57 my-server gunicorn3[19575]:   File "/usr/lib/python3/dist-packages/gunicorn/util.py", line 377, in import_app
Jun 03 13:26:57 my-server gunicorn3[19575]:     _import_(module)
Jun 03 13:26:57 my-server gunicorn3[19575]:   File "/var/www/html/my_app/app.py", line 1, in <module>
Jun 03 13:26:57 my-server gunicorn3[19575]:     from flask import Flask, render_template, flash, request, url_for, redirect, session, flash, g, jsonify, send_file, make_response, send_from_directory
Jun 03 13:26:57 my-server gunicorn3[19575]: ModuleNotFoundError: No module named 'flask'
Jun 03 13:26:57 my-server gunicorn3[19575]: [2020-06-03 13:26:57 +0530] [19577] [INFO] Worker exiting (pid: 19577)
Jun 03 13:26:57 my-server gunicorn3[19575]: [2020-06-03 13:26:57 +0530] [19575] [INFO] Shutting down: Master
Jun 03 13:26:57 my-server gunicorn3[19575]: [2020-06-03 13:26:57 +0530] [19575] [INFO] Reason: Worker failed to boot.
Jun 03 13:26:57 my-server systemd[1]: gunicorn3.service: Main process exited, code=exited, status=3/NOTIMPLEMENTED
Jun 03 13:26:57 my-server systemd[1]: gunicorn3.service: Failed with result 'exit-code'.

</code>```

The error occurs when app runs through python2.7 instead of 3.6.

The Service file /etc/systemd/system/gunicorn3.service is

```<code>[Unit]
Description=gunicorn3 daemon for /var/www/html/my_app/app.py
After=network.target

[Service]
User=root
Group=www-data
RuntimeDirectory=gunicorn3
WorkingDirectory=/var/www/html/my_app/
ExecStart=/usr/bin/gunicorn3 --bind=unix:/tmp/gunicorn3.sock --workers=4 app:app
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID

[Install]
WantedBy=multi-user.target
</code>```

The app runs properly when I run a direct gunicorn3 command but fails when service is created

答:
Your problem seems to be that your gunicorn command is pointing to different Python versions.

The app runs properly when I run a direct gunicorn3 command but fails
  when service is created

Try:

```<code>ExecStart=/usr/bin/env gunicorn3 --bind=unix:/tmp/gunicorn3.sock --workers=4 app:app
</code>```

More clean solution.

```<code>python3 -m venv venv
source venv/bin/activate
python -m pip install -r requirements.txt

ExecStart=/path/to/your/venv/bin/gunicorn --bind=unix:/tmp/gunicorn3.sock --workers=4 app:app
</code>```

Body:
I am deploying a flask app on nginx+gunicorn on ubuntu server.

Gunicorn command runs the flask app properly. The following is the command

gunicorn3 --bind=unix:/tmp/gunicorn.sock --workers=4 app:app

When I try to write a service it fails with the error

gunicorn3.service - gunicorn3 daemon for /var/www/html/my_app/app.py
   Loaded: loaded (/etc/systemd/system/gunicorn3.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Wed 2020-06-03 13:26:57 IST; 6s ago
  Process: 19575 ExecStart=/usr/bin/gunicorn3 --bind=unix:/tmp/gunicorn3.sock --workers=4 app:app (code=exited, status=3)
 Main PID: 19575 (code=exited, status=3)

Jun 03 13:26:57 my-server gunicorn3[19575]:   File "/usr/lib/python3/dist-packages/gunicorn/util.py", line 377, in import_app
Jun 03 13:26:57 my-server gunicorn3[19575]:     _import_(module)
Jun 03 13:26:57 my-server gunicorn3[19575]:   File "/var/www/html/my_app/app.py", line 1, in <module>
Jun 03 13:26:57 my-server gunicorn3[19575]:     from flask import Flask, render_template, flash, request, url_for, redirect, session, flash, g, jsonify, send_file, make_response, send_from_directory
Jun 03 13:26:57 my-server gunicorn3[19575]: ModuleNotFoundError: No module named 'flask'
Jun 03 13:26:57 my-server gunicorn3[19575]: [2020-06-03 13:26:57 +0530] [19577] [INFO] Worker exiting (pid: 19577)
Jun 03 13:26:57 my-server gunicorn3[19575]: [2020-06-03 13:26:57 +0530] [19575] [INFO] Shutting down: Master
Jun 03 13:26:57 my-server gunicorn3[19575]: [2020-06-03 13:26:57 +0530] [19575] [INFO] Reason: Worker failed to boot.
Jun 03 13:26:57 my-server systemd[1]: gunicorn3.service: Main process exited, code=exited, status=3/NOTIMPLEMENTED
Jun 03 13:26:57 my-server systemd[1]: gunicorn3.service: Failed with result 'exit-code'.

The error occurs when app runs through python2.7 instead of 3.6.

The Service file /etc/systemd/system/gunicorn3.service is

[Unit]
Description=gunicorn3 daemon for /var/www/html/my_app/app.py
After=network.target

[Service]
User=root
Group=www-data
RuntimeDirectory=gunicorn3
WorkingDirectory=/var/www/html/my_app/
ExecStart=/usr/bin/gunicorn3 --bind=unix:/tmp/gunicorn3.sock --workers=4 app:app
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID

[Install]
WantedBy=multi-user.target

The app runs properly when I run a direct gunicorn3 command but fails when service is created

Body:
Your problem seems to be that your gunicorn command is pointing to different Python versions.

The app runs properly when I run a direct gunicorn3 command but fails
  when service is created

Try:

ExecStart=/usr/bin/env gunicorn3 --bind=unix:/tmp/gunicorn3.sock --workers=4 app:app

More clean solution.

python3 -m venv venv
source venv/bin/activate
python -m pip install -r requirements.txt

ExecStart=/path/to/your/venv/bin/gunicorn --bind=unix:/tmp/gunicorn3.sock --workers=4 app:app


问:
googlecloudsdk.core.exceptions.RequiresAdminRightsError: You cannot perform this action because you do not have permission
I am trying to install google-cloud-sdk in ubuntu-18.04. I am following offical docs given here. When I run ./google-cloud-sdk/install.sh I get following error:-

```<code>Welcome to the Google Cloud SDK!

To help improve the quality of this product, we collect anonymized usage data
and anonymized stacktraces when crashes are encountered; additional information
is available at <https://cloud.google.com/sdk/usage-statistics>. This data is
handled in accordance with our privacy policy
<https://policies.google.com/privacy>. You may choose to opt in this
collection now (by choosing 'Y' at the below prompt), or at any time in the
future by running the following command:

    gcloud config set disable_usage_reporting false

Do you want to help improve the Google Cloud SDK (y/N)?  N

Traceback (most recent call last):
  File "/home/vineet/./google-cloud-sdk/bin/bootstrapping/install.py", line 225, in <module>
    main()
  File "/home/vineet/./google-cloud-sdk/bin/bootstrapping/install.py", line 200, in main
    Prompts(pargs.usage_reporting)
  File "/home/vineet/./google-cloud-sdk/bin/bootstrapping/install.py", line 123, in Prompts
    scope=properties.Scope.INSTALLATION)
  File "/home/vineet/google-cloud-sdk/lib/googlecloudsdk/core/properties.py", line 2406, in PersistProperty
    config.EnsureSDKWriteAccess()
  File "/home/vineet/google-cloud-sdk/lib/googlecloudsdk/core/config.py", line 198, in EnsureSDKWriteAccess
    raise exceptions.RequiresAdminRightsError(sdk_root)
googlecloudsdk.core.exceptions.RequiresAdminRightsError: You cannot perform this action because you do not have permission to modify the Google Cloud SDK installation directory [/home/vineet/google-cloud-sdk].

Re-run the command with sudo: sudo /home/vineet/google-cloud-sdk/bin/gcloud ...

</code>```

I tried to search it on stackoverflow and github-issues but in vain.

Would appreciate any hint to solve it.

答:
As stated on the error message.

Re-run the command with sudo: sudo /home/vineet/google-cloud-sdk/bin/gcloud ...

The install.sh script should be run using sudo.

There are also other alternatives to install the Google Cloud SDK in Ubuntu 18.04 just as installing the package with apt-get as explained on the documentation.

Body:
I am trying to install google-cloud-sdk in ubuntu-18.04. I am following offical docs given here. When I run ./google-cloud-sdk/install.sh I get following error:-

Welcome to the Google Cloud SDK!

To help improve the quality of this product, we collect anonymized usage data
and anonymized stacktraces when crashes are encountered; additional information
is available at <https://cloud.google.com/sdk/usage-statistics>. This data is
handled in accordance with our privacy policy
<https://policies.google.com/privacy>. You may choose to opt in this
collection now (by choosing 'Y' at the below prompt), or at any time in the
future by running the following command:

    gcloud config set disable_usage_reporting false

Do you want to help improve the Google Cloud SDK (y/N)?  N

Traceback (most recent call last):
  File "/home/vineet/./google-cloud-sdk/bin/bootstrapping/install.py", line 225, in <module>
    main()
  File "/home/vineet/./google-cloud-sdk/bin/bootstrapping/install.py", line 200, in main
    Prompts(pargs.usage_reporting)
  File "/home/vineet/./google-cloud-sdk/bin/bootstrapping/install.py", line 123, in Prompts
    scope=properties.Scope.INSTALLATION)
  File "/home/vineet/google-cloud-sdk/lib/googlecloudsdk/core/properties.py", line 2406, in PersistProperty
    config.EnsureSDKWriteAccess()
  File "/home/vineet/google-cloud-sdk/lib/googlecloudsdk/core/config.py", line 198, in EnsureSDKWriteAccess
    raise exceptions.RequiresAdminRightsError(sdk_root)
googlecloudsdk.core.exceptions.RequiresAdminRightsError: You cannot perform this action because you do not have permission to modify the Google Cloud SDK installation directory [/home/vineet/google-cloud-sdk].

Re-run the command with sudo: sudo /home/vineet/google-cloud-sdk/bin/gcloud ...

I tried to search it on stackoverflow and github-issues but in vain.

Would appreciate any hint to solve it.