问:
Generate all possibilities for a string where some letters can be numbers, in Python
Say I have a string like this.

```<code>sentence = "i like to go fishing on saturday"
</code>```

And some letters can be numbers, in the tradition of '1337' speak i.e. h3110, h0w 4r3 y0u?

However I want to get all possible combinations where some letters are converted to numbers, but others are not. Some examples with the above sentence.

```<code>"i 1ik3 70 g0 fishing 0n s4turd4y"
"i lik3 70 g0 fishing 0n s4turd4y"
"i like 70 g0 fishing 0n s4turd4y"
"i 1ike 70 g0 fishing 0n s4turd4y"
etc.
</code>```

How could I write in Python a dictionary of substitutions for each letter and then a way to generate all possible combinations for the sentence?

答:
You can build the dictionary from pairs and then use itertools.product for  all combinations:

```<code>import itertools

# 1: write down pairs
pairs = ['a4', 't7', 'e3'] # etc.
# 2: make dict; it will be convenient to store both letter and substitute as value
pd = {p[0]:p for p in pairs}
# 3: replace all eligible letters with the appropriate pair and
#    use itertools.product
[''.join(c) for c in itertools.product(*(pd.get(i, i) for i in 'i like to go fishing on saturday'))]
# ['i like to go fishing on saturday', 'i like to go fishing on saturd4y',
#  'i like to go fishing on sa7urday', 'i like to go fishing on sa7urd4y',
#  'i like to go fishing on s4turday', 'i like to go fishing on s4turd4y',
#  'i like to go fishing on s47urday', 'i like to go fishing on s47urd4y',
#  'i like 7o go fishing on saturday', 'i like 7o go fishing on saturd4y',
#  'i like 7o go fishing on sa7urday', 'i like 7o go fishing on
#  ...
</code>```

Body:
Say I have a string like this.

sentence = "i like to go fishing on saturday"

And some letters can be numbers, in the tradition of '1337' speak i.e. h3110, h0w 4r3 y0u?

However I want to get all possible combinations where some letters are converted to numbers, but others are not. Some examples with the above sentence.

"i 1ik3 70 g0 fishing 0n s4turd4y"
"i lik3 70 g0 fishing 0n s4turd4y"
"i like 70 g0 fishing 0n s4turd4y"
"i 1ike 70 g0 fishing 0n s4turd4y"
etc.

How could I write in Python a dictionary of substitutions for each letter and then a way to generate all possible combinations for the sentence?

Body:
You can build the dictionary from pairs and then use itertools.product for  all combinations:

import itertools

# 1: write down pairs
pairs = ['a4', 't7', 'e3'] # etc.
# 2: make dict; it will be convenient to store both letter and substitute as value
pd = {p[0]:p for p in pairs}
# 3: replace all eligible letters with the appropriate pair and
#    use itertools.product
[''.join(c) for c in itertools.product(*(pd.get(i, i) for i in 'i like to go fishing on saturday'))]
# ['i like to go fishing on saturday', 'i like to go fishing on saturd4y',
#  'i like to go fishing on sa7urday', 'i like to go fishing on sa7urd4y',
#  'i like to go fishing on s4turday', 'i like to go fishing on s4turd4y',
#  'i like to go fishing on s47urday', 'i like to go fishing on s47urd4y',
#  'i like 7o go fishing on saturday', 'i like 7o go fishing on saturd4y',
#  'i like 7o go fishing on sa7urday', 'i like 7o go fishing on
#  ...


来源: stackexchange

问:
What should my nginx.conf look like for serving static content
I have the following content in my nginx.conf and everything else is as is

```<code>server {
    listen       8081;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    #location / {
        #root   html;
        #index  index.html index.htm;
    #}

    location = /console {
        proxy_pass http://localhost:7001/main/console;
        proxy_set_header        Host             $host;
        proxy_set_header        X-Real-IP        $remote_addr;
        proxy_set_header        X-Forwarded-For  $proxy_add_x_forwarded_for;
        auth_basic "Admin Area";
        auth_basic_user_file /etc/apache2/.htpasswd;
    }
}
</code>```

Now when I launch http://localhost:8081/console it successfully launches the webpage and even asks me for password.

But there are some static content in this location /main/resources/org/nett/main/images/jquery-3.1.1.min.js

When I click on this it throws 404. What should be in my nginx.conf to serve the static content inside /main/resources/org/nett/main/images/ folder?

答:
You'll note that the location of the static content, /main/resources..., doesn't match any of your locations.  .  resources is not under /main/console, and therefore there's no way to access it under your existing proxy-pass location.

Reconsider whether you need to change the path of your proxy.  It can be done, but requires additional configuration.  If you merely redirect / to 7001:/, then when the data at /main/console refers to /main/resources, that will also have a valid proxy path through nginx.

If your definition of 'working' means the /console maps to 7001/main/console, you'll have to expand upon that definition to address also how you want to map requests under /main/<anythingelse>, more of which may have yet to be uncovered. You'll also have to handle rewriting the references to itself the application sends back ( if, for example, more is requested from /main/console, it will have the same problem as stuff under /main/resources, because it, too, doesn't match /console.  URL rewrites at the proxy should only be undertaken with a decent grasp of regular expressions and http, and only with a sincere and practiced willingness to RTFM.  its complicated.

By the by, if you're attempting to add basic auth to whatever's on 7001, make sure to also encrypt your connection (HTTPS), otherwise your credentials are plaintext on the network (http://mark-kirby.co.uk/2013/how-to-authenticate-apis-http-basic-vs-http-digest/).

ContentLicense: CC BY-SA 3.0

Body:
I have the following content in my nginx.conf and everything else is as is

server {
    listen       8081;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    #location / {
        #root   html;
        #index  index.html index.htm;
    #}

    location = /console {
        proxy_pass http://localhost:7001/main/console;
        proxy_set_header        Host             $host;
        proxy_set_header        X-Real-IP        $remote_addr;
        proxy_set_header        X-Forwarded-For  $proxy_add_x_forwarded_for;
        auth_basic "Admin Area";
        auth_basic_user_file /etc/apache2/.htpasswd;
    }
}

Now when I launch http://localhost:8081/console it successfully launches the webpage and even asks me for password.

But there are some static content in this location /main/resources/org/nett/main/images/jquery-3.1.1.min.js

When I click on this it throws 404. What should be in my nginx.conf to serve the static content inside /main/resources/org/nett/main/images/ folder?


问:
Creating a program that tests for palindrome without building the reversal (Java)
I am trying to create a Java program for my AP Computer Science class that asks the user for a string and tests whether or not the string is a palindrome or not. The teacher specifically told us to not do the project by building the reversal of the string and testing it to see if it matches. I know how to do it while building the reversal but I can't think of another way to do it. </p>

```<code>import java.util.*;

public class mondayassignment
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a String: ");
        String s = scan.nextLine();

                while(s.indexOf(" ") >= 0)
                       {
                            s = s.substring(0, s.indexOf(" ")) +
s.substring(s.indexOf(" ") + 1);
                       }
                System.out.println("Spaces Removed:");
        System.out.println(s);
                String reverse="";
        for(int pos = 0; pos < s.length(); pos++)
                       {
                            reverse =  s.substring(pos, pos + 1) + reverse ;
                       }
                System.out.println("Reverse Of The String You Inputed Is:" );
                System.out.println(reverse);
                System.out.println("Testing For Palindrome:");

                if (reverse.equals(s))
                       {
                            System.out.println(s + " " + "is a palindrome" );
                       }
                else   {
                            System.out.println(s + " " + "is not a palindrome" );
                       }
    }
}
</code>```

<p>Can someone help me create a code that does it without building the reversal of the string? Many solutions I've found online uses boolean and char but the thing is, is that I haven't learn those yet. I've only learned double int and string. SO would there be a way without using boolean and char? I don't think my teacher wants us using boolean and char either because we have never discussed them. </p>

答:
Compare the string char starting from head and tail. If all the letters are equal till the middle of the string it's palindrome.</p>

```<code>boolean palindrome(string str){
  for(int i = 0 ; i < str.lenght()/2 ; i++) {
    if (str.charAt(i) != str.charAt(str.lenght() - i )
       return false;
  }
  return true;
}
</code>```

Body:
I am trying to create a Java program for my AP Computer Science class that asks the user for a string and tests whether or not the string is a palindrome or not. The teacher specifically told us to not do the project by building the reversal of the string and testing it to see if it matches. I know how to do it while building the reversal but I can't think of another way to do it.

import java.util.*;

public class mondayassignment
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a String: ");
        String s = scan.nextLine();

                while(s.indexOf(" ") >= 0)
                       {
                            s = s.substring(0, s.indexOf(" ")) +
s.substring(s.indexOf(" ") + 1);
                       }
                System.out.println("Spaces Removed:");
        System.out.println(s);
                String reverse="";
        for(int pos = 0; pos < s.length(); pos++)
                       {
                            reverse =  s.substring(pos, pos + 1) + reverse ;
                       }
                System.out.println("Reverse Of The String You Inputed Is:" );
                System.out.println(reverse);
                System.out.println("Testing For Palindrome:");

                if (reverse.equals(s))
                       {
                            System.out.println(s + " " + "is a palindrome" );
                       }
                else   {
                            System.out.println(s + " " + "is not a palindrome" );
                       }
    }
}

Can someone help me create a code that does it without building the reversal of the string? Many solutions I've found online uses boolean and char but the thing is, is that I haven't learn those yet. I've only learned double int and string. SO would there be a way without using boolean and char? I don't think my teacher wants us using boolean and char either because we have never discussed them.

Body:
Compare the string char starting from head and tail. If all the letters are equal till the middle of the string it's palindrome.

boolean palindrome(string str){
  for(int i = 0 ; i < str.lenght()/2 ; i++) {
    if (str.charAt(i) != str.charAt(str.lenght() - i )
       return false;
  }
  return true;
}


问:
Equivalent of the php fmod in C#
Does anybody know what the C# equivalent of fmod is?  I'm trying to convert this line of code to C#.

```<code>$lon_rad = fmod(($long1+$dlon_rad + M_PI), 2*M_PI) - M_PI;
</code>```

Here's what I have so far.  I just need the fmod converted.

```<code>double lon_rad = ((lon1+dlon_rad + Math.PI), 2*Math.PI) - Math.PI;
</code>```

答:
```<code>public static double fmod(double dividend, double divisor )
{
    double Modulus =
                     (Math.Abs(dividend) - (Math.Abs(divisor) *
                     (Math.Floor(Math.Abs(dividend) / Math.Abs(divisor))))) *
                     Math.Sign(dividend);

    return Modulus;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Equivalent of the php fmod in C#

Body:
Does anybody know what the C# equivalent of fmod is?  I'm trying to convert this line of code to C#.

$lon_rad = fmod(($long1+$dlon_rad + M_PI), 2*M_PI) - M_PI;

Here's what I have so far.  I just need the fmod converted.

double lon_rad = ((lon1+dlon_rad + Math.PI), 2*Math.PI) - Math.PI;


问:
How to dynamically enhance HTML with Aurelia
We're storing all our page content and blog posts etc inside WordPress, using its API to render the data in our Aurelia app. This is working well;

Authors would now like to be able to link to popups or use route-href or other custom Aurelia attributes from within their blog posts, however code added to the page using innerhtml.bind doesn't get parsed by Aurelia.

I love that a normal href="..."> "just works" in Aurelia - but we have plenty of custom attributes (like <button popup="name-of-popup">...</button> which can't be used by authors.

How can we overcome this?

Edit: With the comments from @bigopon I've started on something, but still can't quite get it to work. Either I suck at searching or the documentation is a little lacking on the TemplatingEngine.enhance() method, but I tried creating a custom attribute like this:

```<code>import {Aurelia, inject, TemplatingEngine} from 'aurelia-framework';

@inject(Element, Aurelia, TemplatingEngine)
export class AureliaEnhanceCustomAttribute {
    constructor (el, aurelia, templatingEngine) {
        this.el = el;
        this.aurelia = aurelia; // NOTE: I've never done this before - is it even correct?
        this.templatingEngine = templatingEngine;
    }

    attached () {
        this.el.innerHTML = this.value;

        // NOTE: Without checking for this we get an endless loop of attached() calls
        if (!this.el.classList.contains('au-target')) {
            this.templatingEngine.enhance({
                element: this.el,
                container: Aurelia.container, // NOTE: I'm guessing here
                resources: Aurelia.resources, // NOTE: Same here, but I need all my global resources to be available inside the enhanced element too
                bindingContext: {} // NOTE: Not sure what to pass in here at all.. :/
            });
        }
    }
}
</code>```

And I'm using it like so:

Where exampleContent is a string fetched from an API call that could look something like this: '<my-custom-element></my-custom-element><button my-custom-attribute="some-value">Log in</button>'.

答:
You are on right track. There are few things to consider

bindingContext / overrideContext: these two you can get by hooking into bind lifecycle of the custom attribute. So you will be able to pass them to the enhance instruction (requires only bindingContext, but passing both is better, helps traversing the scope). About bindingContext, 99% it will be the view model you are in, but you can always use a different object. In this case, this (custom attribute view model), is the right one.

resources: depends on how you want the resource scope of the view returned by TemplatingEngine.prototype.enhance will be. Passing global Aurelia instance's resources will not yield the local resources scope of the custom element it resides in. In order to have the same resources with the element the attribute annotates on, hook in to created lifecycle of the attribute, store the first parameter as owningView. This is the view of the custom element containing the attribute. Then you can access its resources by owningView.resources

cleaning: TemplatingEngine.prototype.enhance returns a View, you need to store this reference to detached and unbind in your attribute life cycle too

Sanitizing

An example: https://gist.run/?id=9dd32bc8a772526ae527f593e26b275b

The gist above is an example I of inheritance / enhance I made to answer another question on Discourse. You can have a look at the select-field to see more example there. It's similar to what you did there.

P/S: If you are happy with the solution, maybe consider writing a blog post / article or open a topic on Aurelia Discourse forum to help others, who may also struggle there.

Updated example:

```<code>import {Aurelia, inject, TemplatingEngine, DOM} from 'aurelia-framework';

@inject(Element, TemplatingEngine)
export class AureliaEnhanceCustomAttribute {
    constructor (el, aurelia, templatingEngine) {
        this.el = el;
        this.templatingEngine = templatingEngine;
    }

    // Custom attribute doesn't have its own view
    // Only the view of the custom element that owns it
    created(owningElementView, thisView) {
        this.owningElementView = owningElementView;
    }

    bind(bindingContext, overrideContext) {
        this.bindingContext = bindingContext;
        this.overrideContext = overrideContext;
    }

    attached () {
        this.el.innerHTML = this.value;

        // NOTE: Without checking for this we get an endless loop of attached() calls

        if (!this.el.classList.contains('au-target')) {
            this.dynamicView = this. this.templatingEngine.enhance({
                element: this.el,
                // we have two choices here, either the container of owning element, or this attribute
                // Lets go with the element, since it propbably has everything we need
                container: this.owningElementView.container,
                // the resources has information about its parent,
                // So we just need the resources of the element containing this attribute
                resources: this.owningElementView.resources,
                // Or this.bindingContext (same)
                bindingContext: this,
                // this helps travel up
                overrideContext: this.overrideContext
            });
        }
    }

    detached() {
        this.dynamicView.detached();
    }

    unbind() {
        if (this.dynamicView) {
            this.dynamicView.unbind();
        }
    }
}
</code>```

Body:
We're storing all our page content and blog posts etc inside WordPress, using its API to render the data in our Aurelia app. This is working well;

Authors would now like to be able to link to popups or use route-href or other custom Aurelia attributes from within their blog posts, however code added to the page using innerhtml.bind doesn't get parsed by Aurelia.

I love that a normal  "just works" in Aurelia - but we have plenty of custom attributes (like <button popup="name-of-popup">...</button> which can't be used by authors.

How can we overcome this?

Edit: With the comments from @bigopon I've started on something, but still can't quite get it to work. Either I suck at searching or the documentation is a little lacking on the TemplatingEngine.enhance() method, but I tried creating a custom attribute like this:

import {Aurelia, inject, TemplatingEngine} from 'aurelia-framework';

@inject(Element, Aurelia, TemplatingEngine)
export class AureliaEnhanceCustomAttribute {
    constructor (el, aurelia, templatingEngine) {
        this.el = el;
        this.aurelia = aurelia; // NOTE: I've never done this before - is it even correct?
        this.templatingEngine = templatingEngine;
    }

    attached () {
        this.el.innerHTML = this.value;

        // NOTE: Without checking for this we get an endless loop of attached() calls
        if (!this.el.classList.contains('au-target')) {
            this.templatingEngine.enhance({
                element: this.el,
                container: Aurelia.container, // NOTE: I'm guessing here
                resources: Aurelia.resources, // NOTE: Same here, but I need all my global resources to be available inside the enhanced element too
                bindingContext: {} // NOTE: Not sure what to pass in here at all.. :/
            });
        }
    }
}

And I'm using it like so:

Where exampleContent is a string fetched from an API call that could look something like this: '<my-custom-element></my-custom-element><button my-custom-attribute="some-value">Log in</button>'.

Body:
You are on right track. There are few things to consider

bindingContext / overrideContext: these two you can get by hooking into bind lifecycle of the custom attribute. So you will be able to pass them to the enhance instruction (requires only bindingContext, but passing both is better, helps traversing the scope). About bindingContext, 99% it will be the view model you are in, but you can always use a different object. In this case, this (custom attribute view model), is the right one.

resources: depends on how you want the resource scope of the view returned by TemplatingEngine.prototype.enhance will be. Passing global Aurelia instance's resources will not yield the local resources scope of the custom element it resides in. In order to have the same resources with the element the attribute annotates on, hook in to created lifecycle of the attribute, store the first parameter as owningView. This is the view of the custom element containing the attribute. Then you can access its resources by owningView.resources

cleaning: TemplatingEngine.prototype.enhance returns a View, you need to store this reference to detached and unbind in your attribute life cycle too

Sanitizing

An example: https://gist.run/?id=9dd32bc8a772526ae527f593e26b275b

The gist above is an example I of inheritance / enhance I made to answer another question on Discourse. You can have a look at the select-field to see more example there. It's similar to what you did there.

P/S: If you are happy with the solution, maybe consider writing a blog post / article or open a topic on Aurelia Discourse forum to help others, who may also struggle there.

Updated example:

import {Aurelia, inject, TemplatingEngine, DOM} from 'aurelia-framework';

@inject(Element, TemplatingEngine)
export class AureliaEnhanceCustomAttribute {
    constructor (el, aurelia, templatingEngine) {
        this.el = el;
        this.templatingEngine = templatingEngine;
    }

    // Custom attribute doesn't have its own view
    // Only the view of the custom element that owns it
    created(owningElementView, thisView) {
        this.owningElementView = owningElementView;
    }

    bind(bindingContext, overrideContext) {
        this.bindingContext = bindingContext;
        this.overrideContext = overrideContext;
    }

    attached () {
        this.el.innerHTML = this.value;

        // NOTE: Without checking for this we get an endless loop of attached() calls

        if (!this.el.classList.contains('au-target')) {
            this.dynamicView = this. this.templatingEngine.enhance({
                element: this.el,
                // we have two choices here, either the container of owning element, or this attribute
                // Lets go with the element, since it propbably has everything we need
                container: this.owningElementView.container,
                // the resources has information about its parent,
                // So we just need the resources of the element containing this attribute
                resources: this.owningElementView.resources,
                // Or this.bindingContext (same)
                bindingContext: this,
                // this helps travel up
                overrideContext: this.overrideContext
            });
        }
    }

    detached() {
        this.dynamicView.detached();
    }

    unbind() {
        if (this.dynamicView) {
            this.dynamicView.unbind();
        }
    }
}


问:
1 - 100 prime or not in Java
This is a basic prime number checker. How would I loop this code so it tells me every single number from 1 to 100 and if its prime or not. For example:

1 is not a prime number

2 is a prime number

3 is a prime number

and so on until 100. This is not a user generated program just straight up if I run it it gives me all 100 numbers

```<code>    int check;
    int number;
    boolean prime = true;
    for (int i=2; i<=check/2; i++)
    {
        number = check%i;
        if (number == 0)
        {
            prime = false;
        }
    }
    if (prime == true)
    {
        System.out.println(check + " is a prime number");
    }
    else
    {
        System.out.println(check + " is not a prime number");
    }
}
</code>```

答:
/* Prime numbers are numbers that are divisible by 1 and by themselves. So, if you take the modulus of a number 'N' with all the number from 1 till 'N' and increase a count each time the modulus is zero, you can use a simple if condition at the end to check whether they are prime or not. In this code, I start from checking with number 1 and go till 100*/ </p>

```<code>int count ;
for(int j=1;j<=100;j++)
{
count=0;
for(int i=1;i<=j;i++)
{
if(j%i==0)
count=count+1;
}
if(count>2)
System.out.println(j+"is not a prime number");
else
System.out.println(j+"is a prime number");

}
</code>```

Title: 1 - 100 prime or not in Java

Body:
This is a basic prime number checker. How would I loop this code so it tells me every single number from 1 to 100 and if its prime or not. For example:

1 is not a prime number

2 is a prime number

3 is a prime number

and so on until 100. This is not a user generated program just straight up if I run it it gives me all 100 numbers

    int check;
    int number;
    boolean prime = true;
    for (int i=2; i<=check/2; i++)
    {
        number = check%i;
        if (number == 0)
        {
            prime = false;
        }
    }
    if (prime == true)
    {
        System.out.println(check + " is a prime number");
    }
    else
    {
        System.out.println(check + " is not a prime number");
    }
}

Body:
/* Prime numbers are numbers that are divisible by 1 and by themselves. So, if you take the modulus of a number 'N' with all the number from 1 till 'N' and increase a count each time the modulus is zero, you can use a simple if condition at the end to check whether they are prime or not. In this code, I start from checking with number 1 and go till 100*/

int count ;
for(int j=1;j<=100;j++)
{
count=0;
for(int i=1;i<=j;i++)
{
if(j%i==0)
count=count+1;
}
if(count>2)
System.out.println(j+"is not a prime number");
else
System.out.println(j+"is a prime number");

}


问:
How to use new geckodriver endpoints?
The new geckodriver v0.17.0 has a new way to install addons as mentioned here:

```<code>POST /session/{session id}/window/fullscreen to invoke the window manager-specific full screen operation
POST /session/{session id}/moz/addon/install to install an extension [Gecko only]
POST /session/{session id}/moz/addon/uninstall to uninstall an extension [Gecko only]
</code>```

How can I use these endpoints to install my addon to firefox for my selenium tests?

答:
In case somebody need to use this from .NET client
(as it is not yet implemented)</p>

```<code>Public Class MyFirefoxDriver
Inherits OpenQA.Selenium.Firefox.FirefoxDriver

Public Sub New(fo As OpenQA.Selenium.Firefox.FirefoxOptions)
    MyBase.New(fo)
    MyBase.CommandExecutor.CommandInfoRepository.TryAddCommand("moz-install-web-ext", New CommandInfo(CommandInfo.PostCommand, "/session/{sessionId}/moz/addon/install"))
End Sub

Public Sub InstallWebExtension(path As String)
    Dim params As New Dictionary(Of String, Object)
    params.Add("path", path)
    params.Add("temporary", True)
    MyBase.Execute("moz-install-web-ext", params)
End Sub

End Class
</code>```

Title: How to use new geckodriver endpoints?

Body:
The new geckodriver v0.17.0 has a new way to install addons as mentioned here:

POST /session/{session id}/window/fullscreen to invoke the window manager-specific full screen operation
POST /session/{session id}/moz/addon/install to install an extension [Gecko only]
POST /session/{session id}/moz/addon/uninstall to uninstall an extension [Gecko only]

How can I use these endpoints to install my addon to firefox for my selenium tests?

Body:
In case somebody need to use this from .NET client
(as it is not yet implemented)

Public Class MyFirefoxDriver
Inherits OpenQA.Selenium.Firefox.FirefoxDriver

Public Sub New(fo As OpenQA.Selenium.Firefox.FirefoxOptions)
    MyBase.New(fo)
    MyBase.CommandExecutor.CommandInfoRepository.TryAddCommand("moz-install-web-ext", New CommandInfo(CommandInfo.PostCommand, "/session/{sessionId}/moz/addon/install"))
End Sub

Public Sub InstallWebExtension(path As String)
    Dim params As New Dictionary(Of String, Object)
    params.Add("path", path)
    params.Add("temporary", True)
    MyBase.Execute("moz-install-web-ext", params)
End Sub

End Class


问:
How to convert PascalCase to snake_case?
If I had:

```<code>$string = "PascalCase";
</code>```

I need

```<code>"pascal_case"
</code>```

Does PHP offer a function for this purpose?

答:
"CamelCase" to "camel_case":

```<code>function camelToSnake($camel)
{
    $snake = preg_replace('/[A-Z]/', '_$0', $camel);
    $snake = strtolower($snake);
    $snake = ltrim($snake, '_');
    return $snake;
}
</code>```

or:

```<code>function camelToSnake($camel)
{
    $snake = preg_replace_callback('/[A-Z]/', function ($match){
        return '_' . strtolower($match[0]);
    }, $camel);
    return ltrim($snake, '_');
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If I had:

$string = "PascalCase";

I need

"pascal_case"

Does PHP offer a function for this purpose?

Body:
"CamelCase" to "camel_case":

function camelToSnake($camel)
{
    $snake = preg_replace('/[A-Z]/', '_$0', $camel);
    $snake = strtolower($snake);
    $snake = ltrim($snake, '_');
    return $snake;
}

or:

function camelToSnake($camel)
{
    $snake = preg_replace_callback('/[A-Z]/', function ($match){
        return '_' . strtolower($match[0]);
    }, $camel);
    return ltrim($snake, '_');
}


问:
join 3 tables with where clause
This query performs three JOIN operations with 3 tables. But is not ok i see..i'm trying to output all the rows in echo, but i have bad luck.

Mysql table columns:

```<code>tours
------
titlu_slider | desc_slider | poza_slider | poza_articol | pret

tours_review
----------
name | time_added | review_text

tours_overview
------------
descriere | titlu_box1 | desc_box1 | titlu_box2 | desc_box2 | titlu_box3 | desc_box3 | titlu_box4 | desc_box4
</code>```

Php code:

```<code><?php
 $db = mysqli_connect("localhost", "root", "fidodido", "antonytravel");
 $q = mysqli_query($db,"SELECT * FROM tours  INNER JOIN tours_review INNER JOIN tours_overview  WHERE id = ".$_GET['id']."");

while ($row = mysqli_fetch_assoc($q)) {
$titlu_slider=$row['titlu_slider'];
$desc_slider=$row['desc_slider'];
$poza_slider=$row['poza_slider'];
$poza_articol=$row['poza_articol'];
$pret=$row['pret'];
## Review table
$name_review=$row['name'];
$time_added=$row['time_added'];
$review_text=$row['review_text'];
## Overview table
$descriere=$row['descriere'];
$titlu_box1=$row['titlu_box1'];
$desc_box1=$row['desc_box1'];
$titlu_box2=$row['titlu_box2'];
$desc_box2=$row['desc_box2'];
$titlu_box3=$row['titlu_box3'];
$desc_box3=$row['desc_box3'];
$titlu_box4=$row['titlu_box4'];
$desc_box4=$row['desc_box4'];

    echo '<section class="parallax_window_in" data-parallax="scroll" data-image-src="'.$poza_slider.'" data-natural-width="1400" data-natural-height="470">
        <div id="sub_content_in">
            <div id="animate_intro">
                <h1>'.$titlu_slider.'</h1>
                <p>"'.$desc_slider.'"</p>
            </div>

        </div>';
</code>```

Some help needed..thanx.

答: INNER join shows the records if there are matching record. Use OUTER join to show all records if it does not exists on other tables.</p>

Title: join 3 tables with where clause

Body:
This query performs three JOIN operations with 3 tables. But is not ok i see..i'm trying to output all the rows in echo, but i have bad luck.

Mysql table columns:

tours
------
titlu_slider | desc_slider | poza_slider | poza_articol | pret

tours_review
----------
name | time_added | review_text

tours_overview
------------
descriere | titlu_box1 | desc_box1 | titlu_box2 | desc_box2 | titlu_box3 | desc_box3 | titlu_box4 | desc_box4

Php code:

<?php
 $db = mysqli_connect("localhost", "root", "fidodido", "antonytravel");
 $q = mysqli_query($db,"SELECT * FROM tours  INNER JOIN tours_review INNER JOIN tours_overview  WHERE id = ".$_GET['id']."");

while ($row = mysqli_fetch_assoc($q)) {
$titlu_slider=$row['titlu_slider'];
$desc_slider=$row['desc_slider'];
$poza_slider=$row['poza_slider'];
$poza_articol=$row['poza_articol'];
$pret=$row['pret'];
## Review table
$name_review=$row['name'];
$time_added=$row['time_added'];
$review_text=$row['review_text'];
## Overview table
$descriere=$row['descriere'];
$titlu_box1=$row['titlu_box1'];
$desc_box1=$row['desc_box1'];
$titlu_box2=$row['titlu_box2'];
$desc_box2=$row['desc_box2'];
$titlu_box3=$row['titlu_box3'];
$desc_box3=$row['desc_box3'];
$titlu_box4=$row['titlu_box4'];
$desc_box4=$row['desc_box4'];

    echo '

'.$titlu_slider.'

"'.$desc_slider.'"

';

Some help needed..thanx.


问:
ListObject with Name defined by a variable or an Array
I am trying to create a series of NEW ListObjects with their Name defined by a variable or an array value.

```<code>TblNameArray = Array("Table1", "Table2", "Table3", "Table4",)

ActiveSheet.ListObjects.Add(xlSrcRange, Range(Cells(R1, C1), Cells(R2, C2)), , xlYes).Name = TblNameArray(w)
</code>```

I get two new Tables with the correct names and then it stops with no error.
I would prefer using a Variable, but i have not figured out how to use a variable in that location.

Any help would be greatly appreciated!

答:
From your question, it's hard to see what, exactly, you are trying to do. However, the code below does work and perhaps that will help you find your way.</p>

```<code>Private Sub InsertTables()

    Dim TblNameArray As Variant
    Dim TblRangeArray As Variant
    Dim w As Integer

    TblNameArray = Array("Table1", "Table2", "Table3", "Table4")
    TblRangeArray = Array("A2:G8", "A11:G15", "A21:G25", "A31:G35")

    With Activesheet
        For w = 0 To UBound(TblNameArray)
            .ListObjects.Add(SourceType:=xlSrcRange, _
                             Source:=Range(TblRangeArray(w)), _
                             XlListObjectHasHeaders:=xlYes).Name = TblNameArray(w)
        Next w
    End With
End Sub

Private Sub ListTables()

    Dim Tbl As ListObject

    For Each Tbl In ActiveSheet.ListObjects
        Debug.Print Tbl.Name
    Next Tbl
End Sub
</code>```

Body:
I am trying to create a series of NEW ListObjects with their Name defined by a variable or an array value.

TblNameArray = Array("Table1", "Table2", "Table3", "Table4",)

ActiveSheet.ListObjects.Add(xlSrcRange, Range(Cells(R1, C1), Cells(R2, C2)), , xlYes).Name = TblNameArray(w)

I get two new Tables with the correct names and then it stops with no error.
I would prefer using a Variable, but i have not figured out how to use a variable in that location.

Any help would be greatly appreciated!

Body:
From your question, it's hard to see what, exactly, you are trying to do. However, the code below does work and perhaps that will help you find your way.

Private Sub InsertTables()

    Dim TblNameArray As Variant
    Dim TblRangeArray As Variant
    Dim w As Integer

    TblNameArray = Array("Table1", "Table2", "Table3", "Table4")
    TblRangeArray = Array("A2:G8", "A11:G15", "A21:G25", "A31:G35")

    With Activesheet
        For w = 0 To UBound(TblNameArray)
            .ListObjects.Add(SourceType:=xlSrcRange, _
                             Source:=Range(TblRangeArray(w)), _
                             XlListObjectHasHeaders:=xlYes).Name = TblNameArray(w)
        Next w
    End With
End Sub

Private Sub ListTables()

    Dim Tbl As ListObject

    For Each Tbl In ActiveSheet.ListObjects
        Debug.Print Tbl.Name
    Next Tbl
End Sub


问:
Closing the application from a fragment causes returning to the parent activity
I tried several ways to end application from inside of a fragment, like:

```<code>system.exit(1)
android.os.Process.killProcess(android.os.Process.myPid());
getActivity().finish();
</code>```

and it is all of fragment code;Exit code put on exitDialog.setPositiveButton oncliklistener that in my try cuse backing to parent activity instead exit

```<code>package com.TB.mylistprojct;

import android.os.Bundle;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class ActFooter extends Fragment
{
    View            EMyView         =null;

    Button          BtnExit         =null;
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater Inflater,ViewGroup Container,Bundle SavedInstanceState)
{
    View MyView=Inflater.inflate(R.layout.actfooter, Container,false);
    EMyView=MyView;
    InitialUI();
    return MyView;
}

public void InitialUI()
{
    BtnExit=(Button)EMyView.findViewById(R.id.Btn_exit);
    BtnExit.setOnClickListener(BtnExit_OnClick);
}

public OnClickListener BtnExit_OnClick=new OnClickListener()
{

    @Override
    public void onClick(View arg0)
    {
        AlertDialog.Builder exitDialog=new AlertDialog.Builder(getActivity());

        exitDialog.setTitle("Warning");
        exitDialog.setMessage("Exit Program");
        exitDialog.setPositiveButton("YSE", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface arg0, int arg1)
            {
                // Exit Code PUT Here
            }
        });
        exitDialog.setNegativeButton("NO", null);
        exitDialog.show();
    }
};
}
</code>```

But the app returns to the parent activity

答:
you can use .....</p>

```<code>if(keyCode == KeyEvent.KEYCODE_BACK)
{
   getActivity().moveTaskToBack(true);
}
</code>```

Body:
I tried several ways to end application from inside of a fragment, like:

system.exit(1)
android.os.Process.killProcess(android.os.Process.myPid());
getActivity().finish();

and it is all of fragment code;Exit code put on exitDialog.setPositiveButton oncliklistener that in my try cuse backing to parent activity instead exit

package com.TB.mylistprojct;

import android.os.Bundle;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class ActFooter extends Fragment
{
    View            EMyView         =null;

    Button          BtnExit         =null;
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater Inflater,ViewGroup Container,Bundle SavedInstanceState)
{
    View MyView=Inflater.inflate(R.layout.actfooter, Container,false);
    EMyView=MyView;
    InitialUI();
    return MyView;
}

public void InitialUI()
{
    BtnExit=(Button)EMyView.findViewById(R.id.Btn_exit);
    BtnExit.setOnClickListener(BtnExit_OnClick);
}

public OnClickListener BtnExit_OnClick=new OnClickListener()
{

    @Override
    public void onClick(View arg0)
    {
        AlertDialog.Builder exitDialog=new AlertDialog.Builder(getActivity());

        exitDialog.setTitle("Warning");
        exitDialog.setMessage("Exit Program");
        exitDialog.setPositiveButton("YSE", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface arg0, int arg1)
            {
                // Exit Code PUT Here
            }
        });
        exitDialog.setNegativeButton("NO", null);
        exitDialog.show();
    }
};
}

But the app returns to the parent activity

Body:
you can use .....

if(keyCode == KeyEvent.KEYCODE_BACK)
{
   getActivity().moveTaskToBack(true);
}


问:
ghostscript fonts
I'm trying to get ghostscript to render a pdf file from a Windows box.  The pdf file uses the ComicSansMS font.  I've copied the comic.ttf file from my Windows7 box into my /usr/share/ghostscript/fonts directory, and I've created a Fontmap file in that same directory containing this line:

```<code>/ComicSansMS (comic.ttf) ;
</code>```

As nearly as I can tell, the font is not being found despite this.  The text comes out very poorly, and some of the smaller font sizes are rendered half the size they should be.  Access times and strace show that the Fontmap file is being read, but the font file (comic.ttf) is not being accessed at all.  There are no error messages:

```<code>hope 78$ gs cards-01.pdf
GPL Ghostscript  9.00 (2010-09-14)
Copyright (C) 2010 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 1.
Page 1
>>showpage, press <return> to continue<<
</code>```

If I use -dFAPIDEBUG on the gs command line, I see the following:

```<code>hope 74$ gs -dFAPIDEBUG -I/usr/share/ghostscript/fonts cards-01.pdf
GPL Ghostscript  9.00 (2010-09-14)
Copyright (C) 2010 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 1.
Page 1
FAPIhook --nostringval--
Trying to render the font Font --nostringval-- ( aliased from ComicSansMS ) with FAPI...
Font --nostringval-- ( aliased from ComicSansMS ) is being rendered with FAPI=FreeType
FAPIhook --nostringval--
Font --nostringval-- ( aliased from ComicSansMS ) is mapped to FAPI=FreeType
FAPIhook RVJCAL+SymbolMT
Trying to render the font Font RVJCAL+SymbolMT with FAPI...
Font RVJCAL+SymbolMT is being rendered with FAPI=FreeType
FAPIhook RVJCAL+SymbolMT
Font RVJCAL+SymbolMT is mapped to FAPI=FreeType
FAPIhook HYLUQF+ComicSansMS
Trying to render the font Font HYLUQF+ComicSansMS with FAPI...
Font HYLUQF+ComicSansMS is being rendered with FAPI=FreeType
FAPIhook HYLUQF+ComicSansMS
Font HYLUQF+ComicSansMS is mapped to FAPI=FreeType
>>showpage, press <return> to continue<<
</code>```

Naturally, the line from the above that most concerns me is this one:

```<code>Font --nostringval-- ( aliased from ComicSansMS ) is being rendered with FAPI=FreeType
</code>```

"gs -h" shows that the font directory is, indeed, in the search path:

```<code>hope 77$ gs -h
GPL Ghostscript  9.00 (2010-09-14)
    [ ... ]
Search path:
   /usr/share/ghostscript/9.00/Resource/Init :
   /usr/share/ghostscript/9.00/lib :
   /usr/share/ghostscript/9.00/Resource/Font :
   /usr/share/ghostscript/fonts : /usr/share/fonts/Type1 : /usr/share/fonts
</code>```

I've tried several permutations of formatting in the Fontmap file, including:

```<code>(Comic Sans MS) (comic.ttf) ;
(ComicSansMS) (comic.ttf) ;
/Comic Sans MS (comic.ttf) ;
/ComicSansMS /comic.ttf ;
</code>```

I'm fairly sure my original one is the correct one, but I was getting desperate.  :-P

Any help would be greatly appreciated.  Thanks in advance.

答:
I assume that PDF does not have the ComicSansMS font embedded?

You should consider 2 other possibilities as well:

Your PDF file card-01.pdf is somehow corrupted. (Are other PDF viewers rendering that file without a problem? Does it display OK in Acrobat Reader on Widnows?)

Your fontfile comic.ttf is somehow corrupted. (Which method did you use to transfer it from Windows to Linux?)

You could try to positively proof that both these components are getting along well enough with each other by using Ghostscript+comic.ttf to create a PDF (with comic.ttf embedded):

```<code>gs \
  -sFONTPATH=/usr/share/ghostscript/fonts \
  -o comic-ttf.pdf \
  -sDEVICE=pdfwrite \
  -g5950x8420 \
  -c "200 700 moveto" \
  -c "/ComicSansMS findfont 60 scalefont setfont" \
  -c "(comic.ttf) show showpage"
</code>```

On Windows, use this variation of above command:

```<code>gswin32c.exe ^
  -o comic-ttf.pdf ^
  -sDEVICE=pdfwrite ^
  -sFONTPATH=c:/windows/fonts ^
  -g5950x8420 ^
  -c "200 700 moveto" ^
  -c "/ComicSansMS findfont 60 scalefont setfont" ^
  -c "(comic.ttf) show showpage"
</code>```

When I do this, I see:

```<code>gswin32c.exe ^
   -o comic-ttf.pdf ^
   -sDEVICE=pdfwrite ^
   -sFONTPATH=c:/windows/fonts ^
   -dHaveTrueTypes=true ^
   -g5950x8420 ^
   -c "200 700 moveto" ^
   -c "/ComicSansMS findfont 60 scalefont setfont" ^
   -c "(comic.ttf) show showpage"
GPL Ghostscript  9.00 (2010-09-14)
Copyright (C) 2010 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Scanning c:/windows/fonts for fonts... 423 files, 255 scanned, 240 new fonts.
Loading ComicSansMS font from c:/windows/fonts/comic.ttf... 3343720 1813337 2926116 1611207 1 done.
</code>```

and my output PDF comic-ttf.pdf looks OK and does have the comic.ttf font embedded.

If this does also work for you, then your Ghostscript and your comic.ttf are OK, but your PDF file cards-01.pdf is not.

Title: ghostscript fonts

Body:
I'm trying to get ghostscript to render a pdf file from a Windows box.  The pdf file uses the ComicSansMS font.  I've copied the comic.ttf file from my Windows7 box into my /usr/share/ghostscript/fonts directory, and I've created a Fontmap file in that same directory containing this line:

/ComicSansMS (comic.ttf) ;

As nearly as I can tell, the font is not being found despite this.  The text comes out very poorly, and some of the smaller font sizes are rendered half the size they should be.  Access times and strace show that the Fontmap file is being read, but the font file (comic.ttf) is not being accessed at all.  There are no error messages:

hope 78$ gs cards-01.pdf
GPL Ghostscript  9.00 (2010-09-14)
Copyright (C) 2010 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 1.
Page 1
>>showpage, press <return> to continue<<

If I use -dFAPIDEBUG on the gs command line, I see the following:

hope 74$ gs -dFAPIDEBUG -I/usr/share/ghostscript/fonts cards-01.pdf
GPL Ghostscript  9.00 (2010-09-14)
Copyright (C) 2010 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 1.
Page 1
FAPIhook --nostringval--
Trying to render the font Font --nostringval-- ( aliased from ComicSansMS ) with FAPI...
Font --nostringval-- ( aliased from ComicSansMS ) is being rendered with FAPI=FreeType
FAPIhook --nostringval--
Font --nostringval-- ( aliased from ComicSansMS ) is mapped to FAPI=FreeType
FAPIhook RVJCAL+SymbolMT
Trying to render the font Font RVJCAL+SymbolMT with FAPI...
Font RVJCAL+SymbolMT is being rendered with FAPI=FreeType
FAPIhook RVJCAL+SymbolMT
Font RVJCAL+SymbolMT is mapped to FAPI=FreeType
FAPIhook HYLUQF+ComicSansMS
Trying to render the font Font HYLUQF+ComicSansMS with FAPI...
Font HYLUQF+ComicSansMS is being rendered with FAPI=FreeType
FAPIhook HYLUQF+ComicSansMS
Font HYLUQF+ComicSansMS is mapped to FAPI=FreeType
>>showpage, press <return> to continue<<

Naturally, the line from the above that most concerns me is this one:

Font --nostringval-- ( aliased from ComicSansMS ) is being rendered with FAPI=FreeType

"gs -h" shows that the font directory is, indeed, in the search path:

hope 77$ gs -h
GPL Ghostscript  9.00 (2010-09-14)
    [ ... ]
Search path:
   /usr/share/ghostscript/9.00/Resource/Init :
   /usr/share/ghostscript/9.00/lib :
   /usr/share/ghostscript/9.00/Resource/Font :
   /usr/share/ghostscript/fonts : /usr/share/fonts/Type1 : /usr/share/fonts

I've tried several permutations of formatting in the Fontmap file, including:

(Comic Sans MS) (comic.ttf) ;
(ComicSansMS) (comic.ttf) ;
/Comic Sans MS (comic.ttf) ;
/ComicSansMS /comic.ttf ;

I'm fairly sure my original one is the correct one, but I was getting desperate.  :-P

Any help would be greatly appreciated.  Thanks in advance.

Body:
I assume that PDF does not have the ComicSansMS font embedded?

You should consider 2 other possibilities as well:

Your PDF file card-01.pdf is somehow corrupted. (Are other PDF viewers rendering that file without a problem? Does it display OK in Acrobat Reader on Widnows?)

Your fontfile comic.ttf is somehow corrupted. (Which method did you use to transfer it from Windows to Linux?)

You could try to positively proof that both these components are getting along well enough with each other by using Ghostscript+comic.ttf to create a PDF (with comic.ttf embedded):

gs \
  -sFONTPATH=/usr/share/ghostscript/fonts \
  -o comic-ttf.pdf \
  -sDEVICE=pdfwrite \
  -g5950x8420 \
  -c "200 700 moveto" \
  -c "/ComicSansMS findfont 60 scalefont setfont" \
  -c "(comic.ttf) show showpage"

On Windows, use this variation of above command:

gswin32c.exe ^
  -o comic-ttf.pdf ^
  -sDEVICE=pdfwrite ^
  -sFONTPATH=c:/windows/fonts ^
  -g5950x8420 ^
  -c "200 700 moveto" ^
  -c "/ComicSansMS findfont 60 scalefont setfont" ^
  -c "(comic.ttf) show showpage"

When I do this, I see:

gswin32c.exe ^
   -o comic-ttf.pdf ^
   -sDEVICE=pdfwrite ^
   -sFONTPATH=c:/windows/fonts ^
   -dHaveTrueTypes=true ^
   -g5950x8420 ^
   -c "200 700 moveto" ^
   -c "/ComicSansMS findfont 60 scalefont setfont" ^
   -c "(comic.ttf) show showpage"
GPL Ghostscript  9.00 (2010-09-14)
Copyright (C) 2010 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Scanning c:/windows/fonts for fonts... 423 files, 255 scanned, 240 new fonts.
Loading ComicSansMS font from c:/windows/fonts/comic.ttf... 3343720 1813337 2926116 1611207 1 done.

and my output PDF comic-ttf.pdf looks OK and does have the comic.ttf font embedded.

If this does also work for you, then your Ghostscript and your comic.ttf are OK, but your PDF file cards-01.pdf is not.


问:
how to improve the performance of in sql expression
I am now execution a sql similar to below：

```<code>select * from table_name where num in (123,124....,210) and type='a'
</code>```

the records of the table_name is around 1500000, so the execution time is very long, is there any idea that I could improve the efficiency?

Thanks.

答: For your query, you want an index on table_name(type, num).

Body:
I am now execution a sql similar to below：

select * from table_name where num in (123,124....,210) and type='a'

the records of the table_name is around 1500000, so the execution time is very long, is there any idea that I could improve the efficiency?

Thanks.


问:
Accessing specific elements in nested array
I am trying to access this array of hashes:

```<code>[
  {
    "Book": "1: SS",
    "Concordance": ". they tugged and heaved at the door, but it
    wouldn’tbudge, not even when hermione tried her alohomora charm, now
    what? said ron, these birds … they can’t be here just for decoration,",
    "Position": 82471,
    "Spell": "alohomora"
  },
  {
    "Book": "1: SS",
    "Concordance": "oh, move over, hermione snarled, she grabbed Harry’s
    wand, tapped the lock, and whispered, alohomora! the lock clicked and
    the door swung open — they piled through it, shut it quickly,",
    "Position": 47346,
    "Spell": "alohomora"
  },
  {
    "Book": "1: SS",
    "Concordance": "it on snape if he showed any sign of wanting to hurt
    Harry, now, don’t forget, it’s locomotormortis, hermione muttered as
     ron slipped his wand up his sleeve, i know, ron snapped, don’t",
    "Position": 65427,
    "Spell": "locomotormortis"
  },
]
</code>```

How will I access the Spell within the second array element? How can I access a specific field of this array?

I have tried to do Mentions.data[1]["Spell"] but I know this is wrong.

答:
Print Mentions.data[1] to see what Ruby sees.

```<code>{:Book => "1: SS",
 :Concordance =>
  "oh, move over, hermione snarled, she grabbed Harry’s \n" +
  "    wand, tapped the lock, and whispered, alohomora! the lock clicked and \n" +
  "    the door swung open — they piled through it, shut it quickly,",
 :Position => 47346,
 :Spell => "alohomora"}
</code>```

Then it's clear to see we use:

```<code>Mentions.data[1][:Spell] #=> "alohomora"
</code>```

Body:
I am trying to access this array of hashes:

[
  {
    "Book": "1: SS",
    "Concordance": ". they tugged and heaved at the door, but it
    wouldn’tbudge, not even when hermione tried her alohomora charm, now
    what? said ron, these birds … they can’t be here just for decoration,",
    "Position": 82471,
    "Spell": "alohomora"
  },
  {
    "Book": "1: SS",
    "Concordance": "oh, move over, hermione snarled, she grabbed Harry’s
    wand, tapped the lock, and whispered, alohomora! the lock clicked and
    the door swung open — they piled through it, shut it quickly,",
    "Position": 47346,
    "Spell": "alohomora"
  },
  {
    "Book": "1: SS",
    "Concordance": "it on snape if he showed any sign of wanting to hurt
    Harry, now, don’t forget, it’s locomotormortis, hermione muttered as
     ron slipped his wand up his sleeve, i know, ron snapped, don’t",
    "Position": 65427,
    "Spell": "locomotormortis"
  },
]

How will I access the Spell within the second array element? How can I access a specific field of this array?

I have tried to do Mentions.data[1]["Spell"] but I know this is wrong.

Body:
Print Mentions.data[1] to see what Ruby sees.

{:Book => "1: SS",
 :Concordance =>
  "oh, move over, hermione snarled, she grabbed Harry’s \n" +
  "    wand, tapped the lock, and whispered, alohomora! the lock clicked and \n" +
  "    the door swung open — they piled through it, shut it quickly,",
 :Position => 47346,
 :Spell => "alohomora"}

Then it's clear to see we use:

Mentions.data[1][:Spell] #=> "alohomora"


答:
When you visually confirm whether a word is a palindrome or not, usually you would just check the characters from either end and start moving inwards.

So really that's two steps:

Check the end bits of the char if they're the same. If they aren't, it's not a palindrome, otherwise, next step

Move inwards from both ends, and repeat #1 till there are 1 or 0 characters left to be checked. (Hint: If you can't use chars, maybe try using a single character string :) )

Title: Creating a program that tests for palindrome without building the reversal (Java)

Body:
I am trying to create a Java program for my AP Computer Science class that asks the user for a string and tests whether or not the string is a palindrome or not. The teacher specifically told us to not do the project by building the reversal of the string and testing it to see if it matches. I know how to do it while building the reversal but I can't think of another way to do it.

import java.util.*;

public class mondayassignment
{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a String: ");
        String s = scan.nextLine();

                while(s.indexOf(" ") >= 0)
                       {
                            s = s.substring(0, s.indexOf(" ")) +
s.substring(s.indexOf(" ") + 1);
                       }
                System.out.println("Spaces Removed:");
        System.out.println(s);
                String reverse="";
        for(int pos = 0; pos < s.length(); pos++)
                       {
                            reverse =  s.substring(pos, pos + 1) + reverse ;
                       }
                System.out.println("Reverse Of The String You Inputed Is:" );
                System.out.println(reverse);
                System.out.println("Testing For Palindrome:");

                if (reverse.equals(s))
                       {
                            System.out.println(s + " " + "is a palindrome" );
                       }
                else   {
                            System.out.println(s + " " + "is not a palindrome" );
                       }
    }
}

Can someone help me create a code that does it without building the reversal of the string? Many solutions I've found online uses boolean and char but the thing is, is that I haven't learn those yet. I've only learned double int and string. SO would there be a way without using boolean and char? I don't think my teacher wants us using boolean and char either because we have never discussed them.


问:
How do you store "int" values in an NSMutableArray* or NSMutableDictionary*? Chronic problems with JSON data that come in as integers.
How do you store "int" values in an NSMutableArray or NSMutableDictionary?  Chronic problems with JSON data that come in as integers.

Should I try to store these integers as NSNumber objects or just as strings that contain the integer?

How dangerous is it to do a "raw" (int) conversion on the pointers if I know the values will always be Natural Numbers (numbers>=0 including zero for null.)

The integers I'm always working with are Foreign Key Id's from a database.

答:
You can also use:</p>

```<code>[myDict setObject:[NSNumber numberWithInt:anInteger] forKey:@"MyInteger"];
</code>```

Body:
You can also use:

[myDict setObject:[NSNumber numberWithInt:anInteger] forKey:@"MyInteger"];


问:
Getting all reviews from a steam game using Steamworks?
Currently, I am trying to get all the steam reviews from a particular game, using the method described in the Steamworks documentation:
https://partner.steamgames.com/doc/store/getreviews

However, when I try to get reviews for a game like Team Fortress 2 for example using the method:
http://store.steampowered.com/appreviews/440?json=1
I always get 20 reviews, due to the start_offset parameter.

Is there a way to get all the reviews in one method command, or do I have to create a loop with different start_offset?

答:
Taplar mentioned it correctly in his comment. start_offset - reviews are returned in batches of 20, so pass 0 for the first set, then 20 for the next set, etc. You need to use the offset like this:

http://store.steampowered.com/appreviews/10?json=1&start_offset=0

http://store.steampowered.com/appreviews/10?json=1&start_offset=20

http://store.steampowered.com/appreviews/10?json=1&start_offset=40

For a game like DOTA 2 there are like 650,000+ reviews. If you imagine yourself in Valve's place it would make sense to limit API calls. So I think it's safe to say that there is no API for all reviews at once.


问:
Best way to convert query string to dictionary in C#
I'm looking for the simplest way of converting a query string from an HTTP GET request into a Dictionary, and back again.

I figure it's easier to carry out various manipulations on the query once it is in dictionary form, but I seem to have a lot of code just to do the conversion. Any recommended ways?

答:
Most simple:</p>

```<code>Dictionary<string, string> parameters = new Dictionary<string, string>();

for (int i = 0; i < context.Request.QueryString.Count; i++)
{
    parameters.Add(context.Request.QueryString.GetKey(i), context.Request.QueryString[i]);
}
</code>```

OwnerDisplayName: AndyH

Body:
Most simple:

Dictionary<string, string> parameters = new Dictionary<string, string>();

for (int i = 0; i < context.Request.QueryString.Count; i++)
{
    parameters.Add(context.Request.QueryString.GetKey(i), context.Request.QueryString[i]);
}


问:
Problems updating w/ EF4 repo & MVC2 - can't update many-to-many graph
I can't seem to successfully update a many-to-many graph in MVC2 using EF4.  I figured the simplest thing to do would be to Clear() the entire graph, call SaveChanges(), then rebuild the graph calling SaveChanges() again at the end, but it's not working.  All my other properties ARE working, however. First, my Action Methods:

```<code>    public ActionResult EditReview(int id)
    {
        var game = _gameRepository.GetGame(id);
        var genres = _gameRepository.AllGenres();
        var platforms = _gameRepository.AllPlatforms();

        var model = new AdminGameViewModel { GameData = game, AllGenres = genres, AllPlatforms = platforms };

        return View(model);
    }

    //
    // POST: /Admin/EditReview/5

    [HttpPost]
    public ActionResult EditReview([Bind(Prefix="GameData")]Game existingGame, int[] PlatformIDs)
    {
        try
        {
            _gameRepository.ValidateGame(existingGame, PlatformIDs);
        }
        catch(RulesException ex)
        {
            ex.CopyTo(ModelState);
            ex.CopyTo(ModelState, "GameData");
        }

        if (ModelState.IsValid)
        {
            return RedirectToAction("Index");
        }
        else
        {
            var genres = _gameRepository.AllGenres();
            var platforms = _gameRepository.AllPlatforms();

            var model = new AdminGameViewModel { GameData = existingGame, AllGenres = genres, AllPlatforms = platforms };

            return View(model);
        }
    }
</code>```

The repo itself (ValidateGame and SaveGame are the relevant methods):

```<code>namespace HandiGamer.Domain.Concrete
{
    public class HGGameRepository : IGameRepository
    {
        private HGEntities _siteDB = new HGEntities();

        public List<Game> Games
        {
            get { return _siteDB.Games.ToList(); }
        }

        public void ValidateGame(Game game, int[] PlatformIDs)
        {
            var errors = new RulesException<Game>();

            if (string.IsNullOrEmpty(game.GameTitle))
            {
                errors.ErrorFor(x => x.GameTitle, "A game must have a title");
            }

            if (string.IsNullOrEmpty(game.ReviewText))
            {
                errors.ErrorFor(x => x.ReviewText, "A review must be written");
            }

            if (game.ReviewScore <= 0 || game.ReviewScore > 5)
            {
                errors.ErrorFor(x => x.ReviewScore, "A game must have a review score, and the score must be between 1 and 5");
            }

            if (string.IsNullOrEmpty(game.Pros))
            {
                errors.ErrorFor(x => x.Pros, "Each game review must have a list of pros");
            }

            if (string.IsNullOrEmpty(game.Cons))
            {
                errors.ErrorFor(x => x.Cons, "Each game review must have a list of cons");
            }

            if (PlatformIDs == null || PlatformIDs.Length == 0)
            {
                errors.ErrorForModel("A game must belong to at least one platform");
            }

            if (game.GenreID == 0)
            {
                errors.ErrorFor(x => x.GenreID, "A game must be associated with a genre");
            }

            if (errors.Errors.Any())
            {
                throw errors;
            }
            else
            {
                SaveGame(game, PlatformIDs);
            }
        }

        public void SaveGame(Game game, int[] PlatformIDs)
        {
            _siteDB.Games.Attach(game);

            if (game.GameID > 0)
            {
                _siteDB.ObjectStateManager.ChangeObjectState(game, System.Data.EntityState.Modified);

                game.Platforms.Clear();
            }
            else
            {
                _siteDB.ObjectStateManager.ChangeObjectState(game, System.Data.EntityState.Added);
            }

            foreach (int id in PlatformIDs)
            {
                Platform plat = _siteDB.Platforms.Single(pl => pl.PlatformID == id);
                game.Platforms.Add(plat);
            }

            game.LastModified = DateTime.Now;

            _siteDB.SaveChanges();
        }

        public Game GetGame(int id)
        {
            return _siteDB.Games.Include("Genre").Include("Platforms").SingleOrDefault(g => g.GameID == id);
        }

        public IEnumerable<Game> GetGame(string title)
        {
            return _siteDB.Games.Include("Genre").Include("Platforms").Where(g => g.GameTitle.StartsWith(title)).AsEnumerable<Game>();
        }

        public List<Game> GetGamesByGenre(int id)
        {
            return _siteDB.Games.Where(g => g.GenreID == id).ToList();
        }

        public List<Game> GetGamesByGenre(string genre)
        {
            return _siteDB.Games.Where(g => g.Genre.Name == genre).ToList();
        }

        public List<Game> GetGamesByPlatform(int id)
        {
            return _siteDB.Games.Where(g => g.Platforms.Any(p => p.PlatformID == id)).ToList();
        }

        public List<Game> GetGamesByPlatform(string platform)
        {
            return _siteDB.Games.Where(g => g.Platforms.Any(p => p.Name == platform)).ToList();
        }

        public List<Genre> AllGenres()
        {
            return _siteDB.Genres.OrderBy(g => g.Name).ToList();
        }

        public List<Platform> AllPlatforms()
        {
            return _siteDB.Platforms.OrderBy(p => p.PlatformID).ToList();
        }
    }
}
</code>```

I'm stumped.

答:
Kevin,
oh this is a little complex and forces you back to EFv1 patterns because with M:M you don't have foreign keys to lean on and you are stuck with having objects.

WHen you add a game, you do want the relationship (i.e. a row in the join table) to be added but you don't want the platform to be added since it's just a reference.

I haven't actually done this but I think it would be easier if you could break it apart and then rebuild the platforms collection once the game is attached and marked added. Otherwise if you add the whole graph, everything gets marked added.

Problem with EF is that if you attach game you will get the related stuff attached too. There might be a cleaner pattern but my thought is to detach the platforms from the game, attach the game to the context, mark it as added. Then I would attach the platforms to the context. They will be "unchanged". Then add them to the games.platform collection. The platforms will still be unchanged but the : will be understood.

You may have tried that. I'd have to do it myself and watch the entity state of everything as I go along to see for sure what's happening. The key is that EF needs to track that a relationship has been added and that's new (and will result in a row in the join table being added) but understand that Platforms are not new.

hth
julie

Body:
I can't seem to successfully update a many-to-many graph in MVC2 using EF4.  I figured the simplest thing to do would be to Clear() the entire graph, call SaveChanges(), then rebuild the graph calling SaveChanges() again at the end, but it's not working.  All my other properties ARE working, however. First, my Action Methods:

    public ActionResult EditReview(int id)
    {
        var game = _gameRepository.GetGame(id);
        var genres = _gameRepository.AllGenres();
        var platforms = _gameRepository.AllPlatforms();

        var model = new AdminGameViewModel { GameData = game, AllGenres = genres, AllPlatforms = platforms };

        return View(model);
    }

    //
    // POST: /Admin/EditReview/5

    [HttpPost]
    public ActionResult EditReview([Bind(Prefix="GameData")]Game existingGame, int[] PlatformIDs)
    {
        try
        {
            _gameRepository.ValidateGame(existingGame, PlatformIDs);
        }
        catch(RulesException ex)
        {
            ex.CopyTo(ModelState);
            ex.CopyTo(ModelState, "GameData");
        }

        if (ModelState.IsValid)
        {
            return RedirectToAction("Index");
        }
        else
        {
            var genres = _gameRepository.AllGenres();
            var platforms = _gameRepository.AllPlatforms();

            var model = new AdminGameViewModel { GameData = existingGame, AllGenres = genres, AllPlatforms = platforms };

            return View(model);
        }
    }

The repo itself (ValidateGame and SaveGame are the relevant methods):

namespace HandiGamer.Domain.Concrete
{
    public class HGGameRepository : IGameRepository
    {
        private HGEntities _siteDB = new HGEntities();

        public List<Game> Games
        {
            get { return _siteDB.Games.ToList(); }
        }

        public void ValidateGame(Game game, int[] PlatformIDs)
        {
            var errors = new RulesException<Game>();

            if (string.IsNullOrEmpty(game.GameTitle))
            {
                errors.ErrorFor(x => x.GameTitle, "A game must have a title");
            }

            if (string.IsNullOrEmpty(game.ReviewText))
            {
                errors.ErrorFor(x => x.ReviewText, "A review must be written");
            }

            if (game.ReviewScore <= 0 || game.ReviewScore > 5)
            {
                errors.ErrorFor(x => x.ReviewScore, "A game must have a review score, and the score must be between 1 and 5");
            }

            if (string.IsNullOrEmpty(game.Pros))
            {
                errors.ErrorFor(x => x.Pros, "Each game review must have a list of pros");
            }

            if (string.IsNullOrEmpty(game.Cons))
            {
                errors.ErrorFor(x => x.Cons, "Each game review must have a list of cons");
            }

            if (PlatformIDs == null || PlatformIDs.Length == 0)
            {
                errors.ErrorForModel("A game must belong to at least one platform");
            }

            if (game.GenreID == 0)
            {
                errors.ErrorFor(x => x.GenreID, "A game must be associated with a genre");
            }

            if (errors.Errors.Any())
            {
                throw errors;
            }
            else
            {
                SaveGame(game, PlatformIDs);
            }
        }

        public void SaveGame(Game game, int[] PlatformIDs)
        {
            _siteDB.Games.Attach(game);

            if (game.GameID > 0)
            {
                _siteDB.ObjectStateManager.ChangeObjectState(game, System.Data.EntityState.Modified);

                game.Platforms.Clear();
            }
            else
            {
                _siteDB.ObjectStateManager.ChangeObjectState(game, System.Data.EntityState.Added);
            }

            foreach (int id in PlatformIDs)
            {
                Platform plat = _siteDB.Platforms.Single(pl => pl.PlatformID == id);
                game.Platforms.Add(plat);
            }

            game.LastModified = DateTime.Now;

            _siteDB.SaveChanges();
        }

        public Game GetGame(int id)
        {
            return _siteDB.Games.Include("Genre").Include("Platforms").SingleOrDefault(g => g.GameID == id);
        }

        public IEnumerable<Game> GetGame(string title)
        {
            return _siteDB.Games.Include("Genre").Include("Platforms").Where(g => g.GameTitle.StartsWith(title)).AsEnumerable<Game>();
        }

        public List<Game> GetGamesByGenre(int id)
        {
            return _siteDB.Games.Where(g => g.GenreID == id).ToList();
        }

        public List<Game> GetGamesByGenre(string genre)
        {
            return _siteDB.Games.Where(g => g.Genre.Name == genre).ToList();
        }

        public List<Game> GetGamesByPlatform(int id)
        {
            return _siteDB.Games.Where(g => g.Platforms.Any(p => p.PlatformID == id)).ToList();
        }

        public List<Game> GetGamesByPlatform(string platform)
        {
            return _siteDB.Games.Where(g => g.Platforms.Any(p => p.Name == platform)).ToList();
        }

        public List<Genre> AllGenres()
        {
            return _siteDB.Genres.OrderBy(g => g.Name).ToList();
        }

        public List<Platform> AllPlatforms()
        {
            return _siteDB.Platforms.OrderBy(p => p.PlatformID).ToList();
        }
    }
}

I'm stumped.


问:
How to get input value from templates and store to database [Django]
I'm trying to get {{ id }} when user clicks on movie and save it to models. I can't use modelForm because id parameter comes from html template. Any suggestions?

Maybe, there is a different way to get an id of that movie user clicks?

Btw, I'm using tmdb api.

```<code>{% for id, poster in poster_id_zip %}
    <div style="display: inline-block; margin: 10px;" class="">
      <a href="{{ movie_details }}"><img src="{{ poster }}" alt=""></a>
      <form class="add-movie-form" method="POST">
        {% csrf_token %}
        <input type="hidden" name="movie-id" value="{{ id }}">
        <button style="display: block; margin: 5px auto 0 auto;" type="submit" name="add">Add</button>
      </form>
    </div>
{% endfor %}
</code>```

views.py

```<code>def index(request):
    api_key = "api_key"
    image_base_url = "https://image.tmdb.org/t/p/"
    if request.method == "POST":
        user_query = request.POST.get('search-box', ' ')
        if user_query == '':
            user_query = ' '

        search_movies_url = "https://api.themoviedb.org/3/search/movie?api_key={}&query={}".format(api_key, user_query)

        search_results_data = requests.get(search_movies_url)

        total_results = search_results_data.json().get("total_results") # for handling no search results

        movie_ids, poster_path, poster_full_url = [], [], []

        for movie in search_results_data.json().get("results"):
            movie_ids.append(movie.get("id"))
            poster_path.append(movie.get("poster_path"))

        for poster in poster_path:
            poster_full_url.append(image_base_url+"{}{}".format("w185", poster))

        movie_details = "https://api.themoviedb.org/3/movie/{}?api_key={}".format(movie_ids, api_key)

        poster_id_zip = zip(movie_ids, poster_full_url) # grouping ids with poster images

        context = {"movie_ids": movie_ids, "poster_url": poster_full_url, "movie_details": movie_details, "poster_id_zip": poster_id_zip, "total_results": total_results,}

        return render(request, 'homepage/movies.html', context)
    return render(request, 'homepage/index.html')
</code>```

models.py

```<code>from django.db import models

# Create your models here.

class MovieId(models.Model):
    movie_id = models.IntegerField()
    def __str__(self):
        return self.movie_id
</code>```

答:
I think all you have to do is create a ModelForm. And then do something like:

```<code>movie_form = MovieModelForm(request.POST)
if movie_form.is_valid():
    movie_form.save() # to save the object
</code>```

Before that change the name of input item in HTML to this:

```<code><input type="hidden" name="movie_id" value="{{ id }}">
</code>```

to match the modelform.

Body:
I'm trying to get {{ id }} when user clicks on movie and save it to models. I can't use modelForm because id parameter comes from html template. Any suggestions?

Maybe, there is a different way to get an id of that movie user clicks?

Btw, I'm using tmdb api.

{% for id, poster in poster_id_zip %}

      <form class="add-movie-form" method="POST">
        {% csrf_token %}
        <input type="hidden" name="movie-id" value="{{ id }}">
        <button style="display: block; margin: 5px auto 0 auto;" type="submit" name="add">Add</button>
      </form>

{% endfor %}

views.py

def index(request):
    api_key = "api_key"
    image_base_url = "https://image.tmdb.org/t/p/"
    if request.method == "POST":
        user_query = request.POST.get('search-box', ' ')
        if user_query == '':
            user_query = ' '

        search_movies_url = "https://api.themoviedb.org/3/search/movie?api_key={}&query={}".format(api_key, user_query)

        search_results_data = requests.get(search_movies_url)

        total_results = search_results_data.json().get("total_results") # for handling no search results

        movie_ids, poster_path, poster_full_url = [], [], []

        for movie in search_results_data.json().get("results"):
            movie_ids.append(movie.get("id"))
            poster_path.append(movie.get("poster_path"))

        for poster in poster_path:
            poster_full_url.append(image_base_url+"{}{}".format("w185", poster))

        movie_details = "https://api.themoviedb.org/3/movie/{}?api_key={}".format(movie_ids, api_key)

        poster_id_zip = zip(movie_ids, poster_full_url) # grouping ids with poster images

        context = {"movie_ids": movie_ids, "poster_url": poster_full_url, "movie_details": movie_details, "poster_id_zip": poster_id_zip, "total_results": total_results,}

        return render(request, 'homepage/movies.html', context)
    return render(request, 'homepage/index.html')

models.py

from django.db import models

# Create your models here.

class MovieId(models.Model):
    movie_id = models.IntegerField()
    def __str__(self):
        return self.movie_id

Body:
I think all you have to do is create a ModelForm. And then do something like:

movie_form = MovieModelForm(request.POST)
if movie_form.is_valid():
    movie_form.save() # to save the object

Before that change the name of input item in HTML to this:

<input type="hidden" name="movie_id" value="{{ id }}">

to match the modelform.


问:
JS function unexpected result?
I am trying to figure out this code...

```<code>function addTen(x) {
  return x + 10;
}

function divideByThree(y) {
  return y / 3;
}

var result = addTen(2);
console.log(divideByThree(result));
</code>```

How i took it is like that. result should be 20 because it says (2) so 10 x 2 = 20 then divide it by 3 and that's 6,something.
Well,it actually equals 4,why is that? Can anyone explain please?

答:
addTen does not multiply by 2, it adds 10 to 2:

10 + 2 = 12

Then divided by 3: 12 / 3 = 4

Title: JS function unexpected result?

Body:
I am trying to figure out this code...

function addTen(x) {
  return x + 10;
}

function divideByThree(y) {
  return y / 3;
}

var result = addTen(2);
console.log(divideByThree(result));

How i took it is like that. result should be 20 because it says (2) so 10 x 2 = 20 then divide it by 3 and that's 6,something.
Well,it actually equals 4,why is that? Can anyone explain please?


问:
AssertJ to log assertion's results
I'm trying to understand if is possible to configure AssertJ to log the negative result of an assertion to a file without interrupting the routing that is running the comparison.

The reason behind this request is that we are comparing the JSON generated by two version of a software to spot differences, but instead of manually creating all the checks I would like to leverage the functionalities already available in AssertJ.

As a possible solution to this I was thinking of using a try/catch for  assertion exceptions, but I'm really concerned about the overall performance of the routine.

Any idea?

答:
You can access the error message by catching the AssertionError, then use whatever logging framework.
If you want to capture all the errors (and not fail at the first one), use soft assertions. </p>

Title: AssertJ to log assertion's results


问:
iOS Development: How can I shorten a URL from my code?
I'm building an iPhone app and I'd like to include functionality that allows users to login to twitter and tweet a link to my app. In order to do this, however, the tweet will need to shorten the URL to my app on the App Store.  How can I write code to shorten a URL for a tweet?

I've done a search for this and found a tutorial on iCodeBlog, as well as some questions posted on SO, however, they're all either more work than I think is needed or they're using http://api.tr.im, which is no longer available.  I'm hoping there's a newer approach to this that is as simple as the iCodeBlog solution.

Thanks for your wisdom!

答: I just google a few minutes because I'm also interested in that topic. And I found this: TinyURL API I think that's the easiest way to implement something like this. I think I'll write a little class for this to use it in further projects. :-D</p>


答:
You are missing a few things in your query. Specifically related to the fields that link the tables. To do these joins the best practice is to name each table and then use that name to in an ON statement to JOIN the tables

So

```<code>SELECT * FROM tours
INNER JOIN tours_review
INNER JOIN tours_overview
WHERE id = ".$_GET['id'].""
</code>```

Should be:

```<code>SELECT * FROM tours AS t
INNER JOIN tours_review AS r ON r.somefield = t.somefield
INNER JOIN tours_overview AS o ON o.somefield = t.somefield
WHERE id = ".$_GET['id'].""
</code>```

MySQL can't join tables if it doesn't know what is connecting them.

Title: join 3 tables with where clause

Body:
This query performs three JOIN operations with 3 tables. But is not ok i see..i'm trying to output all the rows in echo, but i have bad luck.

Mysql table columns:

tours
------
titlu_slider | desc_slider | poza_slider | poza_articol | pret

tours_review
----------
name | time_added | review_text

tours_overview
------------
descriere | titlu_box1 | desc_box1 | titlu_box2 | desc_box2 | titlu_box3 | desc_box3 | titlu_box4 | desc_box4

Php code:

<?php
 $db = mysqli_connect("localhost", "root", "fidodido", "antonytravel");
 $q = mysqli_query($db,"SELECT * FROM tours  INNER JOIN tours_review INNER JOIN tours_overview  WHERE id = ".$_GET['id']."");

while ($row = mysqli_fetch_assoc($q)) {
$titlu_slider=$row['titlu_slider'];
$desc_slider=$row['desc_slider'];
$poza_slider=$row['poza_slider'];
$poza_articol=$row['poza_articol'];
$pret=$row['pret'];
## Review table
$name_review=$row['name'];
$time_added=$row['time_added'];
$review_text=$row['review_text'];
## Overview table
$descriere=$row['descriere'];
$titlu_box1=$row['titlu_box1'];
$desc_box1=$row['desc_box1'];
$titlu_box2=$row['titlu_box2'];
$desc_box2=$row['desc_box2'];
$titlu_box3=$row['titlu_box3'];
$desc_box3=$row['desc_box3'];
$titlu_box4=$row['titlu_box4'];
$desc_box4=$row['desc_box4'];

    echo '

'.$titlu_slider.'

"'.$desc_slider.'"

';

Some help needed..thanx.

Body:
You are missing a few things in your query. Specifically related to the fields that link the tables. To do these joins the best practice is to name each table and then use that name to in an ON statement to JOIN the tables

So

SELECT * FROM tours
INNER JOIN tours_review
INNER JOIN tours_overview
WHERE id = ".$_GET['id'].""

Should be:

SELECT * FROM tours AS t
INNER JOIN tours_review AS r ON r.somefield = t.somefield
INNER JOIN tours_overview AS o ON o.somefield = t.somefield
WHERE id = ".$_GET['id'].""

MySQL can't join tables if it doesn't know what is connecting them.


答:
You need to specify how how the tables relate to each other which might look something like the on conditions shown below (which are just guesses)

```
SELECT *
FROM tours t
INNER JOIN tours_review trev <b>ON t.id = trev.tour_id</b>
INNER JOIN tours_overview tovr <b>ON = t.id = tovr.tour_id</b>
WHERE t.id = $whatever
```

You then face the issue of what type of join because if you have a tour with no reviews then you probably still want to list it. For that type of relationship you need an "outer join".

```
SELECT *
FROM tours t
<b>LEFT OUTER JOIN</b> tours_review trev ON t.id = trev.tour_id
INNER JOIN tours_overview tovr ON = t.id = tovr.tour_id
WHERE t.id = $whatever
```

If every every tour has an "overview" then that can remain an "inner join"

EDIT: Please note that you need to prefix EVERY column reference with a table name or table alias (I have used table aliases to make the query shorter). If you don't do this your query may fail, e.g. if every table has a column id and you just ask for where id = 123 the query will not know which table to use and the query would error.

Title: join 3 tables with where clause

Body:
You need to specify how how the tables relate to each other which might look something like the on conditions shown below (which are just guesses)

SELECT *
FROM tours t
INNER JOIN tours_review trev ON t.id = trev.tour_id
INNER JOIN tours_overview tovr ON = t.id = tovr.tour_id
WHERE t.id = $whatever

You then face the issue of what type of join because if you have a tour with no reviews then you probably still want to list it. For that type of relationship you need an "outer join".

SELECT *
FROM tours t
LEFT OUTER JOIN tours_review trev ON t.id = trev.tour_id
INNER JOIN tours_overview tovr ON = t.id = tovr.tour_id
WHERE t.id = $whatever

If every every tour has an "overview" then that can remain an "inner join"

EDIT: Please note that you need to prefix EVERY column reference with a table name or table alias (I have used table aliases to make the query shorter). If you don't do this your query may fail, e.g. if every table has a column id and you just ask for where id = 123 the query will not know which table to use and the query would error.


问:
Is iOS App Store Over-The-Air download limit based on 'Download Size' or 'Install Size'?
I don't want to lose app installs on cellular due to the 100MB Over-The-Air download limit on App Store.

In this way, before I submit an app update to the App Store I always check the App Store File Sizes section of the current build in iTunes Connect to ensure the binary size will not exceed the OTA download limit.

Here's what iTunes Connect shows for my last app build, which is already published on the App Store:

and here's what the App Store shows on my iPhone 5S device:

Given this, I may assume the 'Size' field displayed on the App Store refers to the App 'Install Size'.

Does Apple apply the OTA download limit based on the 'Install Size' (which is displayed to users on the App Store page as 'Size') or the 'Download Size' shown in the App Store File Sizes of iTunes Connect?

答:
Apple has increased the cellular download limit from 100 MB to 150 MB, letting customers download more apps from the App Store over their cellular network.

apple


问:
Moment.js locale change not working?
I'm trying to set the Moment.js default locale to match the browser locale in an Angular application.

I have followed the steps for Typescript as stated here in the docs. This is my code in the main.ts

```<code>import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

import * as moment from 'moment';
import 'moment/locale/es';

if (environment.production) {
  enableProdMode();
}

moment.locale(navigator.language);

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));
</code>```

navigator.language will default to es here because the settings of my browser but I've also tried to set it to es manually.

Later in my code I tried to console.log(moment.locale()) and it prints es so I though that all was working. Also when I try to get the week days using moment.weekDaysShort() I'm getting the names translated to the es locale but not in the correct order. The week should start on Monday but the first value of weekDays is Sunday.

Any idea on what am I doing wrong? Thanks.

答:
The week should start on Monday but the first value of weekDays is Sunday.

That is not what the moment / contributor team thinks.

Source will set you free

https://github.com/moment/moment/blob/4caa268356434f3ae9b5041985d62a0e8c246c78/locale/es.js#L37

```<code>weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),
weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),
</code>```

Title: Moment.js locale change not working?

Body:
I'm trying to set the Moment.js default locale to match the browser locale in an Angular application.

I have followed the steps for Typescript as stated here in the docs. This is my code in the main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

import * as moment from 'moment';
import 'moment/locale/es';

if (environment.production) {
  enableProdMode();
}

moment.locale(navigator.language);

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

navigator.language will default to es here because the settings of my browser but I've also tried to set it to es manually.

Later in my code I tried to console.log(moment.locale()) and it prints es so I though that all was working. Also when I try to get the week days using moment.weekDaysShort() I'm getting the names translated to the es locale but not in the correct order. The week should start on Monday but the first value of weekDays is Sunday.

Any idea on what am I doing wrong? Thanks.

Body:
The week should start on Monday but the first value of weekDays is Sunday.

That is not what the moment / contributor team thinks.

Source will set you free

https://github.com/moment/moment/blob/4caa268356434f3ae9b5041985d62a0e8c246c78/locale/es.js#L37

weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),
weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),


问:
Installing Lightgbm on Mac with OpenMP dependency
I'm new to python and would like to install lightgbm on my macbook. I did a pip install lightgbm and it said installation successful. However when I try to import that into my notebook I get the following error message:

```<code>../anaconda/envs/python3/lib/python3.6/ctypes/__init__.py in __init__(self, name, mode, handle, use_errno, use_last_error)
342
343         if handle is None:
--> 344             self._handle = _dlopen(self._name, mode)
345         else:
346             self._handle = handle

OSError: dlopen(../anaconda/envs/python3/lib/python3.6/site-packages/lightgbm/lib_lightgbm.so, 6): Library not loaded: /usr/local/opt/gcc/lib/gcc/7/libgomp.1.dylib
Referenced from: ../anaconda/envs/python3/lib/python3.6/site-packages/lightgbm/lib_lightgbm.so
Reason: image not found
</code>```

The documentation on lightgbm website gives a different installation guideline using brew install.... My question is whether I have to do a brew install? If that's the case why the pip installation shows successful installation then?

答:
pip would only install lightgbm python files. The documentation states that lightgbm depends on OpenMP. So you need to install that as well. The problem you are facing is because python cannot find the required "dynamic link library" that comes with OpenMP.

brew install open-mpi and it should fix the problem.

Sidenote: As a quick test, I installed lightgbm the same way you did, and faced the same problem. But I located the libgopm.1.dylib in /usr/local/opt/gcc/lib/gcc/6. Symlinking it to the required path didn't prove to be successful.

Body:
I'm new to python and would like to install lightgbm on my macbook. I did a pip install lightgbm and it said installation successful. However when I try to import that into my notebook I get the following error message:

../anaconda/envs/python3/lib/python3.6/ctypes/__init__.py in __init__(self, name, mode, handle, use_errno, use_last_error)
342
343         if handle is None:
--> 344             self._handle = _dlopen(self._name, mode)
345         else:
346             self._handle = handle

OSError: dlopen(../anaconda/envs/python3/lib/python3.6/site-packages/lightgbm/lib_lightgbm.so, 6): Library not loaded: /usr/local/opt/gcc/lib/gcc/7/libgomp.1.dylib
Referenced from: ../anaconda/envs/python3/lib/python3.6/site-packages/lightgbm/lib_lightgbm.so
Reason: image not found

The documentation on lightgbm website gives a different installation guideline using brew install.... My question is whether I have to do a brew install? If that's the case why the pip installation shows successful installation then?


问:
polylang plugin shows all site pages on one page when switching to second language
I am trying to switch to a second language using polylang plugin in my Wordpress test site.

I don't have relevant code to show, I haven't identified problem code associated with this error.

What I expect is to find myself on the Home page equivalent in the second language no matter which English page I was on previously.

Instead I am taken to the Spanish version of the About page, not Home page equivalent. Also, the page content is made up of not just that page's content but all of the content from every page on the site is stacked on top of each other - including old versions of pages.

If I subsequently click on the Spanish menu which displays as expected, the next page displays perfectly. When I click back to the About page (the page previous acting as a site catch-all) everything is as it should be. So the problem only manifests on the initial switch to a second language.

Switching back to English does not cause the problem to reoccur, everything is fine in this case. It is only when initially switching from English (site primary language) to Spanish that the problem occurs.

I am using the 'X' Wordpress theme for this 'local' version of my site. My Wordpress & free polylang versions are up to date.
Any help with this problem would be much appreciated.
Thanks, Brent.

答:
I have come up with a solution for my problem.
This isn't the most elegant solution but I need something that works now so here goes.

I noticed that when switching to Spanish I was taken to the page: http://localhost/www.ecia.com/es/ i.e. no specific page, fine if I had an index.php file in that location but I don't. The result is I am taken to the page with the bloated content.

My work around was, use a redirection for that URL to the page I want the switcher to go to i.e. instead of http://localhost/www.ecia.com/es - I redirect to http://localhost/www.ecia.com/es/casa

This is not the best fix, but I have found it difficult going any deeper into how Polylang plugin works so it will suffice for my purposes.

Brent