问:
Mandelbrot Sequence with Python's Turtle
I am trying to draw the mandelbrot sequence with python's turtle graphics. I am using two classes, one to represent the mandelbrot sequence.

```<code>class Mandelbrot:
def __init__(self,c,limit=50):
    self.__limit = int(limit)
    self.__colormap = ['black','white']
    self.__cardinality = limit
    z = 0
    for i in range(limit):
        z = z * z + c

        if abs(z) > 2:
            self.__cardinality = i
            return

def getColor(self):
    if self.__cardinality == self.__limit:
        return self.__colormap[0]
    return self.__colormap[1]
</code>```

The other class represents the turtle display.

```<code>import turtle
from mandelbrot import *

class Display:
    def __init__(self):
        self.t = turtle.Turtle()
        self.t.ht();self.t.turtlesize(1)
        self.t.speed(0)
        turtle.tracer(2000,0)

    for x in range(-150,151):
        for y in range(-150,151):
            self.t.color(Mandelbrot(turtleConvert(x,y)).getColor())
            self.t.goto(x,y)

def turtleConvert(x,y): #converts from turtle pixels to the complex plane
    return complex((x/300)*4,(y/300)*4)
</code>```

When I make an instance of the display class, the program runs but only prints the lower half of the fractal. Could anyone provide a solution?

This is a picture of my result.

答:
On my system (OSX), your program produces the entire fractal:

So this may be Python turtle or Tkinter implementation specific.  (Add your system details to your question or as a comment after it.)

I will address a couple of unrelated issues, however.  First, you create a new Mandelbrot instance for every point you plot -- you only need one instance that you invoke as needed:

```<code>class Mandelbrot:
    def __init__(self, limit=50):
        self.__limit = int(limit)
        self.__colormap = ['black', 'white']
        self.__cardinality = self.__limit

    def computeCardinality(self, c):
        z = 0
        self.__cardinality = self.__limit

        for i in range(self.__limit):
            z = z * z + c

            if abs(z) > 2:
                self.__cardinality = i
                return

    def getColor(self):
        if self.__cardinality == self.__limit:
            return self.__colormap[0]
        return self.__colormap[1]
</code>```

Your main program revised to use this mandelbrot.py, and changing your tracer() logic slightly:

```<code>from turtle import Turtle, Screen
from mandelbrot import *

class Display:
    def __init__(self, screen):
        self.t = Turtle(visible=False)
        self.t.speed('fastest')
        screen.tracer(0)

        mandelbrot = Mandelbrot()

        for x in range(-150, 151):
            for y in range(-150, 151):
                mandelbrot.computeCardinality(turtleConvert(x, y))
                self.t.color(mandelbrot.getColor())
                self.t.goto(x, y)
            screen.update()

        screen.tracer(1)

def turtleConvert(x, y):  # converts from turtle pixels to the complex plane
    return complex(x / 75, y / 75)

screen = Screen()
dummy = Display(screen)
screen.mainloop()
</code>```

The second issue is that if you look at the image I generated above, you'll see slight curved lines across it.  You may or may not experience these, again depending on the system you're using.  If you do get these, or simply want to learn about them, see:

Why is turtle lightening pixels?

How do I control turtle's self._newline()?

Body:
I am trying to draw the mandelbrot sequence with python's turtle graphics. I am using two classes, one to represent the mandelbrot sequence.

class Mandelbrot:
def __init__(self,c,limit=50):
    self.__limit = int(limit)
    self.__colormap = ['black','white']
    self.__cardinality = limit
    z = 0
    for i in range(limit):
        z = z * z + c

        if abs(z) > 2:
            self.__cardinality = i
            return

def getColor(self):
    if self.__cardinality == self.__limit:
        return self.__colormap[0]
    return self.__colormap[1]

The other class represents the turtle display.

import turtle
from mandelbrot import *

class Display:
    def __init__(self):
        self.t = turtle.Turtle()
        self.t.ht();self.t.turtlesize(1)
        self.t.speed(0)
        turtle.tracer(2000,0)

    for x in range(-150,151):
        for y in range(-150,151):
            self.t.color(Mandelbrot(turtleConvert(x,y)).getColor())
            self.t.goto(x,y)

def turtleConvert(x,y): #converts from turtle pixels to the complex plane
    return complex((x/300)*4,(y/300)*4)

When I make an instance of the display class, the program runs but only prints the lower half of the fractal. Could anyone provide a solution?

This is a picture of my result.

Body:
On my system (OSX), your program produces the entire fractal:

So this may be Python turtle or Tkinter implementation specific.  (Add your system details to your question or as a comment after it.)

I will address a couple of unrelated issues, however.  First, you create a new Mandelbrot instance for every point you plot -- you only need one instance that you invoke as needed:

class Mandelbrot:
    def __init__(self, limit=50):
        self.__limit = int(limit)
        self.__colormap = ['black', 'white']
        self.__cardinality = self.__limit

    def computeCardinality(self, c):
        z = 0
        self.__cardinality = self.__limit

        for i in range(self.__limit):
            z = z * z + c

            if abs(z) > 2:
                self.__cardinality = i
                return

    def getColor(self):
        if self.__cardinality == self.__limit:
            return self.__colormap[0]
        return self.__colormap[1]

Your main program revised to use this mandelbrot.py, and changing your tracer() logic slightly:

from turtle import Turtle, Screen
from mandelbrot import *

class Display:
    def __init__(self, screen):
        self.t = Turtle(visible=False)
        self.t.speed('fastest')
        screen.tracer(0)

        mandelbrot = Mandelbrot()

        for x in range(-150, 151):
            for y in range(-150, 151):
                mandelbrot.computeCardinality(turtleConvert(x, y))
                self.t.color(mandelbrot.getColor())
                self.t.goto(x, y)
            screen.update()

        screen.tracer(1)

def turtleConvert(x, y):  # converts from turtle pixels to the complex plane
    return complex(x / 75, y / 75)

screen = Screen()
dummy = Display(screen)
screen.mainloop()

The second issue is that if you look at the image I generated above, you'll see slight curved lines across it.  You may or may not experience these, again depending on the system you're using.  If you do get these, or simply want to learn about them, see:

Why is turtle lightening pixels?

How do I control turtle's self._newline()?


来源: stackexchange

问:
Comparing dates in Django does not work
I have a problem comparing dates in Django. I followed the hint How to compare dates in Django but it does not work. Maybe you can help me.

My code:

modelys.py

```<code>class Customer(models.Model):
last_updated = models.DateTimeField(auto_now_add=True)
</code>```

views.py

```<code>@property
def is_past_due(self):
return (date.today() - self.date)> timedelta(1)
</code>```

home.html

```<code>{% if customer.last_updated.is_past_due %}
<td class="table-danger">{{ customer.last_updated }}</td>
{% else %}
<td class="align-middle">{{ customer.last_updated }}</td>
{% endif %}
</code>```

I am using Bootstrap, so when the difference between two dates has a more than one day I want a tablefield to become 'danger'-ous ;-), but nothing changes.

Thanks in advance.

PS: edited the typo in def timdedelta to timedelta.

答:
Here the final code as sumup of the posts:

models.py

```<code>from datetime import datetime

class Customer(models.Model):
last_updated = models.DateTimeField(auto_now_add=True)
#...some more code...
    @property
    def is_past_due(self):
        return (datetime.now(timezone.utc) - self.last_updated).days>1
</code>```

home.html

```<code>{% if customer.is_past_due %}
<td class="align-middle table-danger">{{ customer.last_updated.date}}</td>
{% else %}
<td class="align-middle">{{ customer.last_updated}}</td>
{% endif %}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Comparing dates in Django does not work

Body:
I have a problem comparing dates in Django. I followed the hint How to compare dates in Django but it does not work. Maybe you can help me.

My code:

modelys.py

class Customer(models.Model):
last_updated = models.DateTimeField(auto_now_add=True)

views.py

@property
def is_past_due(self):
return (date.today() - self.date)> timedelta(1)

home.html

{% if customer.last_updated.is_past_due %}
{{ customer.last_updated }}
{% else %}
{{ customer.last_updated }}
{% endif %}

I am using Bootstrap, so when the difference between two dates has a more than one day I want a tablefield to become 'danger'-ous ;-), but nothing changes.

Thanks in advance.

PS: edited the typo in def timdedelta to timedelta.

Body:
Here the final code as sumup of the posts:

models.py

from datetime import datetime

class Customer(models.Model):
last_updated = models.DateTimeField(auto_now_add=True)
#...some more code...
    @property
    def is_past_due(self):
        return (datetime.now(timezone.utc) - self.last_updated).days>1

home.html

{% if customer.is_past_due %}
<td class="align-middle table-danger">{{ customer.last_updated.date}}</td>
{% else %}
<td class="align-middle">{{ customer.last_updated}}</td>
{% endif %}


问:
How to create pie chart in iPhone?
I want to show pie chart of my category by percentage.

How can I create pie chart of category percentage ?

答:
This might be helpful with the warning that if it looks like someone else's code, it's because I worked out how to do it with web sites, and the additional warning that I did this not long after starting iPhone. People who want to tell me which bits are inefficient or wrong are welcome, I'm still learning. </p>

```<code>static inline float radians(double degrees) { return degrees * M_PI / 180; }

// making a simple pac man shape
- (UIImage*)getImage {

    UIImage* image;
    if(self.completion == 100.0f) {
        image = [UIImage imageNamed:@"completedTaskIcon.png"];
    } else {
        UIGraphicsBeginImageContext(CGSizeMake(SIDELENGTH, SIDELENGTH));

        CGContextRef context = UIGraphicsGetCurrentContext();

        // the image should have a clear background
        [[UIColor clearColor] set];
        CGRect myRect = CGRectMake(0.0f, 0.0f, SIDELENGTH, SIDELENGTH);
        UIRectFill(myRect);

        // color was hopefully set before this method called
        [self.color set];

        // centre point is required
        CGFloat midx = SIDELENGTH/2;
        CGFloat midy = SIDELENGTH/2;
        // radius of the arc
        CGFloat radius = (SIDELENGTH/2) * 0.60f;

        // pie background
        CGContextSetFillColor(context, CGColorGetComponents([[UIColor orangeColor] CGColor]));
        CGContextBeginPath(context);
        CGContextMoveToPoint(context, midx + radius, midy);
        CGContextAddArc(context, midx, midy, radius,  radians(0), radians(360), 0);
        CGContextFillPath(context);

        // pie segment
        CGContextSetFillColor(context, CGColorGetComponents([[UIColor blueColor] CGColor]));
        CGContextBeginPath(context);
        CGContextMoveToPoint(context, midx, midy);
        CGContextAddLineToPoint(context, midx + radius, midy);
        CGContextAddArc(context, midx, midy, radius,  radians(0), radians(360 * (self.completion / 100.0f)), 0);
        CGContextFillPath(context);
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

    return image;
}
</code>```

Title: How to create pie chart in iPhone?

Body:
This might be helpful with the warning that if it looks like someone else's code, it's because I worked out how to do it with web sites, and the additional warning that I did this not long after starting iPhone. People who want to tell me which bits are inefficient or wrong are welcome, I'm still learning.

static inline float radians(double degrees) { return degrees * M_PI / 180; }

// making a simple pac man shape
- (UIImage*)getImage {

    UIImage* image;
    if(self.completion == 100.0f) {
        image = [UIImage imageNamed:@"completedTaskIcon.png"];
    } else {
        UIGraphicsBeginImageContext(CGSizeMake(SIDELENGTH, SIDELENGTH));

        CGContextRef context = UIGraphicsGetCurrentContext();

        // the image should have a clear background
        [[UIColor clearColor] set];
        CGRect myRect = CGRectMake(0.0f, 0.0f, SIDELENGTH, SIDELENGTH);
        UIRectFill(myRect);

        // color was hopefully set before this method called
        [self.color set];

        // centre point is required
        CGFloat midx = SIDELENGTH/2;
        CGFloat midy = SIDELENGTH/2;
        // radius of the arc
        CGFloat radius = (SIDELENGTH/2) * 0.60f;

        // pie background
        CGContextSetFillColor(context, CGColorGetComponents([[UIColor orangeColor] CGColor]));
        CGContextBeginPath(context);
        CGContextMoveToPoint(context, midx + radius, midy);
        CGContextAddArc(context, midx, midy, radius,  radians(0), radians(360), 0);
        CGContextFillPath(context);

        // pie segment
        CGContextSetFillColor(context, CGColorGetComponents([[UIColor blueColor] CGColor]));
        CGContextBeginPath(context);
        CGContextMoveToPoint(context, midx, midy);
        CGContextAddLineToPoint(context, midx + radius, midy);
        CGContextAddArc(context, midx, midy, radius,  radians(0), radians(360 * (self.completion / 100.0f)), 0);
        CGContextFillPath(context);
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

    return image;
}

ContentLicense: CC BY-SA 2.5


问:
PayPal 401 Unauthorized with credit card payment in live production using .NET REST API for Express checkout API
I'm using .NET REST API for PayPal Express Checkout for direct credit card payment. When I use sandbox, I create Payment, set credit card as funding instrument, billing address and payment works fine.
But when I switch to live, calling Payment.Create(apiContext) with the exactly same data throws PayPal.IdentityException with 401-Unauthorized message. However, at that time I have valid access token.
Calling regular PayPal payment works fine either using live environmnet.

Thanks for any suggestions.

答:
I found a solution to this problem. It is necessary to determine sdkConfig in apiContext.</p>

```<code>        var sdkConfig = new Dictionary<string, string> { { "mode", "live" } };
        string accessToken = new OAuthTokenCredential(id, secret, sdkConfig).GetAccessToken();

        var apiContext = new APIContext(accessToken);
        apiContext.Config = sdkConfig;
</code>```

Body:
I found a solution to this problem. It is necessary to determine sdkConfig in apiContext.

        var sdkConfig = new Dictionary<string, string> { { "mode", "live" } };
        string accessToken = new OAuthTokenCredential(id, secret, sdkConfig).GetAccessToken();

        var apiContext = new APIContext(accessToken);
        apiContext.Config = sdkConfig;


问:
Should I commit the .vscode folder to source control?
Is the .vscode folder meant to be committed to source control?

In a fresh project, the folder is empty, except the settings.json file. What kind of things would go into this folder? Is it machine-specific, developer-specific like the .vs folder and thus not be committed? Or should all developers share this folder and thus it should be committed?

The comment at the top of the file .vscode/settings.json states:

```<code>// Place your settings in this file to overwrite default and user settings.
{
}
</code>```

This seems to imply that the folder should contain project-specific settings and thus be included in source. Also, this post on UserVoice seems to imply some typings would go in there, also suggesting that it should be committed.

答:
never commit .vscode/settings.json - with the weird exception of search.exclude . If you really need to, be very careful of putting only settings particular of your project that you want to enforce to other developers.

for validation, formatting, compilation use other files like package.json, .eslint, tsconfig.json, etc

The only .vscode that makes sense to include are complex launch configs for debugging.

Be careful, there could be a third party extension in your system that could put private information there !

What you can't do is copy & paste the whole settings.json contents file to .vscode/settings.json. I'm seeing some people doing this and committing the file is an atrocity. In that case you will not only break others workspace but worst, you will be enforcing settings to users that you shouldn't like aesthetics, UI, experience. You probably will break their environments because some are very system dependent. Imagine I have vision problems so my editor.* user settings are personalize and when I open your project the visuals change...

Summary: If you are serious don't commit .vscode/settings.json. In general, settings that could be useful for a particular project like validation, compilation, makes sense but in general you can use particular tools configuration files like .eslint, tsconfig.json, .gitignore, package.json. etc. I guess vscode authors just added the file for simplifying newcomer experience but if you want to be serious don't!

Body:
Is the .vscode folder meant to be committed to source control?

In a fresh project, the folder is empty, except the settings.json file. What kind of things would go into this folder? Is it machine-specific, developer-specific like the .vs folder and thus not be committed? Or should all developers share this folder and thus it should be committed?

The comment at the top of the file .vscode/settings.json states:

// Place your settings in this file to overwrite default and user settings.
{
}

This seems to imply that the folder should contain project-specific settings and thus be included in source. Also, this post on UserVoice seems to imply some typings would go in there, also suggesting that it should be committed.

ContentLicense: CC BY-SA 4.0


问:
How to pass multiple ArrayList to BaseAdapter in Android?
I am trying to pass some dynamic data to BaseAdapter to display it on listview .(using ArrayList),My current code gives me following error:

Error:

```<code>error: cannot find symbol variable ArrayList
error: cannot find symbol variable String
</code>```

Pointing to this part of code(ArrayList < String >):

```<code>CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);
</code>```

I check the Arraylist size and foundout that IconArrayList and NameArrayList are not empty using int itemCount = IconArrayList.size();

However If i pass following static string array to Baseadapter then it displays the data on listview!

```<code>String NameArrayList[] = {"USA", "China", "australia", "Portugle", "Norway", "NewZealand"};
String IconArrayList[] = {"http://awebsite.com/icons/usa.png", "http://awebsite.com/icons/china.png", "http://awebsite.com/icons/australia.png", "http://awebsite.com/icons/portugle.png", "http://awebsite.com/icons/norway.png", "http://awebsite.com/icons/new_zealand.png"};

CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), NameArrayList, IconArrayList);
</code>```

Could you guys help me fix above errors and pass arraylist successfully to baseAdapter so it displays it.Thanks in advance.

MainActivity.java:

```<code>import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy.Builder;

import java.io.InputStreamReader;

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.io.BufferedReader;

import java.util.ArrayList;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sendGetRequest();

     }

public String sendGetRequest() {

         String NEW_ICON = "icon";

        ArrayList<String> IconArrayList =new ArrayList<String>();
        ArrayList<String> NameArrayList =new ArrayList<String>();
        ArrayList<String> UrlArrayList =new ArrayList<String>();

        try {

            StrictMode.setThreadPolicy(new Builder().permitAll().build());

            HttpURLConnection myURLConnection = (HttpURLConnection) new URL("http://awebsite.com/test/test.php").openConnection();

            myURLConnection.setReadTimeout(60000);
            myURLConnection.setConnectTimeout(60000);
            myURLConnection.setRequestMethod("GET");
            myURLConnection.setUseCaches(false);
            myURLConnection.setDoInput(true);
            myURLConnection.setDoOutput(true);
            myURLConnection.setRequestProperty("Content-Type", "html");
            myURLConnection.setRequestProperty("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 6.0;)");

            OutputStream os = myURLConnection.getOutputStream();

            os.close();

            myURLConnection.connect();

            BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));

            StringBuffer sb = new StringBuffer();

            String line;

            while ((line = in.readLine()) != null) {

                sb.append(line);
                sb.append("\\n");
            }
            in.close();

            String linesArray[] = sb.toString().split("#MYLIST:");

            for (int i = 0; i < linesArray.length; i++) {
                String currLine = linesArray[i];

                String[] dataArray = currLine.split(",");

                if (dataArray[0].contains(NEW_ICON)) {

                   String s =dataArray[0];

                    s = s.substring(s.indexOf("(") + 1);
                    s = s.substring(0, s.indexOf(")"));

                    IconArrayList.add(s);

                    if (dataArray[1].contains("http://")) {
                        String[] split = dataArray[1].split("http://");
                        String name = split[0];
                        String url = split[1];
                        url ="http://"+url;

                        //adding name and url to arraylist
                        NameArrayList.add(name);
                        UrlArrayList.add(url);
                      }

                }

            }// end of for loop

            //showing array list total
            int itemCount = IconArrayList.size();
            int itemCount2 = NameArrayList.size();
            int itemCount3 = UrlArrayList.size();

            ListView simpleList;
            simpleList = (ListView) findViewById(R.id.simpleListView);
            CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);
            simpleList.setAdapter(customAdapter);

        } catch (Exception e) {

        }
        return null;

    }
</code>```

BaseAdapter:

```<code>public class CustomAdapter extends BaseAdapter {
    Context context;
    String countryList[];

    String flags[];

    LayoutInflater inflter;

    public CustomAdapter(Context applicationContext, String[] countryList, String[] flags) {
        this.context = context;
        this.countryList = countryList;
        this.flags = flags;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return countryList.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.activity_listview, null);
        TextView country = (TextView) view.findViewById(R.id.textView);
        ImageView icon = (ImageView) view.findViewById(R.id.icon);
        country.setText(countryList[i]);

        Picasso.with(view.getContext())
                .load(flags[i])
                //.resize(50,50)
                .into(icon);

        return view;
    }
}
</code>```

答:
This is not the way to pass multiple properties to any class . Instead of it you should use a POJO class. Below is an example .

```<code>class CountryModel{
    public String countryName;
    public String countryFlag;

    public CountryModel(String countryName, String countryFlag) {
        this.countryName = countryName;
        this.countryFlag = countryFlag;
    }
}
</code>```

Then parse your data into a collection of this model objects.Below is an example.

```<code> ArrayList<CountryModel> countryList=new ArrayList<>();
 countryList.add(new CountryModel("Norway","NorwayflagUrl"));
 countryList.add(new CountryModel("Iceland","IcelandflagUrl"));
 countryList.add(new CountryModel("Denmark","DenmarkflagUrl"));
</code>```

Then set the adapter. In this case you need to modify your adapter.

```<code>ListView simpleList = (ListView) findViewById(R.id.simpleListView);
        CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), countryList);
        simpleList.setAdapter(customAdapter);
</code>```

You can modify your adapter as below.

```<code> public class CustomAdapter extends BaseAdapter {
    Context context;
   ArrayList<CountryModel> countryList;

    LayoutInflater inflter;

    public CustomAdapter(Context applicationContext, ArrayList<CountryModel> countryList) {
        this.context = context;
        this.countryList = countryList;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return countryList.size();
    }

    @Override
    public Object getItem(int i) {
        return countryList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.activity_listview, null);
        TextView country = (TextView) view.findViewById(R.id.textView);
        ImageView icon = (ImageView) view.findViewById(R.id.icon);
        country.setText(countryList.get(i).countryName);

        Picasso.with(view.getContext())
                .load(countryList.get(i).countryFlag)
                //.resize(50,50)
                .into(icon);
        return view;
    }
}
</code>```

Body:
I am trying to pass some dynamic data to BaseAdapter to display it on listview .(using ArrayList),My current code gives me following error:

Error:

error: cannot find symbol variable ArrayList
error: cannot find symbol variable String

Pointing to this part of code(ArrayList < String >):

CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);

I check the Arraylist size and foundout that IconArrayList and NameArrayList are not empty using int itemCount = IconArrayList.size();

However If i pass following static string array to Baseadapter then it displays the data on listview!

String NameArrayList[] = {"USA", "China", "australia", "Portugle", "Norway", "NewZealand"};
String IconArrayList[] = {"http://awebsite.com/icons/usa.png", "http://awebsite.com/icons/china.png", "http://awebsite.com/icons/australia.png", "http://awebsite.com/icons/portugle.png", "http://awebsite.com/icons/norway.png", "http://awebsite.com/icons/new_zealand.png"};

CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), NameArrayList, IconArrayList);

Could you guys help me fix above errors and pass arraylist successfully to baseAdapter so it displays it.Thanks in advance.

MainActivity.java:

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy.Builder;

import java.io.InputStreamReader;

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.OutputStream;
import java.io.BufferedReader;

import java.util.ArrayList;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sendGetRequest();

     }

public String sendGetRequest() {

         String NEW_ICON = "icon";

        ArrayList<String> IconArrayList =new ArrayList<String>();
        ArrayList<String> NameArrayList =new ArrayList<String>();
        ArrayList<String> UrlArrayList =new ArrayList<String>();

        try {

            StrictMode.setThreadPolicy(new Builder().permitAll().build());

            HttpURLConnection myURLConnection = (HttpURLConnection) new URL("http://awebsite.com/test/test.php").openConnection();

            myURLConnection.setReadTimeout(60000);
            myURLConnection.setConnectTimeout(60000);
            myURLConnection.setRequestMethod("GET");
            myURLConnection.setUseCaches(false);
            myURLConnection.setDoInput(true);
            myURLConnection.setDoOutput(true);
            myURLConnection.setRequestProperty("Content-Type", "html");
            myURLConnection.setRequestProperty("User-Agent", "Dalvik/2.1.0 (Linux; U; Android 6.0;)");

            OutputStream os = myURLConnection.getOutputStream();

            os.close();

            myURLConnection.connect();

            BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));

            StringBuffer sb = new StringBuffer();

            String line;

            while ((line = in.readLine()) != null) {

                sb.append(line);
                sb.append("\\n");
            }
            in.close();

            String linesArray[] = sb.toString().split("#MYLIST:");

            for (int i = 0; i < linesArray.length; i++) {
                String currLine = linesArray[i];

                String[] dataArray = currLine.split(",");

                if (dataArray[0].contains(NEW_ICON)) {

                   String s =dataArray[0];

                    s = s.substring(s.indexOf("(") + 1);
                    s = s.substring(0, s.indexOf(")"));

                    IconArrayList.add(s);

                    if (dataArray[1].contains("http://")) {
                        String[] split = dataArray[1].split("http://");
                        String name = split[0];
                        String url = split[1];
                        url ="http://"+url;

                        //adding name and url to arraylist
                        NameArrayList.add(name);
                        UrlArrayList.add(url);
                      }

                }

            }// end of for loop

            //showing array list total
            int itemCount = IconArrayList.size();
            int itemCount2 = NameArrayList.size();
            int itemCount3 = UrlArrayList.size();

            ListView simpleList;
            simpleList = (ListView) findViewById(R.id.simpleListView);
            CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), ArrayList<String> NameArrayList, ArrayList<String> IconArrayList);
            simpleList.setAdapter(customAdapter);

        } catch (Exception e) {

        }
        return null;

    }

BaseAdapter:

public class CustomAdapter extends BaseAdapter {
    Context context;
    String countryList[];

    String flags[];

    LayoutInflater inflter;

    public CustomAdapter(Context applicationContext, String[] countryList, String[] flags) {
        this.context = context;
        this.countryList = countryList;
        this.flags = flags;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return countryList.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.activity_listview, null);
        TextView country = (TextView) view.findViewById(R.id.textView);
        ImageView icon = (ImageView) view.findViewById(R.id.icon);
        country.setText(countryList[i]);

        Picasso.with(view.getContext())
                .load(flags[i])
                //.resize(50,50)
                .into(icon);

        return view;
    }
}

Body:
This is not the way to pass multiple properties to any class . Instead of it you should use a POJO class. Below is an example .

class CountryModel{
    public String countryName;
    public String countryFlag;

    public CountryModel(String countryName, String countryFlag) {
        this.countryName = countryName;
        this.countryFlag = countryFlag;
    }
}

Then parse your data into a collection of this model objects.Below is an example.

 ArrayList<CountryModel> countryList=new ArrayList<>();
 countryList.add(new CountryModel("Norway","NorwayflagUrl"));
 countryList.add(new CountryModel("Iceland","IcelandflagUrl"));
 countryList.add(new CountryModel("Denmark","DenmarkflagUrl"));

Then set the adapter. In this case you need to modify your adapter.

ListView simpleList = (ListView) findViewById(R.id.simpleListView);
        CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), countryList);
        simpleList.setAdapter(customAdapter);

You can modify your adapter as below.

 public class CustomAdapter extends BaseAdapter {
    Context context;
   ArrayList<CountryModel> countryList;

    LayoutInflater inflter;

    public CustomAdapter(Context applicationContext, ArrayList<CountryModel> countryList) {
        this.context = context;
        this.countryList = countryList;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return countryList.size();
    }

    @Override
    public Object getItem(int i) {
        return countryList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.activity_listview, null);
        TextView country = (TextView) view.findViewById(R.id.textView);
        ImageView icon = (ImageView) view.findViewById(R.id.icon);
        country.setText(countryList.get(i).countryName);

        Picasso.with(view.getContext())
                .load(countryList.get(i).countryFlag)
                //.resize(50,50)
                .into(icon);
        return view;
    }
}


问:
Visual Studio 2010 - recommended extensions
What are your recommended extensions for Visual Studio 2010?
(Please indicate if its free or not And also its purpose / function too)</p>

答:
This is my list of extensions.

The list on this is pretty comprehensive, so I spent sometime to find the extensions that I need. Here is the snapshot. Hope it will help someone.

I tried installing Codemaid, and it appeared to be a nifty addon, but my Visual Studio response became very slow. Felt like some threads were doing some work all the time when Codemaid was on.
So uninstalling for now.


问:
MSVC 2017 15.5.0 - vertical block guide lines
Just updated my MSVC 2017 to version 15.5.0 and noticed that in C++ files there is now a vertical dashed line connecting open/close bracers. Before now I've seen similar in C# files but didn't care as much.

Now, however, when this feature is auto-enabled for C++ files as well it drives me nuts. I hate this with passion yet can't find a way to disable it.

Anyone knows how to not show those vertical block guide lines for C++ files?

N.B. I'm posting this question in this section of the site because it matches it the most. Even though this is not strictly speaking a "code" question but it is an IDE question so I feel it belongs here.

If it doesn't - let me know where should this question be posted and I'll move it there.

答: Disable Show structure guide lines in Text Editor->General->Display seciton.


问:
How to render pdf from angular io (5) sites with phantomjs
I just put some image and try to render pdf:

```<code>phantom.create().then(async function(ph) {
    let page = await ph.createPage();
    let status = await page.open("http://localhost:4000")
    await page.render('file.pdf');
    ph.exit();
});
</code>```

But i get blank pdf file.

I also try

```<code>page.onLoadFinished
</code>```

But it is never income to it.

I also try:

```<code> await new Promise(resolve => setTimeout(() => resolve(), 10000));
</code>```

But nothing.

答:
I solved this issue by running phantom alone, and figure out that i need to uncomment this lines in polyfills:</p>

```<code>/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
</code>```

Body:
I just put some image and try to render pdf:

phantom.create().then(async function(ph) {
    let page = await ph.createPage();
    let status = await page.open("http://localhost:4000")
    await page.render('file.pdf');
    ph.exit();
});

But i get blank pdf file.

I also try

page.onLoadFinished

But it is never income to it.

I also try:

 await new Promise(resolve => setTimeout(() => resolve(), 10000));

But nothing.

Body:
I solved this issue by running phantom alone, and figure out that i need to uncomment this lines in polyfills:

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';


问:
Loops logic not working as expected in java selenium
I want to check whether value which is passed is matching the value in if loop and if its matching then it should execute the code which is in if loop. What happens is everytime I run it selects only first value and doesn't check for the other values. I am unable to figure out whats wrong with my logic. Below is my code

```<code>for (int i = 0; i < stageListOfFilters.size(); i++) {
                System.out.println(stageListOfFilters.get(i).getText());

                if (finalSnapshot1.toString().equals(stageListOfFilters.get(i).getText())) {

                    driver.findElement(By.xpath(".//*[@id='DS']/div/div/div[1]/div[" + i + "]/div[1]")).click();

                    System.out.println("Value of i: " + i);
                    Thread.sleep(2000);
                }
            }
</code>```

Do let me know if any additional information is required. For more details please go through this  link.

Below you can see the list of snapshot date filter and the css corresponding to it. Now i want to click on the matching title. How can i do it ?

I tried below code for getting data from title attribute but gives null values:

```<code>stageListOfFilters = driver.findElements(By.xpath(".//*[@id='DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop

            for (WebElement element : stageListOfFilters) {
                System.out.println("Dates are: " + element.getAttribute("title"));
            }
</code>```

答:
I was not able to select the proper xpath of the date list. I solved it now and below is my working code which fulfills my expectations.

```<code>try {
            Date varDate = dateFormat.parse("01-Sep-2017");
            dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 2017-08-18
            finalSnapshot1 = dateFormat.format(varDate).toString();
            System.out.println("Date: " + finalSnapshot1); // Prints 2017-08-18
            driver.findElement(By.xpath(config.getsnapshotFilter())).click();
            Thread.sleep(2000);

            stageListOfFilters = driver
                    .findElements(By.xpath("(//*[@class='QvFrame DS'])[1]/div/div/div[1]/child::div")); // This collects
                                                                                // the list
            // of dates which is
            // fetched later on in
            // for loop
            System.out.println("Size" + stageListOfFilters.size());
            Thread.sleep(2000);
            for (int i = 1; i < stageListOfFilters.size(); i++) {

                if (finalSnapshot1.equals(stageListOfFilters.get(i).getText())) {
                    System.out.println("Filters list value: " + stageListOfFilters.get(i).getText());
                    System.out.println("Value to be compared: " + finalSnapshot1);
                    i = i + 1;
                    driver.findElement(By.xpath(".//*[@class='QvFrame DS']/div/div/div[1]/div[" + i + "]/div[1]"))
                            .click();
                    System.out.println("Value of i: " + i +" and Date is: "+ finalSnapshot1.toString());
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
</code>```

Thanks everyone for your help. I solved it finally after 21 days. LOL !

Body:
I want to check whether value which is passed is matching the value in if loop and if its matching then it should execute the code which is in if loop. What happens is everytime I run it selects only first value and doesn't check for the other values. I am unable to figure out whats wrong with my logic. Below is my code

for (int i = 0; i < stageListOfFilters.size(); i++) {
                System.out.println(stageListOfFilters.get(i).getText());

                if (finalSnapshot1.toString().equals(stageListOfFilters.get(i).getText())) {

                    driver.findElement(By.xpath(".//*[@id='DS']/div/div/div[1]/div[" + i + "]/div[1]")).click();

                    System.out.println("Value of i: " + i);
                    Thread.sleep(2000);
                }
            }

Do let me know if any additional information is required. For more details please go through this  link.

Below you can see the list of snapshot date filter and the css corresponding to it. Now i want to click on the matching title. How can i do it ?

I tried below code for getting data from title attribute but gives null values:

stageListOfFilters = driver.findElements(By.xpath(".//*[@id='DS']")); // This collects the list
                                                                                // of dates which is
                                                                                // fetched later on in
                                                                                // for loop

            for (WebElement element : stageListOfFilters) {
                System.out.println("Dates are: " + element.getAttribute("title"));
            }

Body:
I was not able to select the proper xpath of the date list. I solved it now and below is my working code which fulfills my expectations.

try {
            Date varDate = dateFormat.parse("01-Sep-2017");
            dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 2017-08-18
            finalSnapshot1 = dateFormat.format(varDate).toString();
            System.out.println("Date: " + finalSnapshot1); // Prints 2017-08-18
            driver.findElement(By.xpath(config.getsnapshotFilter())).click();
            Thread.sleep(2000);

            stageListOfFilters = driver
                    .findElements(By.xpath("(//*[@class='QvFrame DS'])[1]/div/div/div[1]/child::div")); // This collects
                                                                                // the list
            // of dates which is
            // fetched later on in
            // for loop
            System.out.println("Size" + stageListOfFilters.size());
            Thread.sleep(2000);
            for (int i = 1; i < stageListOfFilters.size(); i++) {

                if (finalSnapshot1.equals(stageListOfFilters.get(i).getText())) {
                    System.out.println("Filters list value: " + stageListOfFilters.get(i).getText());
                    System.out.println("Value to be compared: " + finalSnapshot1);
                    i = i + 1;
                    driver.findElement(By.xpath(".//*[@class='QvFrame DS']/div/div/div[1]/div[" + i + "]/div[1]"))
                            .click();
                    System.out.println("Value of i: " + i +" and Date is: "+ finalSnapshot1.toString());
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

Thanks everyone for your help. I solved it finally after 21 days. LOL !


问:
How to make dynamic positions in Spritkit in Swift
I only have a scene with following variables:

```<code>widthOfScene = self.size.width
heightOfScene = self.size.height
var constLabelPosition = CGPoint(x:witdhOfScene*0.6, y: heightOfScene*0.95)
var dynamLabelPosition = CGPoint(x: constLabelPosition.x * 0.1, y: constLabelPosition.y)
</code>```

I want my dynamLabel to be just always 10% right of my constLabel even if I decide to change the constLabelPosition in a few months.
My code is not working. dynamLabel is always just in the middle of the constLabel...is there a way to implement such dynamic label position?

答:
I'm sorry, but this seems like a simple miscalculation of x position of  dynamicLabelPosition.

You sure you didn't mean :

```<code>var dynamLabelPosition = CGPoint(x: constLabelPosition.x + constLabelPosition.x * 0.1, y: constLabelPosition.y)
</code>```

Body:
I only have a scene with following variables:

widthOfScene = self.size.width
heightOfScene = self.size.height
var constLabelPosition = CGPoint(x:witdhOfScene*0.6, y: heightOfScene*0.95)
var dynamLabelPosition = CGPoint(x: constLabelPosition.x * 0.1, y: constLabelPosition.y)

I want my dynamLabel to be just always 10% right of my constLabel even if I decide to change the constLabelPosition in a few months.
My code is not working. dynamLabel is always just in the middle of the constLabel...is there a way to implement such dynamic label position?

Body:
I'm sorry, but this seems like a simple miscalculation of x position of  dynamicLabelPosition.

You sure you didn't mean :

var dynamLabelPosition = CGPoint(x: constLabelPosition.x + constLabelPosition.x * 0.1, y: constLabelPosition.y)


问:
Dagger with Mvp on Kotlin - Android
I am an Android developer that is just getting into Kotlin, and I have been trying to setup an Mvp Dagger application in Kotlin, but I cannot figure out what is going on.  I continue to get this error:

```<code>Error:dagger.internal.codegen.ComponentProcessor was unable to process this interface
because not all of its dependencies could be resolved.
Check for compilation errors or a circular dependency with generated code.
</code>```

Here is my code:

KotlinApplication:

```<code>class KotlinApplication: MultiDexApplication(), HasActivityInjector {

    @Inject lateinit var injector: DispatchingAndroidInjector<Activity>

    override fun onCreate() {
        super.onCreate()
        inject()
    }

    override fun activityInjector(): AndroidInjector<Activity> {
        return injector
    }

    fun inject() {
        DaggerAppComponent.builder().application(this).build().inject(this);
    }

}
</code>```

AppComponent:

```<code>@Singleton
@Component(modules = arrayOf(AppModule::class, InjectionModule::class))
interface AppComponent {

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(app: KotlinApplication): Builder

        fun build(): AppComponent
    }

    fun inject(app: KotlinApplication)

}
</code>```

AppModule:

```<code>@Module
class AppModule {
    @Singleton
    @Provides
    fun provideAppContext(app: KotlinApplication): Context {
        return app
    }

    @Singleton
    @Provides
    fun provideApplication(app: KotlinApplication): Application {
        return app
    }
}
</code>```

InjectionModule:

```<code>@Module
abstract class InjectionModule {

    @ActivityScope
    @ContributesAndroidInjector(modules = arrayOf(MainModule::class))
    internal abstract fun bindMainActivity(): MainActivity

}
</code>```

MainActivity:

```<code>class MainActivity : AppCompatActivity(), MainMvp.View {

    @Inject lateinit var presenter: MainMvp.Presenter

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
</code>```

MainMvp:

```<code>interface MainMvp {
    interface View {

    }

    interface Presenter {

    }
}
</code>```

MainPresenter:

```<code>class MainPresenter(view: MainMvp.View): MainMvp.Presenter {

    var view: MainMvp.View

    init {
        this.view = view
    }

}
</code>```

MainBindModule:

```<code>@Module
interface MainBindModule {
    @ActivityScope
    @Binds
    fun bindView(activity: MainActivity): MainMvp.View
}
</code>```

MainModule:

```<code>@Module(includes = arrayOf(MainBindModule::class))
class MainModule {

    @ActivityScope
    @Provides
    fun providePresenter(view: MainMvp.View): MainMvp.Presenter {
        return MainPresenter(view)
    }

}
</code>```

And finally, ActivityScope:

```<code>@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityScope
</code>```

Does anyone know what might be wrong? I have used the same exact Architectural pattern in java several times before, and I have never ran into this error before.

Also, when I comment out everything inside of InjectionModule, everything works

答:
With Reference to Official Dagger2 issue page

It says:

This is a gradle issue, not a dagger one.

Try clean/re-build your project

Title: Dagger with Mvp on Kotlin - Android

Body:
I am an Android developer that is just getting into Kotlin, and I have been trying to setup an Mvp Dagger application in Kotlin, but I cannot figure out what is going on.  I continue to get this error:

Error:dagger.internal.codegen.ComponentProcessor was unable to process this interface
because not all of its dependencies could be resolved.
Check for compilation errors or a circular dependency with generated code.

Here is my code:

KotlinApplication:

class KotlinApplication: MultiDexApplication(), HasActivityInjector {

    @Inject lateinit var injector: DispatchingAndroidInjector<Activity>

    override fun onCreate() {
        super.onCreate()
        inject()
    }

    override fun activityInjector(): AndroidInjector<Activity> {
        return injector
    }

    fun inject() {
        DaggerAppComponent.builder().application(this).build().inject(this);
    }

}

AppComponent:

@Singleton
@Component(modules = arrayOf(AppModule::class, InjectionModule::class))
interface AppComponent {

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(app: KotlinApplication): Builder

        fun build(): AppComponent
    }

    fun inject(app: KotlinApplication)

}

AppModule:

@Module
class AppModule {
    @Singleton
    @Provides
    fun provideAppContext(app: KotlinApplication): Context {
        return app
    }

    @Singleton
    @Provides
    fun provideApplication(app: KotlinApplication): Application {
        return app
    }
}

InjectionModule:

@Module
abstract class InjectionModule {

    @ActivityScope
    @ContributesAndroidInjector(modules = arrayOf(MainModule::class))
    internal abstract fun bindMainActivity(): MainActivity

}

MainActivity:

class MainActivity : AppCompatActivity(), MainMvp.View {

    @Inject lateinit var presenter: MainMvp.Presenter

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

MainMvp:

interface MainMvp {
    interface View {

    }

    interface Presenter {

    }
}

MainPresenter:

class MainPresenter(view: MainMvp.View): MainMvp.Presenter {

    var view: MainMvp.View

    init {
        this.view = view
    }

}

MainBindModule:

@Module
interface MainBindModule {
    @ActivityScope
    @Binds
    fun bindView(activity: MainActivity): MainMvp.View
}

MainModule:

@Module(includes = arrayOf(MainBindModule::class))
class MainModule {

    @ActivityScope
    @Provides
    fun providePresenter(view: MainMvp.View): MainMvp.Presenter {
        return MainPresenter(view)
    }

}

And finally, ActivityScope:

@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityScope

Does anyone know what might be wrong? I have used the same exact Architectural pattern in java several times before, and I have never ran into this error before.

Also, when I comment out everything inside of InjectionModule, everything works


问:
Object Normalization
In the same line as Database Normalization - is there an approach to object normalization, not design pattern, but the same mathematical like approach to normalizing object creation.  For example: first normal form: no repeating fields....
here's some links to DB Normalization:

http://en.wikipedia.org/wiki/Database_normalization
  http://databases.about.com/od/specificproducts/a/normalization.htm

Would this make object creation and self-documentation better?

Here's a link to a book about class normalization (guess we're really talking about classes)
http://www.agiledata.org/essays/classNormalization.html

答:
In a fairly ad-hoc and untutored fashion, that will probably cause purists to scoff, and perhaps rightly, I think of a database table as being a set of objects of a particular type, and vice versa. Then I take my thoughts from there. Viewed this way, it doesn't seem to me like there's anything particularly special you have to do to use normal form in your everyday programming. Each object's identity will do for starters as its primary key, and references (pointers, etc.) will do by way of foreign keys. Then just follow the same rules.

(My objects usually end up in 3NF, or some approximation thereof. I treat this all more as guidelines, and, like I said, "untutored".)

If the rules are followed properly, each bit of information then ends up in one place, the interrelationships are clear, and everything is structured such that introducing inconsistencies takes some work. One could say that this approach produces good results on this basis, and I would agree.

One downside is that the end result can feel a bit like a tangle of spaghetti, particularly after some time away, and it's hard to shake the constant lingering sensation, even though it's usually false, that surely a few of all these links could be removed...

OwnerDisplayName: meade

Title: Object Normalization

LastEditorDisplayName: meade

OwnerDisplayName: please delete me


问:
What API does Facebook Flacedeck use?
What API does flacedeck use?

http://blog.inextin.in/2010/12/flacedeck-mediacenterized-facebook.html

Does it use the same Facebook Developer toolkit or some other?

答: When I had the same question, I've seen to files of installed application. It deploys with assembly named "Microsoft.Facebook, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" (Microsoft.Facebook.dll). It had puzzled me because I couldnt find any facebook framework by Microsoft. I can't say exactly what is it, but it's content (I've investigated it with Reflector tool) looks close to "Facebook Developer Toolkit" </p>

Title: What API does Facebook Flacedeck use?


问:
Can new objects be instantiated without the = new Obj ()?
So String isn't a primitive type but rather a class and objects of classes have to be created in the form Obj x = new Obj (); usually. However, strings can be created by saying String x = "..."; and this is the preferred way rather than String x = new String ("...");.

So I was wondering why this is allowed for strings and would it be possible to create objects of other classes in a similar fashion if the constructor only required a single parameter.

For example, if a class had a constructor that only called one integer, would saying Obj x = 2; be syntactically correct because it has the object name and parameter still included in the same way that Strings are written.

答:
String is a special final class that can not be extended. Creating a String with new keyword and literals are different;

There is a special memory area in the heap just for strings called String Pool. When you create a String literal, jvm searches the string pool and if it exists in the pool that string is addressed, if there is no match for the string you created than it is added to the pool and other strings with the same value address that object too.

If you create a String with the new keyword, it is ensured that string is a new object in the memory no matter what.

So String is a special kind of object that can not be categorized with the other objects.

Here is an article

What is String Pool


问:
How to delete NW profile data on Ubuntu?
"Your profile cannot be used because it's from a newer version of NW.js"

On Windows you delete the subfolder in ApplicationData, where is this on Ubuntu 16.04?

答: It's in ~/.config/app_name. See http://docs.nwjs.io/en/latest/References/Command%20Line%20Options/#-user-data-dir</p>


问:
MySQL Error Code: #1111 - Invalid use of group function
I am trying to write a mysql query to select  at least two  or more than same user subscription.Here's the query:

```<code>  SELECT a.* FROM `subscription` a, user b WHERE b.id=a.user_id and
        count(a.user_id) > 1 group by a.id
</code>```

Can anyone tell me what i am doing wrong?

答:
You should use having with Aggregate functions.
Where is used to filter rows. Having is used to filter groups based on given condition.

```<code>SELECT a.* FROM `subscription` a, user b WHERE b.id=a.user_id
 group by a.id
having count(a.user_id) > 1
</code>```

Also, use ANSI Syntax for Join as follows:

```<code>SELECT a.*
FROM `subscription` a
inner join
user b
on b.id=a.user_id
group by a.id
having count(a.user_id) > 1
;
</code>```

Body:
I am trying to write a mysql query to select  at least two  or more than same user subscription.Here's the query:

  SELECT a.* FROM `subscription` a, user b WHERE b.id=a.user_id and
        count(a.user_id) > 1 group by a.id

Can anyone tell me what i am doing wrong?

Body:
You should use having with Aggregate functions.
Where is used to filter rows. Having is used to filter groups based on given condition.

SELECT a.* FROM `subscription` a, user b WHERE b.id=a.user_id
 group by a.id
having count(a.user_id) > 1

Also, use ANSI Syntax for Join as follows:

SELECT a.*
FROM `subscription` a
inner join
user b
on b.id=a.user_id
group by a.id
having count(a.user_id) > 1
;


问:
How do I get the name of a Ruby class?
How can I get the class name from an ActiveRecord object?

I have:

```<code>result = User.find(1)
</code>```

I tried:

```<code>result.class
# => User(id: integer, name: string ...)
result.to_s
# => #<User:0x3d07cdc>"
</code>```

I need only the class name, in a string (User in this case). Is there a method for that?

I know this is pretty basic, but I searched both Rails' and Ruby's docs, and I couldn't find it.

答:
In my case when I use something like result.class.name I got something like Module1::class_name. But if we only want class_name, use

result.class.table_name.singularize

Title: How do I get the name of a Ruby class?

Body:
How can I get the class name from an ActiveRecord object?

I have:

result = User.find(1)

I tried:

result.class
# => User(id: integer, name: string ...)
result.to_s
# => #<User:0x3d07cdc>"

I need only the class name, in a string (User in this case). Is there a method for that?

I know this is pretty basic, but I searched both Rails' and Ruby's docs, and I couldn't find it.


问:
How to align the button at the leftmost side in a listbox control?
I am developing window phone 7 application. I am new to the silverlight. I am dynamically creating the button control and binding these all button controls to the listbox.    </p>

```<code><ListBox x:Name="lstButtons" Margin="393,-28,-12,28" Background="Orange">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <Button Content="{Binding ElementName}" Width="100" HorizontalAlignment="Right"></Button>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
 </ListBox>
</code>```

<p>Now I want to display the button control at the leftmost side means I want to display the button control near to the left border of the listbox. I want to display the button control which is aligned to the left. With my above code the the button control appears in the center in the listbox ? How should I align it to the left ? Can you please provide me any code or link through which I can resolve the above issue ? If I am doing anything wrong then please guide me. </p>

答: Take a look at the sample XAML in the MSDN resource page here. You need to play with the HorizontalAlignment property of the element you are trying to align within the parent, perhaps fine tune the alignment by setting the margin property of the element. </p>

Body:
I am developing window phone 7 application. I am new to the silverlight. I am dynamically creating the button control and binding these all button controls to the listbox.

<ListBox x:Name="lstButtons" Margin="393,-28,-12,28" Background="Orange">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <Button Content="{Binding ElementName}" Width="100" HorizontalAlignment="Right"></Button>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
 </ListBox>

Now I want to display the button control at the leftmost side means I want to display the button control near to the left border of the listbox. I want to display the button control which is aligned to the left. With my above code the the button control appears in the center in the listbox ? How should I align it to the left ? Can you please provide me any code or link through which I can resolve the above issue ? If I am doing anything wrong then please guide me.


问:
DropShadowEffect WPF
I am new to WPF/XAML coding. I am trying to add a drop shadow effect to a Rectangle shape. The XAML for the rectangle is:

CODE 1

```<code><Rectangle HorizontalAlignment="Left" Height="552" Margin="2,10,0,0"
             VerticalAlignment="Top" Width="427" StrokeThickness="4"
             Fill="#FF484A4D" Grid.Column="1"/>
</code>```

The code for DropShadowEffect is:

CODE 2

```<code><Rectangle.Effect>
    <DropShadowEffect x:name="Dshadow" BlurRadius="10" ShadowDepth="0" Color="Black"/>
</Rectangle.Effect>
</code>```

The problem is, I can't combine/use these two codes together. When I arrange CODE 2 after CODE 1, it doesn't work. How should I fix/arrange these codes?

答:
You should not close your Rectangle at the first line.

```<code><Rectangle HorizontalAlignment="Left"
           Height="552"
           Margin="2,10,0,0"
           VerticalAlignment="Top"
           Width="427"
           StrokeThickness="4"
           Fill="#FF484A4D"
           Grid.Column="1">
     <Rectangle.Effect>
         <DropShadowEffect BlurRadius="10"
                           ShadowDepth="0"
                           Color="Black"/>
     </Rectangle.Effect>
 </Rectangle>
</code>```

You need to access a Property of Rectangle - you cannot do that if you have already closed that Element.

Title: DropShadowEffect WPF

Body:
I am new to WPF/XAML coding. I am trying to add a drop shadow effect to a Rectangle shape. The XAML for the rectangle is:

CODE 1

<Rectangle HorizontalAlignment="Left" Height="552" Margin="2,10,0,0"
             VerticalAlignment="Top" Width="427" StrokeThickness="4"
             Fill="#FF484A4D" Grid.Column="1"/>

The code for DropShadowEffect is:

CODE 2

<Rectangle.Effect>
    <DropShadowEffect x:name="Dshadow" BlurRadius="10" ShadowDepth="0" Color="Black"/>
</Rectangle.Effect>

The problem is, I can't combine/use these two codes together. When I arrange CODE 2 after CODE 1, it doesn't work. How should I fix/arrange these codes?

Body:
You should not close your Rectangle at the first line.

<Rectangle HorizontalAlignment="Left"
           Height="552"
           Margin="2,10,0,0"
           VerticalAlignment="Top"
           Width="427"
           StrokeThickness="4"
           Fill="#FF484A4D"
           Grid.Column="1">
     <Rectangle.Effect>
         <DropShadowEffect BlurRadius="10"
                           ShadowDepth="0"
                           Color="Black"/>
     </Rectangle.Effect>
 </Rectangle>

You need to access a Property of Rectangle - you cannot do that if you have already closed that Element.


问:
How count the value of array？
Sorry, i need to clarify detailly.

I'm using Java to write simple array recording 3 times stock buying; every new car initiated is presented as new transaction made:

~~
1 share purchased at time $100/share.

2 shares are purchased at time $200/share.

3 shares are purchased at time $300/share.

Total 6 shares in hand.
~~

How to calculate the average buying price per share ? Which continually run by keep adding new car.

```<code>package javaex;

import java.util.ArrayList;
import java.util.function.Predicate;

    public class javaExstockprice
        public static void main(String[] args){
         ArrayList<Car> al= new ArrayList();
        al.add(new Car(1,100));
        al.add(new Car(2,200));
        al.add(new Car(3,300));

        System.out.println("showsharesbuyingmethod-alltransaction = shares : buying");
        al.forEach(c->c.showsharesbuying() );
        System.out.println();
        al.removeIf(c->c.shares>1);
        System.out.print("transcation amount 1 share / below");
        System.out.println();
         al.forEach(c->c.showsharesbuying() );
        System.out.println();
    }

    class Car
    float shares;
    float buying;
    Car (float a, float b) {
        shares = a;
        buying = b;
    }

    void showsharesbuying() {
        System.out.println("showsharesbuying " + shares+ " : " + buying);
    }
</code>```

答:
Well, trying to guess what you want, here is what comes to my mind:

```<code>import java.util.List;
import java.util.ArrayList;
import java.util.function.Predicate;

public class JavaExStockPrice {

    public static void main(String[] args){

        List<Car> al= new ArrayList();
        al.add(new Car(1,100));
        al.add(new Car(2,200));
        al.add(new Car(3,300));

        System.out.println("showsharesbuyingmethod-alltransaction = shares : buying");
        al.forEach(c->c.showSharesBuying() );
        System.out.println("Avg: " + priceAvg(al));
        System.out.println();
        al.removeIf(c->c.shares>1);
        System.out.print("transcation amount 1 share / below");
        System.out.println();
        al.forEach(c->c.showSharesBuying() );
        System.out.println("Avg: " + priceAvg(al));
        System.out.println();
    }

    static double priceAvg(List<Car> l) {
        return l.stream().mapToDouble(c -> c.buying * c.shares).average().getAsDouble() /
                    l.stream().mapToDouble(c -> c.shares).average().getAsDouble();
    }

}

class Car {
    float shares;
    float buying;

    Car (float a, float b) {
        shares = a;
        buying = b;
    }

    void showSharesBuying() {
        System.out.println("showsharesbuying " + shares+ " : " + buying);
    }
}
</code>```

Having logic on static methods like this is not a good idea, but I'm not sure if that's what you want to know.

Title: How count the value of array？

Body:
Sorry, i need to clarify detailly.

I'm using Java to write simple array recording 3 times stock buying; every new car initiated is presented as new transaction made:

~~
1 share purchased at time $100/share.

2 shares are purchased at time $200/share.

3 shares are purchased at time $300/share.

Total 6 shares in hand.
~~

How to calculate the average buying price per share ? Which continually run by keep adding new car.

package javaex;

import java.util.ArrayList;
import java.util.function.Predicate;

    public class javaExstockprice
        public static void main(String[] args){
         ArrayList<Car> al= new ArrayList();
        al.add(new Car(1,100));
        al.add(new Car(2,200));
        al.add(new Car(3,300));

        System.out.println("showsharesbuyingmethod-alltransaction = shares : buying");
        al.forEach(c->c.showsharesbuying() );
        System.out.println();
        al.removeIf(c->c.shares>1);
        System.out.print("transcation amount 1 share / below");
        System.out.println();
         al.forEach(c->c.showsharesbuying() );
        System.out.println();
    }

    class Car
    float shares;
    float buying;
    Car (float a, float b) {
        shares = a;
        buying = b;
    }

    void showsharesbuying() {
        System.out.println("showsharesbuying " + shares+ " : " + buying);
    }

Body:
Well, trying to guess what you want, here is what comes to my mind:

import java.util.List;
import java.util.ArrayList;
import java.util.function.Predicate;

public class JavaExStockPrice {

    public static void main(String[] args){

        List<Car> al= new ArrayList();
        al.add(new Car(1,100));
        al.add(new Car(2,200));
        al.add(new Car(3,300));

        System.out.println("showsharesbuyingmethod-alltransaction = shares : buying");
        al.forEach(c->c.showSharesBuying() );
        System.out.println("Avg: " + priceAvg(al));
        System.out.println();
        al.removeIf(c->c.shares>1);
        System.out.print("transcation amount 1 share / below");
        System.out.println();
        al.forEach(c->c.showSharesBuying() );
        System.out.println("Avg: " + priceAvg(al));
        System.out.println();
    }

    static double priceAvg(List<Car> l) {
        return l.stream().mapToDouble(c -> c.buying * c.shares).average().getAsDouble() /
                    l.stream().mapToDouble(c -> c.shares).average().getAsDouble();
    }

}

class Car {
    float shares;
    float buying;

    Car (float a, float b) {
        shares = a;
        buying = b;
    }

    void showSharesBuying() {
        System.out.println("showsharesbuying " + shares+ " : " + buying);
    }
}

Having logic on static methods like this is not a good idea, but I'm not sure if that's what you want to know.


问:
How to cancel a task from different class
I want to cancel a task started by one class from some other class. Below is an example program where i have two classes and want to cancel the task from different class. Cancellation token doesn't seem to work.</p>

```<code>namespace threadingiwthcancel
{
    class ThreadExample
    {
        public async Task PrintSomething(CancellationToken token)
        {
            int i = 0;
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    Console.WriteLine("Cancel requested");
                    break;
                }
                await Task.Delay(TimeSpan.FromSeconds(1));
                Console.WriteLine(i);
                i++;
            }

        }
    }
    class Cancel
    {
        public void cancelTask()
        {
            CancellationTokenSource source = new CancellationTokenSource();
            source.Cancel();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            callasyncmethod(token);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Cancel c = new Cancel();
            c.cancelTask();
            Console.ReadLine();
        }

        private static async void callasyncmethod(CancellationToken token)
        {
            ThreadExample te = new ThreadExample();
            await te.PrintSomething(token);
        }
    }
}
</code>```

答:
if you want to do like that than you need to pass object of CancellationSoruce to you cancel method in other class , do not create new CancellationSoruce

```<code>class Cancel
{
 public void cancelTask(CancellationTokenSource source )
    {
        source.Cancel();
    }
}
</code>```

in main

```<code>static void Main(string[] args)
        {
            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            callasyncmethod(token);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Cancel c = new Cancel();
            c.cancelTask(source );
            Console.ReadLine();
        }
</code>```

or can do like this

```<code>  class Cancel
    {
        private readonly CancellationTokenSource source;
        public Cancel(CancellationTokenSource source)
        {
          this.source = soruce;
        }
        public void cancelTask()
        {
            source.Cancel();
        }
    }
</code>```

and in main

```<code>static void Main(string[] args)
        {
            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            callasyncmethod(token);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Cancel c = new Cancel(source );
            c.cancelTask();
            Console.ReadLine();
        }
</code>```

Body:
I want to cancel a task started by one class from some other class. Below is an example program where i have two classes and want to cancel the task from different class. Cancellation token doesn't seem to work.

namespace threadingiwthcancel
{
    class ThreadExample
    {
        public async Task PrintSomething(CancellationToken token)
        {
            int i = 0;
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    Console.WriteLine("Cancel requested");
                    break;
                }
                await Task.Delay(TimeSpan.FromSeconds(1));
                Console.WriteLine(i);
                i++;
            }

        }
    }
    class Cancel
    {
        public void cancelTask()
        {
            CancellationTokenSource source = new CancellationTokenSource();
            source.Cancel();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            callasyncmethod(token);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Cancel c = new Cancel();
            c.cancelTask();
            Console.ReadLine();
        }

        private static async void callasyncmethod(CancellationToken token)
        {
            ThreadExample te = new ThreadExample();
            await te.PrintSomething(token);
        }
    }
}

Body:
if you want to do like that than you need to pass object of CancellationSoruce to you cancel method in other class , do not create new CancellationSoruce

class Cancel
{
 public void cancelTask(CancellationTokenSource source )
    {
        source.Cancel();
    }
}

in main

static void Main(string[] args)
        {
            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            callasyncmethod(token);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Cancel c = new Cancel();
            c.cancelTask(source );
            Console.ReadLine();
        }

or can do like this

  class Cancel
    {
        private readonly CancellationTokenSource source;
        public Cancel(CancellationTokenSource source)
        {
          this.source = soruce;
        }
        public void cancelTask()
        {
            source.Cancel();
        }
    }

and in main

static void Main(string[] args)
        {
            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            callasyncmethod(token);
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Cancel c = new Cancel(source );
            c.cancelTask();
            Console.ReadLine();
        }


答:
Cancellation token doesnt seem to work.

The reason for failure is that you are creating a different CancellationTokenSource and calling Cancel on it.  Sadly, no other operations will be notified and so your original task continues.

I want to cancel a task started by one class from some other class

Be sure to pass the original source to it:

```<code>class Cancel
{
    CancellationTokenSource _source;

    public Cancel (CancellationTokenSource source)
    {
       _source = source;
    }

    public void cancelTask()
    {
        _source.Cancel();
    }
}

    static void Main(string[] args)
    {
        CancellationTokenSource source = new CancellationTokenSource();
        CancellationToken token = source.Token;
        callasyncmethod(token);
        Thread.Sleep(TimeSpan.FromSeconds(2));
        Cancel c = new Cancel(source); // pass in the original source
        c.cancelTask();
        Console.ReadLine();
    }
</code>```

Title: How to cancel a task from different class

Body:
Cancellation token doesnt seem to work.

The reason for failure is that you are creating a different CancellationTokenSource and calling Cancel on it.  Sadly, no other operations will be notified and so your original task continues.

I want to cancel a task started by one class from some other class

Be sure to pass the original source to it:

class Cancel
{
    CancellationTokenSource _source;

    public Cancel (CancellationTokenSource source)
    {
       _source = source;
    }

    public void cancelTask()
    {
        _source.Cancel();
    }
}

    static void Main(string[] args)
    {
        CancellationTokenSource source = new CancellationTokenSource();
        CancellationToken token = source.Token;
        callasyncmethod(token);
        Thread.Sleep(TimeSpan.FromSeconds(2));
        Cancel c = new Cancel(source); // pass in the original source
        c.cancelTask();
        Console.ReadLine();
    }


问:
How do I strip malicious HTML (XXS etc.) from content submissions?
I have a content submission form that contains multiple fields for input, all of which, when submitted, are entered directly into the database. When this content is requested, it is printed.

I have realized this is a security issue.

How can I strip malicious HTML (XSS) only, while still allowing formatting tags (b, i etc.)?

答: First run htmlspecialchars on the input and then undo it for the allowed tags (for example, replace  with ).

Body: First run htmlspecialchars on the input and then undo it for the allowed tags (for example, replace &lt;b&gt; with <b>).


问:
writing function outside of a class in react component
I've seen code like this

```<code>function abc(){
  return 'abc'
}
class MyComponent extends React.Component {
    static abc = abc;
    render() { return <h1>{this.abc}</h1>; }
}
</code>```

where function abc is defined outside of a react class. I have no clue why the author did it that way, why can't just do it within the class?

答:
These are ES6 static methods and are not exclusive to React. They are members of the component class and not of instances of the component. They are not used extensively in React, but they can be useful. It is even mentioned in the React docs:

Sometimes it’s useful to define a static method on a React component.
  For example, Relay containers expose a static method getFragment to
  facilitate the composition of GraphQL fragments.

They can be used as common members of the Component, shared by all instances of it. To give you an idea, other static members of a React class are displayName and defaultProps.

Also see Static methods in React. As you can see, there aren't many cases where you would use a static method.

Body:
I've seen code like this

function abc(){
  return 'abc'
}
class MyComponent extends React.Component {
    static abc = abc;
    render() { return
{this.abc}
; }
}

where function abc is defined outside of a react class. I have no clue why the author did it that way, why can't just do it within the class?


问:
Change color of span upon click
https://codepen.io/SmileySteven/pen/pdBYdv?editors=1111

```<code>function test(){
  var span = document.querySelectorAll('span');
  for(var i = 0 ; i <= span.length ;i++){
    span.addEventListener('click', function(){
    this.style.backgroundColor === '#ffffff'? this.style.backgroundColor = 'yellow'
         : this.style.backgroundColor="#000000";
   })
 }
}
test();
</code>```

Hello guys, I am trying to change the background color of my spans upon click but it does not seem to work - care to guide me as to what I am doing wrong?  I have set all span to background color of #ffffff

答:
Adding onto the above answer, I would also recommend running test on document ready.

```<code>$( document ).ready(test);
</code>```

Updated codepen with fix: https://codepen.io/TheRodeo/pen/pdBYVJ

Title: Change color of span upon click

Body:
https://codepen.io/SmileySteven/pen/pdBYdv?editors=1111

function test(){
  var span = document.querySelectorAll('span');
  for(var i = 0 ; i <= span.length ;i++){
    span.addEventListener('click', function(){
    this.style.backgroundColor === '#ffffff'? this.style.backgroundColor = 'yellow'
         : this.style.backgroundColor="#000000";
   })
 }
}
test();

Hello guys, I am trying to change the background color of my spans upon click but it does not seem to work - care to guide me as to what I am doing wrong?  I have set all span to background color of #ffffff

Body:
Adding onto the above answer, I would also recommend running test on document ready.

$( document ).ready(test);

Updated codepen with fix: https://codepen.io/TheRodeo/pen/pdBYVJ


问:
Reversing Characters within a List using a loop
This is my code I have come up with trying to reverse these strings

```<code>presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

reversedPresidents=""
for ch in presidents:
    reversedPresidents=ch+reversedPresidents

print(reversedPresidents)
</code>```

As of now, it only prints the list backwards like this:

```<code>John Quincy Adams  James Monroe  James Madison  Thomas Jefferson  John Adams George Washington
</code>```

I need it to output the list like:

```<code>notgnihsaW egroeG
smadA nhoJ
</code>```

and so on

答:
Try this:</p>

```<code>presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " ,
" James Madison " , " James Monroe " ," John Quincy Adams " ]

reversedPresidents=[]
for ch in presidents:
     reversedPresidents.append(ch[::-1])

print(reversedPresidents)

 [' notgnihsaW egroeG', ' smadA nhoJ ', ' nosreffeJ samohT ', ' nosidaM
  semaJ ', ' eornoM semaJ ', ' smadA ycniuQ nhoJ ']
</code>```

Body:
This is my code I have come up with trying to reverse these strings

presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

reversedPresidents=""
for ch in presidents:
    reversedPresidents=ch+reversedPresidents

print(reversedPresidents)

As of now, it only prints the list backwards like this:

John Quincy Adams  James Monroe  James Madison  Thomas Jefferson  John Adams George Washington

I need it to output the list like:

notgnihsaW egroeG
smadA nhoJ

and so on

Body:
Try this:

presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " ,
" James Madison " , " James Monroe " ," John Quincy Adams " ]

reversedPresidents=[]
for ch in presidents:
     reversedPresidents.append(ch[::-1])

print(reversedPresidents)

 [' notgnihsaW egroeG', ' smadA nhoJ ', ' nosreffeJ samohT ', ' nosidaM
  semaJ ', ' eornoM semaJ ', ' smadA ycniuQ nhoJ ']


问:
How to resolve jQuery libraries conflict in project
I am facing a small problem while using Bootstrap Carousel. Actually
my project is in Magneto 2, and is using jQuery 1.12.4 but the Bootstrap Carousel wants 3.2.1 version of jQuery.

How can I resolve this conflict?

Right now, the scenario is Bootstrap Carousel is working fine in standalone example but when I try to use in my Magneto 2 project, it is not working.

I followed this example of carousel.

答:
If the page in which you want to use carousel does not require jQuery v 1.12.4 then load v 3.2.1 in that particular page. Or if the older jquery is being included by master template then load the new JQ in the page again in such a way that it loads after older JQ.

So it will override older JQ file with new one for that particular page. And you will be good to go with Carousel.

Try this out and do comment how it goes.