问:
Foreach loop with double condition in java8 using lambda
I have an exercise with this description:

```<code>1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.
1111 produces 4 because each digit (all 1) matches the next.
1234 produces 0 because no digit matches the next.
91212129 produces 9 because the only digit that matches the next one is the last digit, 9.
</code>```

I have written the following code:

```<code>String inputString = "1111"; // taking this number as example

int sum = 0;
for (int i = 0; i < inputString.length() - 1; i++) {
    if (inputString.charAt(i) == inputString.charAt(i + 1)) {
        sum += Integer.parseInt(String.valueOf(inputString.charAt(i)));
    }
    if (i + 2 == inputString.length() - 1) {
        if (inputString.charAt(i + 2) == inputString.charAt(0)) {
            sum += Integer.parseInt(String.valueOf(inputString.charAt(i + 2)));
        }
    }
}
</code>```

The result of sum is 4, which is correct.

Now I'm trying to write the same one in Java8 using lambda but I can't figure out how to get the last condition inside my stream.

This is how far I got:

```<code>Integer sum = IntStream.range(0, (inputString.length() - 1)).boxed()
                .filter(j -> inputString.charAt(j) == inputString.charAt(j + 1))
                .mapToInt(i -> Integer.parseInt(String.valueOf(inputString.charAt(i)))).sum();
</code>```

答:
This is going to get really messy with streams as far as my knowledge goes, nevertheless, I enjoyed the challenge and here's how I'd do it:

First, create two functions:

a mapper function from char to int to help reduce the code we're going to keep repeating.

a predicate like function to validate whether two given characters are equal; again to help reduce the code we're going to keep repeating.

that is:

```<code>public static int mapper(String value, int index){
    return Integer.parseInt(String.valueOf(value.charAt(index)));
}

public static boolean areEqual(String inputString, int firstIndex, int secondIndex){
      return inputString.charAt(firstIndex) == inputString.charAt(secondIndex);
}
</code>```

then you can accomplish the task by doing:

```<code>int sum = IntStream.range(0, inputString.length() - 1)
            .map(i -> areEqual(inputString, i, i + 1) &&
                    i + 2 == inputString.length() - 1 &&
                    areEqual(inputString, i + 2, 0)?
                    mapper(inputString, i) + mapper(inputString, i + 2) :
                    areEqual(inputString, i , i + 1) &&
                            i + 2 != inputString.length() - 1 ?
                            mapper(inputString, i) :
                            i + 2 == inputString.length() - 1 &&
                                    areEqual(inputString,i + 2, 0) &&
                                    inputString.charAt(i) != inputString.charAt(i + 1) ?
                                    mapper(inputString, i + 2) :
                                    inputString.charAt(i) == inputString.charAt(i + 1) ?
                                            mapper(inputString, i) : 0
            )
            .sum();
</code>```

The solution above takes into consideration all the possible conditions that could be met hence the need to subsequently keep checking different conditions.

As an aside, another thing you might want to do to reduce the code more is by making inputString a global variable which you can then directly use within the two helper functions and thus meaning we can get rid of the inputString parameter both for methods.

Body:
I have an exercise with this description:

1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.
1111 produces 4 because each digit (all 1) matches the next.
1234 produces 0 because no digit matches the next.
91212129 produces 9 because the only digit that matches the next one is the last digit, 9.

I have written the following code:

String inputString = "1111"; // taking this number as example

int sum = 0;
for (int i = 0; i < inputString.length() - 1; i++) {
    if (inputString.charAt(i) == inputString.charAt(i + 1)) {
        sum += Integer.parseInt(String.valueOf(inputString.charAt(i)));
    }
    if (i + 2 == inputString.length() - 1) {
        if (inputString.charAt(i + 2) == inputString.charAt(0)) {
            sum += Integer.parseInt(String.valueOf(inputString.charAt(i + 2)));
        }
    }
}

The result of sum is 4, which is correct.

Now I'm trying to write the same one in Java8 using lambda but I can't figure out how to get the last condition inside my stream.

This is how far I got:

Integer sum = IntStream.range(0, (inputString.length() - 1)).boxed()
                .filter(j -> inputString.charAt(j) == inputString.charAt(j + 1))
                .mapToInt(i -> Integer.parseInt(String.valueOf(inputString.charAt(i)))).sum();

Body:
This is going to get really messy with streams as far as my knowledge goes, nevertheless, I enjoyed the challenge and here's how I'd do it:

First, create two functions:

a mapper function from char to int to help reduce the code we're going to keep repeating.

a predicate like function to validate whether two given characters are equal; again to help reduce the code we're going to keep repeating.

that is:

public static int mapper(String value, int index){
    return Integer.parseInt(String.valueOf(value.charAt(index)));
}

public static boolean areEqual(String inputString, int firstIndex, int secondIndex){
      return inputString.charAt(firstIndex) == inputString.charAt(secondIndex);
}

then you can accomplish the task by doing:

int sum = IntStream.range(0, inputString.length() - 1)
            .map(i -> areEqual(inputString, i, i + 1) &&
                    i + 2 == inputString.length() - 1 &&
                    areEqual(inputString, i + 2, 0)?
                    mapper(inputString, i) + mapper(inputString, i + 2) :
                    areEqual(inputString, i , i + 1) &&
                            i + 2 != inputString.length() - 1 ?
                            mapper(inputString, i) :
                            i + 2 == inputString.length() - 1 &&
                                    areEqual(inputString,i + 2, 0) &&
                                    inputString.charAt(i) != inputString.charAt(i + 1) ?
                                    mapper(inputString, i + 2) :
                                    inputString.charAt(i) == inputString.charAt(i + 1) ?
                                            mapper(inputString, i) : 0
            )
            .sum();

The solution above takes into consideration all the possible conditions that could be met hence the need to subsequently keep checking different conditions.

As an aside, another thing you might want to do to reduce the code more is by making inputString a global variable which you can then directly use within the two helper functions and thus meaning we can get rid of the inputString parameter both for methods.


来源: stackexchange

问:
Regex for groovy not working
Please find below my code. I am trying to iterate through files and in a directory and print out all the match to the regex: (&)(.+?\b)
however this doesn't seem to work (it returns an empty string). Where did I go wrong?

```<code>import groovy.io.FileType

class FileExample {
    static void main(String[] args) {

        def list = []

        def dir = new File("*path to dir*")
        dir.eachFileRecurse (FileType.FILES) { file ->
            list << file.name;
            def s= "${file.text}";
            def w = s.toString();
            w.readLines().grep(~/(&)(.+?\b)/)
        }
    }
}
</code>```

答:
w.readLines().grep(~/(&)(.+?\b)/) does not do any output, it gives you the matching lines as return value, so if you change it to println w.readLines().grep(~/(&)(.+?\b)/) or w.readLines().grep(~/(&)(.+?\b)/).each { println it }, you will get the matched lines printed on stdout.

Btw.

```<code> def s= "${file.text}";
 def w = s.toString();
 w.readLines()
</code>```

is just a biiiig waste of time. It is exactly the same as file.text.readLines().

"${file.text}" is a GString that replaces the placeholders on evaluation,  but as you have nothing but the file.text placeholder, this is the same as file.text as String or file.text.toString().

But as file.text actually is a String already, it is identical to file.text.

And even if you would need the GString because you have more than the placeholder in it, GString already has a readLines() method, so no need for using .toString() first, even if a GString would be necessary.

ContentLicense: CC BY-SA 3.0

Title: Regex for groovy not working

Body:
Please find below my code. I am trying to iterate through files and in a directory and print out all the match to the regex: (&)(.+?\b)
however this doesn't seem to work (it returns an empty string). Where did I go wrong?

import groovy.io.FileType

class FileExample {
    static void main(String[] args) {

        def list = []

        def dir = new File("*path to dir*")
        dir.eachFileRecurse (FileType.FILES) { file ->
            list << file.name;
            def s= "${file.text}";
            def w = s.toString();
            w.readLines().grep(~/(&)(.+?\b)/)
        }
    }
}

Body:
w.readLines().grep(~/(&)(.+?\b)/) does not do any output, it gives you the matching lines as return value, so if you change it to println w.readLines().grep(~/(&)(.+?\b)/) or w.readLines().grep(~/(&)(.+?\b)/).each { println it }, you will get the matched lines printed on stdout.

Btw.

 def s= "${file.text}";
 def w = s.toString();
 w.readLines()

is just a biiiig waste of time. It is exactly the same as file.text.readLines().

"${file.text}" is a GString that replaces the placeholders on evaluation,  but as you have nothing but the file.text placeholder, this is the same as file.text as String or file.text.toString().

But as file.text actually is a String already, it is identical to file.text.

And even if you would need the GString because you have more than the placeholder in it, GString already has a readLines() method, so no need for using .toString() first, even if a GString would be necessary.


问:
FirebaseApp.initializeApp(Context); Android error;
I've spent about three days now trying to solve a java error that's stopping me from finishing my chat app! And of course it's a firebase error! I'm new to Android Developing so when you answer, if you could explain it using simple terms, it'll help a lot! -

```<code>    Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.teo.myapplication. Make sure to call FirebaseApp.initializeApp(Context) first.
                                                                               at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
                                                                               at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
                                                                               at com.example.teo.myapplication.MainActivity.onCreate(MainActivity.java:52)
</code>```

my actual code for the problem looks like this (lines 51 and 52):

```<code>    FirebaseApp.initializeApp(Context);
    dataBase = FirebaseDatabase.getInstance();
</code>```

It looks like it should work, but Context get's an error! It's the old expression expected error and I've tried everything to fix it.
i've tried the following plus some more:

```<code>FirebaseApp.initializeApp(this)

FirebaseApp.initializeApp(this.context)

FirebaseApp.initializeApp(context)

FirebaseApp.initializeApp(many other things)
</code>```

And nothing works! The only thing I can find to work is just (Context) except there's an error on Context... UGH.

I've tried calling it in both MainActivity and ChatActivity but there's an error for both. Please help me!

these are my dependencies:

```<code>  dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.google.firebase:firebase-storage:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.google.firebase:firebase-core:10.2.1'
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'com.google.code.gson:gson:2.8.1'
    compile 'com.google.firebase:firebase-messaging:11.0.4'
    compile 'com.firebase:firebase-client-android:2.5.0'

    testCompile 'junit:junit:4.12'

}
</code>```

I've tried to use the actual code that works

example:

```<code>    FirebaseApp.initializeApp(this);
  dataBase = FirebaseDatabase.getInstance();
</code>```

But even though it doesn't say there's any errors, when I run my app, it closes right away and the same error pops up.

Thanks!

EDIT:

ChatActivity onCreate method code:

```<code>  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat_activity);

    Intent intent = getIntent();
    username = intent.getStringExtra("username");
    chatroomName = intent.getStringExtra("Chat_room_name");
    Incognito = intent.getBooleanExtra("Incognito", false);

    listview = (ListView) findViewById(R.id.list_view);
    chatsend = (EditText) findViewById(R.id.chat_function);
    final ArrayList<String> listArray = new ArrayList<String>();
    MyListAdapter adapter = new MyListAdapter(getApplicationContext(), listArray, ChatActivity.this);
    listview.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    context = this;
    FirebaseApp.initializeApp(this);
  dataBase = FirebaseDatabase.getInstance();
     ref = dataBase.getReference();

    // listArray.add(chatsend);

}
</code>```

Thanks! This code was altered after trying to fix a attempts from comments although none worked as whenever, like said before, I put (this) or anything that isn't (Context), it just asks for (Context) instead.

Edit including the manifest File:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.teo.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ChatActivity"/>
    </application>

</manifest>
</code>```

Thanks!

答:
Add:

```<code>apply plugin: 'com.google.gms.google-services'
</code>```

in your app gradle file

According to the docs:

As said in the docs:

Any FirebaseApp initialization must occur only in the main process of the app. Use of Firebase in processes other than the main process is not supported and will likely cause problems related to resource contention.

you need to initialize it not in the activity.

add an application class to your manifest example:

```<code>      <applicaton
       android:name="MyApplication"

</code>```

then do this:

```<code>public class MyApplication extends Application {
  @Override
public void onCreate() {
    super.onCreate();
   FirebaseApp.initializeApp(this);
}
</code>```

and remove the initialization from the activity. You need to initialize it in the application class which is the base class.

Body:
I've spent about three days now trying to solve a java error that's stopping me from finishing my chat app! And of course it's a firebase error! I'm new to Android Developing so when you answer, if you could explain it using simple terms, it'll help a lot! -

    Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.example.teo.myapplication. Make sure to call FirebaseApp.initializeApp(Context) first.
                                                                               at com.google.firebase.FirebaseApp.getInstance(Unknown Source)
                                                                               at com.google.firebase.database.FirebaseDatabase.getInstance(Unknown Source)
                                                                               at com.example.teo.myapplication.MainActivity.onCreate(MainActivity.java:52)

my actual code for the problem looks like this (lines 51 and 52):

    FirebaseApp.initializeApp(Context);
    dataBase = FirebaseDatabase.getInstance();

It looks like it should work, but Context get's an error! It's the old expression expected error and I've tried everything to fix it.
i've tried the following plus some more:

FirebaseApp.initializeApp(this)

FirebaseApp.initializeApp(this.context)

FirebaseApp.initializeApp(context)

FirebaseApp.initializeApp(many other things)

And nothing works! The only thing I can find to work is just (Context) except there's an error on Context... UGH.

I've tried calling it in both MainActivity and ChatActivity but there's an error for both. Please help me!

these are my dependencies:

  dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.3.1'
    compile 'com.google.firebase:firebase-storage:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.google.firebase:firebase-core:10.2.1'
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.android.gms:play-services-ads:11.0.4'
    compile 'com.google.code.gson:gson:2.8.1'
    compile 'com.google.firebase:firebase-messaging:11.0.4'
    compile 'com.firebase:firebase-client-android:2.5.0'

    testCompile 'junit:junit:4.12'

}

I've tried to use the actual code that works

example:

    FirebaseApp.initializeApp(this);
  dataBase = FirebaseDatabase.getInstance();

But even though it doesn't say there's any errors, when I run my app, it closes right away and the same error pops up.

Thanks!

EDIT:

ChatActivity onCreate method code:

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat_activity);

    Intent intent = getIntent();
    username = intent.getStringExtra("username");
    chatroomName = intent.getStringExtra("Chat_room_name");
    Incognito = intent.getBooleanExtra("Incognito", false);

    listview = (ListView) findViewById(R.id.list_view);
    chatsend = (EditText) findViewById(R.id.chat_function);
    final ArrayList<String> listArray = new ArrayList<String>();
    MyListAdapter adapter = new MyListAdapter(getApplicationContext(), listArray, ChatActivity.this);
    listview.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    context = this;
    FirebaseApp.initializeApp(this);
  dataBase = FirebaseDatabase.getInstance();
     ref = dataBase.getReference();

    // listArray.add(chatsend);

}

Thanks! This code was altered after trying to fix a attempts from comments although none worked as whenever, like said before, I put (this) or anything that isn't (Context), it just asks for (Context) instead.

Edit including the manifest File:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.teo.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ChatActivity"/>
    </application>

</manifest>

Thanks!

Body:
Add:

apply plugin: 'com.google.gms.google-services'

in your app gradle file

According to the docs:

As said in the docs:

Any FirebaseApp initialization must occur only in the main process of the app. Use of Firebase in processes other than the main process is not supported and will likely cause problems related to resource contention.

you need to initialize it not in the activity.

add an application class to your manifest example:

      <applicaton
       android:name="MyApplication"

then do this:

public class MyApplication extends Application {
  @Override
public void onCreate() {
    super.onCreate();
   FirebaseApp.initializeApp(this);
}

and remove the initialization from the activity. You need to initialize it in the application class which is the base class.


问:
Click a left/right button to display different divs
Im working on a site and i want to add this next part where you can click left and right buttons to go through different work. There would be an image, a title, a paragraph and then a button. When you click a left or right arrow on the right or left it would swipe through different work.

See this image as to see the design of what im trying to do.

Im not sure what would be the best way to attack this. Some hid the current div and present the new div when the arrow is clicked. I'd be happy with just 3 different divs to swipe through. And when you click a arrow the current div will fade out quickly and the new div will fade in.

** would also need to be responsive** maybe at mobile you can swip insead of buttons

答:
Don't reinvent the wheel, someone may post a slick response that may work. But if you are creating elements with a degree of sophistication, it is better to use a library that has solved many of the issues that your own implementation either will not have time to handle or won't find any of these issues until later on. /endrant

```<code>Try any fine library off of github

[Unslider][1]

[GlideJS][2]
</code>```

Body:
Don't reinvent the wheel, someone may post a slick response that may work. But if you are creating elements with a degree of sophistication, it is better to use a library that has solved many of the issues that your own implementation either will not have time to handle or won't find any of these issues until later on. /endrant

Try any fine library off of github

[Unslider][1]

[GlideJS][2]


问:
google marker open activity when marker is clicked
I have created an app that shows the list of bar locations by a marker on a map taken from a database on firebase.

each bar has a list of beverages.

what I wish to happen is that when a marker is clicked a new activity will open with the name of the bar selected at the top of the new activity

What i wish to happen is that when the marker is clicked it will open a new activity

//Declaration list of venues

```<code>List<Venue> venueList;
</code>```

//onCreate method

```<code>    venueList = new ArrayList<>();
    mVenues.push().setValue(marker);
</code>```

//onMapsReady method, gets the venues into the map

```<code>  public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mVenues.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot s : dataSnapshot.getChildren()){
                Venue venue = s.getValue(Venue.class);

                venueList.add(venue);
                for (int i = 0; i < venueList.size(); i++)
                {
                    LatLng latLng = new LatLng(venue.venueLat,venue.venueLong);
                    if (mMap != null) {
                        marker = mMap.addMarker(new MarkerOptions()
                                .position(latLng).title(venue.venueName));
                                           }
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });
</code>```

//Marker Click Event

```<code>  //CMarker click event to take user to purchase beverage
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener(){
        public boolean onMarkerClick(Marker marker) {
            String title = marker.getTitle();
            {
                for (int i = 0; i < venueList.size();) {
                    //getting the selected venue
                    Venue venue = venueList.get(i);
                    //creating an intent

                    Intent intent = new Intent(getApplicationContext(), viewbeverageActivity.class);

                    //putting venue name and id to intent
                    intent.putExtra(VENUE_ID, venue.getVenueId());
                    intent.putExtra(VENUE_NAME, venue.getVenueName());

                    //starting the activity with intent
                    startActivity(intent);

                }
                return false;
            }
        }
    });
</code>```

//Venue Class

```<code>package uk.ac.ferry_j2ulster.beerapp;

import com.google.firebase.database.IgnoreExtraProperties;

public class Venue {
    private String venueId;
    public String venueName;
    private String venueType;
    public double venueLat;
    public double venueLong;

    public Venue(){

    }

    public Venue(String venueId, String venueName, String venueType,double venueLat, double venueLong) {
        this.venueId = venueId;
        this.venueName = venueName;
        this.venueType = venueType;
        this.venueLat =  venueLat;
        this.venueLong =  venueLong;

    }

    public String getVenueId() {
        return venueId;
    }

    public String getVenueName() {
        return venueName;
    }

    public String getVenueType() {
        return venueType;
    }

    public double getVenueLong() { return venueLong;
    }

    public double getVenueLat() {return venueLat;
    }
}
</code>```

I hope to open a new activity with the bar that was selected as a title at the top

no errors, not sure how to start with this one

答:
The problem is that you are using a loop to go through each Venue, and calling startActivity() for all venues.

Instead, define a HashMap that will map each Marker ID to a Venue ID:

```<code> Map<String, String> mMarkerMap = new HashMap<>();
</code>```

Then, put an entry in the HashMap for each Marker:

```<code>@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot s : dataSnapshot.getChildren()){
        Venue venue = s.getValue(Venue.class);

        venueList.add(venue);
        for (int i = 0; i < venueList.size(); i++)
        {
            LatLng latLng = new LatLng(venue.venueLat,venue.venueLong);
            if (mMap != null) {
                marker = mMap.addMarker(new MarkerOptions()
                        .position(latLng).title(venue.venueName));
                //Added:
                mMarkerMap.put(marker.getId(), venue.getVenueId());
            }
        }
    }
}
</code>```

Then, when the user taps a Marker, get the title and Venue ID from the Marker/HashMap, and send it to the new activity:

```<code>@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    //...........

    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            String venueID = mMarkerMap.get(marker.getId());
            String venueName = marker.getTitle();
            Intent intent = new Intent(MapActivity.this, NewActivity.class);
            intent.putExtra(VENUE_NAME, venueName);
            intent.putExtra(VENUE_ID, venueID);
            startActivity(intent);

            return false;
        }
    });
}
</code>```

In the new activity, simply get the title and Venue ID Strings passed in:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new);

    String venueName = getIntent().getStringExtra(MapActivity.VENUE_NAME);
    if (title != null) {
        getSupportActionBar().setTitle(title);
    }

    String venueID = getIntent().getStringExtra(MapActivity.VENUE_ID);
    if (venueID != null) {
        //use venue ID to get the information about this venue
    }

    //.......
 }
</code>```

Body:
I have created an app that shows the list of bar locations by a marker on a map taken from a database on firebase.

each bar has a list of beverages.

what I wish to happen is that when a marker is clicked a new activity will open with the name of the bar selected at the top of the new activity

What i wish to happen is that when the marker is clicked it will open a new activity

//Declaration list of venues

List<Venue> venueList;

//onCreate method

    venueList = new ArrayList<>();
    mVenues.push().setValue(marker);

//onMapsReady method, gets the venues into the map

  public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mVenues.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot s : dataSnapshot.getChildren()){
                Venue venue = s.getValue(Venue.class);

                venueList.add(venue);
                for (int i = 0; i < venueList.size(); i++)
                {
                    LatLng latLng = new LatLng(venue.venueLat,venue.venueLong);
                    if (mMap != null) {
                        marker = mMap.addMarker(new MarkerOptions()
                                .position(latLng).title(venue.venueName));
                                           }
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });

//Marker Click Event

  //CMarker click event to take user to purchase beverage
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener(){
        public boolean onMarkerClick(Marker marker) {
            String title = marker.getTitle();
            {
                for (int i = 0; i < venueList.size();) {
                    //getting the selected venue
                    Venue venue = venueList.get(i);
                    //creating an intent

                    Intent intent = new Intent(getApplicationContext(), viewbeverageActivity.class);

                    //putting venue name and id to intent
                    intent.putExtra(VENUE_ID, venue.getVenueId());
                    intent.putExtra(VENUE_NAME, venue.getVenueName());

                    //starting the activity with intent
                    startActivity(intent);

                }
                return false;
            }
        }
    });

//Venue Class

package uk.ac.ferry_j2ulster.beerapp;

import com.google.firebase.database.IgnoreExtraProperties;

public class Venue {
    private String venueId;
    public String venueName;
    private String venueType;
    public double venueLat;
    public double venueLong;

    public Venue(){

    }

    public Venue(String venueId, String venueName, String venueType,double venueLat, double venueLong) {
        this.venueId = venueId;
        this.venueName = venueName;
        this.venueType = venueType;
        this.venueLat =  venueLat;
        this.venueLong =  venueLong;

    }

    public String getVenueId() {
        return venueId;
    }

    public String getVenueName() {
        return venueName;
    }

    public String getVenueType() {
        return venueType;
    }

    public double getVenueLong() { return venueLong;
    }

    public double getVenueLat() {return venueLat;
    }
}

I hope to open a new activity with the bar that was selected as a title at the top

no errors, not sure how to start with this one

Body:
The problem is that you are using a loop to go through each Venue, and calling startActivity() for all venues.

Instead, define a HashMap that will map each Marker ID to a Venue ID:

 Map<String, String> mMarkerMap = new HashMap<>();

Then, put an entry in the HashMap for each Marker:

@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot s : dataSnapshot.getChildren()){
        Venue venue = s.getValue(Venue.class);

        venueList.add(venue);
        for (int i = 0; i < venueList.size(); i++)
        {
            LatLng latLng = new LatLng(venue.venueLat,venue.venueLong);
            if (mMap != null) {
                marker = mMap.addMarker(new MarkerOptions()
                        .position(latLng).title(venue.venueName));
                //Added:
                mMarkerMap.put(marker.getId(), venue.getVenueId());
            }
        }
    }
}

Then, when the user taps a Marker, get the title and Venue ID from the Marker/HashMap, and send it to the new activity:

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    //...........

    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            String venueID = mMarkerMap.get(marker.getId());
            String venueName = marker.getTitle();
            Intent intent = new Intent(MapActivity.this, NewActivity.class);
            intent.putExtra(VENUE_NAME, venueName);
            intent.putExtra(VENUE_ID, venueID);
            startActivity(intent);

            return false;
        }
    });
}

In the new activity, simply get the title and Venue ID Strings passed in:

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

    String venueName = getIntent().getStringExtra(MapActivity.VENUE_NAME);
    if (title != null) {
        getSupportActionBar().setTitle(title);
    }

    String venueID = getIntent().getStringExtra(MapActivity.VENUE_ID);
    if (venueID != null) {
        //use venue ID to get the information about this venue
    }

    //.......
 }


问:
Sending POST info via PHP (curl) or jQuery - IP problem -
Im sending post info by using php curl. its okay. no problem. however it sends server's IP. this is a problem for me.

jquery is sending post info with user's IP, however jQuery have cross domain problem. it is not sending post info to another domain. It only works for same domain.

I wanna send post info (to another domain) + user ip (not server ip). Id like to learn your advices... Well, is there any other ways to make this job?

Thanks, Regards.

答:
If the "some-other-site" is yours too and you just need client IP there - you can pass just another POST parameter with value from global array $_SERVER["REMOTE_ADDR"]

But if you need to make request from client IP - you should use iframe, as Pekka said.

ContentLicense: CC BY-SA 2.5


问:
AWS Gateway custom authorizer necessary when using AWS_IAM authorization in Method Request?
I'm using AWS Gateway as my web API with AWS Lambda as my serverless backend. Lambda functions are only invoked by my Gateway APIs. Through Lambda I call and execute operations on other AWS Services (RDS, SNS, etc.).
I want only my clients to get access to my web APIs. To do so I setup all of my Gateway APIs with AWS_IAM authorization. An unauthenticated client have only policies that let him invoke e.g. the function for login/sign up a user. In comparison an authenticated client have policies that enables him to access more recourses.

The question now is: Because I only want my clients to get access to my Gateway APIs and to do it as secure as possible, is it necessary to create a custom authorizer which checks the validity of tokens?

Neither I did setup a cognito user pool, nor I did setup a external public provider (google, Facebook, openId, amazon, etc.). I'm working with custom developer authenticated identities. All users are saved in AWS RDS. When a user tries to login and gets correctly authenticated through his email and password a open id and a jwt token is returned to the client. This is done by invoking 'getOpenIdTokenForDeveloperIdentity'.

I found some recourses on the web where people created a custom authorizer, but they did always verify the validity of the token by a external provider (google, facebook, auth0, etc.). This member did wrote that you only need to have a external provider when you have "[...]some totally different auth logic[...]" https://stackoverflow.com/a/39407156/5181862. And I don't think this is the case here.

The clients that run the application are iOS and later Android devices, if this information is necessary.

答:
If all the APIs have AWS_IAM authorization, that is already pretty secure. AWS_IAM requires that the client have valid AWS credentials from the same account as the API (your account).

It sounds like you are using Cognito (talking about unauthenticated client policy), in which case your authorization model is secure if implemented correctly.


问:
How does AWS FIFO SQS deduplication ID work?
I'm trying to use the AWS SQS FIFO service together with an Elastic Beanstalk worker environment.

Let's say I send a message with MessageDeduplicationId test, if I continue sending this exact message in the next 5 minutes, the message will be ignored, correct?

What happens if I send a message with MessageDeduplicationId test , the consumer processes the message and deletes it, then, in about 1 minute, I send the exact same message again. Will this message be ignored?

My question is, does deduplication occur as long as the same MessageDeduplicationId is still in queue/flight? Or is the id banner forever, no other message with the same id can be sent.

Thanks.

答:
I continue sending this exact messages in the next 5 minutes, the message will be ignored, correct?

Correct.  Any longer than 5 minutes, though, and it will be accepted again and delivered again and then ignored for another 5 minutes.

ContentLicense: CC BY-SA 4.0


问:
Angular 5 getting array issue with data from service to component to template
Trying to display data in template HTML from a component to service call which calls and returns an API, but I'm getting this error

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

HTML

```<code><li *ngFor="let item of testing">
   <a [routerLink]="[item.url]" >
    <span>{{item.name}}</span>
   </a>
</li>
</code>```

Component

```<code>testing: any;

this.arsSevice.getMenu()
     .subscribe(
         result => {
            this.testing = result;
            console.log('menu',result);
      },
      error => {
         console.log('menu error', error);
      }
      )
</code>```

Service:

```<code>getMenu()  {
    return this.http.post(this.menuUrl, JSON.stringify({
        "UserID": 61525,
        "AppID": 15,
        "NavAppID":null,
        "AppGroupID": 116,
        "SelectedCaseID": 0,
        "SelectedRoleID":0
    }), httpOptions)
        .map((response: Response)=> {
            return response;
        })
}
</code>```

Image screenshot of the data

Update

I see a data problem

"menu" has data:  and it what is HERE and NOT working.

the working one is from a different API call
Notice that is has

data: Array(16)

How can I fix my data from object to array ?

答:
Try this: *ngFor="let item of testing.data.Menu1Items". I do not believe you need the async pipe for this. I would also *ngIf which ever div is containing the *ngFor loop.

Like so:

```<code><div *ngIf="testing">
    <li *ngFor="let item of testing.data.Menu1Items">
       <a [routerLink]="[item.url]" >
        <span>{{item.name}}</span>
       </a>
    </li>
</div>
</code>```

Let me know if this can help out with what you are trying to achieve.

EDIT:

So I would suggest formatting your data differently when returning a response to your client, this is how I would format the data before its returned:

```<code>[
  {
    actionType: '',
    displayName: 'MyiCIS',
    displayOrder: '1',
    displayOrder1: null,
    groupName: 'Data Entry',
    id: 420,
    url: 'MyiCIS.asp',
    type: 'Menu1Items'
  },
  {
    actionType: '',
    displayName: 'MyiCIS',
    displayOrder: '1',
    displayOrder1: null,
    groupName: 'Data Entry',
    id: 420,
    url: 'MyiCIS.asp',
    type: 'Menu1Items'
  },
  {
    actionType: '',
    displayName: 'MyiCIS',
    displayOrder: '1',
    displayOrder1: null,
    groupName: 'Data Entry',
    id: 420,
    url: 'MyiCIS.asp',
    type: 'Menu2Items'
  },
  {
    actionType: '',
    displayName: 'MyiCIS',
    displayOrder: '1',
    displayOrder1: null,
    groupName: 'Data Entry',
    id: 420,
    url: 'MyiCIS.asp',
    type: 'Menu2Items'
  }
];
</code>```

Then if you want to group the data by whichever field you choose, run the array through this method and it will spit out the data grouped into separate arrays:

```<code>transformArray(array: Array<any>, field) {
    if (array) {
      const groupedObj = array.reduce((prev, cur) => {
        if (!prev[cur[field]]) {
          prev[cur[field]] = [cur];
        } else {
          prev[cur[field]].push(cur);
        }
        return prev;
      }, {});
      return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] }));
    }
    return [];
  }
</code>```

Here is a console log of the data before its transformed and then after its been transformed:

So the first array is just what should be returned from the server, and the second array is after the transformation.

Then to loop through this in your markup, here is the structure of the *ngFor:

```<code><div *ngFor"let category of data">
  <div>{{ category.key }}</div>
  <div *ngFor="let item of category.value">
    {{ value.name }}
  </div>
</div>
</code>```

I hope this can be of help, I think your first step should be formatting that array before its returned to the client as an array of objects not grouped by a key, and then manipulate the data once it hits your client.

Body:
Trying to display data in template HTML from a component to service call which calls and returns an API, but I'm getting this error

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

HTML

    {{item.name}}

Component

testing: any;

this.arsSevice.getMenu()
     .subscribe(
         result => {
            this.testing = result;
            console.log('menu',result);
      },
      error => {
         console.log('menu error', error);
      }
      )

Service:

getMenu()  {
    return this.http.post(this.menuUrl, JSON.stringify({
        "UserID": 61525,
        "AppID": 15,
        "NavAppID":null,
        "AppGroupID": 116,
        "SelectedCaseID": 0,
        "SelectedRoleID":0
    }), httpOptions)
        .map((response: Response)=> {
            return response;
        })
}

Image screenshot of the data

Update

I see a data problem

"menu" has data:  and it what is HERE and NOT working.

the working one is from a different API call
Notice that is has

data: Array(16)

How can I fix my data from object to array ?

Body:
Try this: *ngFor="let item of testing.data.Menu1Items". I do not believe you need the async pipe for this. I would also *ngIf which ever div is containing the *ngFor loop.

Like so:

<div *ngIf="testing">
    <li *ngFor="let item of testing.data.Menu1Items">
       <a [routerLink]="[item.url]" >
        <span>{{item.name}}</span>
       </a>
    </li>
</div>

Let me know if this can help out with what you are trying to achieve.

EDIT:

So I would suggest formatting your data differently when returning a response to your client, this is how I would format the data before its returned:

[
  {
    actionType: '',
    displayName: 'MyiCIS',
    displayOrder: '1',
    displayOrder1: null,
    groupName: 'Data Entry',
    id: 420,
    url: 'MyiCIS.asp',
    type: 'Menu1Items'
  },
  {
    actionType: '',
    displayName: 'MyiCIS',
    displayOrder: '1',
    displayOrder1: null,
    groupName: 'Data Entry',
    id: 420,
    url: 'MyiCIS.asp',
    type: 'Menu1Items'
  },
  {
    actionType: '',
    displayName: 'MyiCIS',
    displayOrder: '1',
    displayOrder1: null,
    groupName: 'Data Entry',
    id: 420,
    url: 'MyiCIS.asp',
    type: 'Menu2Items'
  },
  {
    actionType: '',
    displayName: 'MyiCIS',
    displayOrder: '1',
    displayOrder1: null,
    groupName: 'Data Entry',
    id: 420,
    url: 'MyiCIS.asp',
    type: 'Menu2Items'
  }
];

Then if you want to group the data by whichever field you choose, run the array through this method and it will spit out the data grouped into separate arrays:

transformArray(array: Array<any>, field) {
    if (array) {
      const groupedObj = array.reduce((prev, cur) => {
        if (!prev[cur[field]]) {
          prev[cur[field]] = [cur];
        } else {
          prev[cur[field]].push(cur);
        }
        return prev;
      }, {});
      return Object.keys(groupedObj).map(key => ({ key, value: groupedObj[key] }));
    }
    return [];
  }

Here is a console log of the data before its transformed and then after its been transformed:

So the first array is just what should be returned from the server, and the second array is after the transformation.

Then to loop through this in your markup, here is the structure of the *ngFor:

<div *ngFor"let category of data">
  <div>{{ category.key }}</div>
  <div *ngFor="let item of category.value">
    {{ value.name }}
  </div>
</div>

I hope this can be of help, I think your first step should be formatting that array before its returned to the client as an array of objects not grouped by a key, and then manipulate the data once it hits your client.


问:
Twilio Call Logs (Node.js helper Library)
I am just trying to get a list of all calls from a specific number with the twilio-node helper library, but currently I have some issues with the async behaviour of the function to retrieve the call logs.

So my code looks like this:

const filter = {
   from: phoneNumber
};

var calls = {};

client.calls
.each(filter, call => {
  calls[call.sid] = call;
});```

So what I am trying to do, is to wait for all calls to be fetched and inserted into the calls object. After that has been completed, I need to call a function that returns the call object. I already tried .then(() => {}); and .done(() => {}); but that keeps giving me the following error:

Cannot read property 'then' of undefined

I hope someone can help me out :)

答:
Twilio developer evangelist here.

client.calls.each is intended to be used to deal with each call as they are received from the API. If you want a list of calls then you can use the list method. Be sure to set a limit though, as list by default will fetch all calls.

```<code>const filter = {
  from: phoneNumber,
  limit: 50
};

client.calls.list(filter).then(calls => { // do something with all the calls });
</code>```

Let me know if that helps.

Body:
I am just trying to get a list of all calls from a specific number with the twilio-node helper library, but currently I have some issues with the async behaviour of the function to retrieve the call logs.

So my code looks like this:

const filter = {
   from: phoneNumber
};

var calls = {};

client.calls
.each(filter, call => {
  calls[call.sid] = call;
});

So what I am trying to do, is to wait for all calls to be fetched and inserted into the calls object. After that has been completed, I need to call a function that returns the call object. I already tried .then(() => {}); and .done(() => {}); but that keeps giving me the following error:

Cannot read property 'then' of undefined

I hope someone can help me out :)

Body:
Twilio developer evangelist here.

client.calls.each is intended to be used to deal with each call as they are received from the API. If you want a list of calls then you can use the list method. Be sure to set a limit though, as list by default will fetch all calls.

const filter = {
  from: phoneNumber,
  limit: 50
};

client.calls.list(filter).then(calls => { // do something with all the calls });

Let me know if that helps.


问:
Retrieving servlet context, session and request in a POJO outside container
Is there any way to retrieve a session from a POJO? Or ultimately to retrieve a bean from a POJO.

To clarify:

Basically I am creating a bean from a servlet and I need to access the properties of that bean from outside of the web container (from a POJO). I cannot pass the request to the pojo; and the request is needed to retrieve the session.

More specifically I have a web application that uses the Cactus framework to run JUnit tests from a web interface. However the servlet that invokes the JUnit test runner is compiled in a jar; I added extra drop down menus to change settings from which the JUnit test will read from to switch between different environments (WLI clusters), so given that the runner servlet is already compiled I cannot modify it to handle the extra parameters from the multiple environments. I have tried the persistence approach of writing to a .dat file fro which the JUnit test will read from by way of a Reader class; also I have have tried the bean approach which ultimately was not accessible from the JUnit test.

答:
Yes, there is.

If you're using a web framework, for example Wicket, there is often a way to get the current HttpSession. From there, you can get the Spring ApplicationContext and if you have that, you can get Spring Beans from it. This works in any location, as we're using static utility methods only.

Example code:

```<code>import org.apache.wicket.protocol.http.WebApplication;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.WebApplicationContext;

ServletContext sc = WebApplication.getServletContext();
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);

Object bean = wac.getBean("myBeanId");
</code>```

Note however that the Spring Filter and the Wicket Filter must be in place and handle the current request, otherwise the utility methods won't work.

If you didn't mean Spring Beans, than you would have to store them in the HTTP Session yourself. If you do not have a web framework, you may want to do what rfeak is suggesting and implement your own ThreadLocal.

Body:
Yes, there is.

If you're using a web framework, for example Wicket, there is often a way to get the current HttpSession. From there, you can get the Spring ApplicationContext and if you have that, you can get Spring Beans from it. This works in any location, as we're using static utility methods only.

Example code:

import org.apache.wicket.protocol.http.WebApplication;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.WebApplicationContext;

ServletContext sc = WebApplication.getServletContext();
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);

Object bean = wac.getBean("myBeanId");

Note however that the Spring Filter and the Wicket Filter must be in place and handle the current request, otherwise the utility methods won't work.

If you didn't mean Spring Beans, than you would have to store them in the HTTP Session yourself. If you do not have a web framework, you may want to do what rfeak is suggesting and implement your own ThreadLocal.


问:
Python / Kivy Initial Variable Assignment
I'm relatively new to Python and OOP, and going through the Kivy documentation and found some syntax I was not used to seeing. I am not really sure how to search for the answer since I don't know what to call this type of syntax, so I'll illustrate with the code itself.

Here is the code from the kivy docs:

```<code>import kivy
kivy.require('1.0.5')

from kivy.uix.floatlayout import FloatLayout
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty

class Controller(FloatLayout):
    '''Create a controller that receives a custom widget from the kv lang file.

    Add an action to be called from the kv lang file.
    '''
    label_wid = ObjectProperty()
    info = StringProperty()

    def do_action(self):
        self.label_wid.text = 'My label after button press'
        self.info = 'New info text'

class ControllerApp(App):

    def build(self):
        return Controller(info='Hello world')

if __name__ == '__main__':
    ControllerApp().run()
</code>```

When the above code runs

```<code>return Controller(info='Hello world')
</code>```

I understand that it is setting a value for Controller().info (or controller_object_instance.info within the kivy.app.build() code), but I don't understand how this string assignment to the variable 'info' works, since I would think you would need an init() function at the top of the class to accept this assignment. Since there is no init() within the Controller() class, why doesn't

```<code>Controller(info='Hello world')
</code>```

throw an error? How does the above line of code know to properly assign the value 'Hello world' to its own attribute 'info'? Is there some init() function inherited from App and this can someone be used or does it have something to do with these two lines of code?

```<code>label_wid = ObjectProperty()
info = StringProperty()
</code>```

Any help appreciated. Just looking for a way to search for this more on my own, and I'm stuck on what topic to search for.

答:
When you created the class Controller, you wanted to inherit the class FloatLayout.

This means, whenever you create a Controller object, you create a FloatLayout which you extended. So the __init__ function from FloatLayout at executes.

Look at this example:

```<code>class Animal:

    def __init__(self,**kwargs):
        self.info = kwargs.get("info")

class Dog(Animal):

    pass

obj = Dog(info="Hello world")

print(obj.info)
</code>```

Now you want to create a Dog, but a dog is also an Animal, so you want to inherit all it's methods and attributes.

So if you pass info as an argument when creating an instance of Dog, it will be passed to Animal's __init__ function.

Body:
I'm relatively new to Python and OOP, and going through the Kivy documentation and found some syntax I was not used to seeing. I am not really sure how to search for the answer since I don't know what to call this type of syntax, so I'll illustrate with the code itself.

Here is the code from the kivy docs:

import kivy
kivy.require('1.0.5')

from kivy.uix.floatlayout import FloatLayout
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty

class Controller(FloatLayout):
    '''Create a controller that receives a custom widget from the kv lang file.

    Add an action to be called from the kv lang file.
    '''
    label_wid = ObjectProperty()
    info = StringProperty()

    def do_action(self):
        self.label_wid.text = 'My label after button press'
        self.info = 'New info text'

class ControllerApp(App):

    def build(self):
        return Controller(info='Hello world')

if __name__ == '__main__':
    ControllerApp().run()

When the above code runs

return Controller(info='Hello world')

I understand that it is setting a value for Controller().info (or controller_object_instance.info within the kivy.app.build() code), but I don't understand how this string assignment to the variable 'info' works, since I would think you would need an init() function at the top of the class to accept this assignment. Since there is no init() within the Controller() class, why doesn't

Controller(info='Hello world')

throw an error? How does the above line of code know to properly assign the value 'Hello world' to its own attribute 'info'? Is there some init() function inherited from App and this can someone be used or does it have something to do with these two lines of code?

label_wid = ObjectProperty()
info = StringProperty()

Any help appreciated. Just looking for a way to search for this more on my own, and I'm stuck on what topic to search for.

Body:
When you created the class Controller, you wanted to inherit the class FloatLayout.

This means, whenever you create a Controller object, you create a FloatLayout which you extended. So the __init__ function from FloatLayout at executes.

Look at this example:

class Animal:

    def __init__(self,**kwargs):
        self.info = kwargs.get("info")

class Dog(Animal):

    pass

obj = Dog(info="Hello world")

print(obj.info)

Now you want to create a Dog, but a dog is also an Animal, so you want to inherit all it's methods and attributes.

So if you pass info as an argument when creating an instance of Dog, it will be passed to Animal's __init__ function.


问:
What alternative do I have to a Left Join in this query?
I have this query that is used in a SSRS report that someone else created. The left join is the cause of the problem. If I change it to an inner join I get results (not the correct results) in about 15 seconds. With the Left Join I end up canceling the query after 20 minutes.  I added an index to both Budgets.Professionals and Transactions.Professionals with no change in performance. Is there a way to rewrite the query and not use the Left Join?</p>

```<code>SELECT
profs.ProfName as orig
,profs.Initials
,DATEPART(year, TransDate) as [Year]
,SUM(CASE WHEN IsFlatFee = 'Y'  OR COALESCE(MT.Admin, 'N') = 'Y'
    THEN 0.0
    ELSE Units * (aph.assignedpercent/100) * isnull(B.rate, 0.0)
    END) AS ctp
,SUM(CASE WHEN IsFlatFee = 'Y'  OR COALESCE(MT.Admin, 'N') = 'Y'
    THEN 0
    ELSE Units
    END * (aph.assignedpercent/100)) AS worked_hours
,SUM(Value * (aph.assignedpercent/100)) AS worked_value
, 0 AS billed_hours
,0 AS billed_value
,0 AS billed_netamt
, 0.0 as paid
, 0.0 as wo
FROM Transactions Trans
INNER JOIN Matters Matts ON Trans.matters  = Matts.matters
INNER JOIN MatterTypes MT ON Matts.mattertype  = MT.mattertypesdesc
and MT.Admin <> 'Y'
INNER JOIN Components Comps ON Comps.components  = Trans.components
and Comps.CompType = 'F'
INNER JOIN AssignedProfsHistory APH on APH.Matters = Trans.Matters
and APH.AssignedType = 'Originating'
and Trans.TransDate between APH.EffectiveDate and
ISNULL(EndDate,'12/31/2099')
INNER JOIN  Professionals profs on profs.Professionals  = APH.Professionals
    and profs.ProfType = 'Member'
    and profs.IsActive = 'Y'
    and profs.IsBillable = 'Y'
**LEFT join** (SELECT Budgets.Professionals as timekeeper, Budgets.Amount as
rate, Budgets.PeriodDate
FROM Matters Matts
INNER JOIN Budgets ON Matts.matters  = Budgets.matters
    and cast(Budgets.PeriodDate as Date) <= '2017-12-31'
    AND MONTH('2017-12-31') = MONTH(Budgets.PeriodDate)
WHERE Matts.MatterID  = '99999-99.003') as B
    *on B.timekeeper = Trans.Professionals*
    and YEAR(B.PeriodDate) = DATEPART(year, TransDate)
WHERE cast(transdate as DATE) between dateadd(day, 1, DATEADD(year, -3,
'2017-12-31')) and '2017-12-31'
GROUP BY profs.ProfName, profs.Initials, DATEPART(year, TransDate)
</code>```

答:
As Sean and Aaron said. There are too many things that are potentially an issue.

You seem (I'm guessing from column names) that you are joining on text columns mattertypesdesc for one. In fact most of the work is done against text columns. Even Matts.MatterID is textual. This may not be possible in your scenario but it would perform better if the tables had integer primary keys and you join on those.

Anyway, guessing aside.... You might get a quick win if you replace your sub query in the left join with a temp table.

so before you existing query just do ...

```<code>SELECT Budgets.Professionals as timekeeper, Budgets.Amount as rate, Budgets.PeriodDate
INTO #t
FROM Matters Matts
INNER JOIN Budgets ON Matts.matters  = Budgets.matters
    and cast(Budgets.PeriodDate as Date) <= '2017-12-31'
    AND MONTH('2017-12-31') = MONTH(Budgets.PeriodDate)
WHERE Matts.MatterID  = '99999-99.003'
</code>```

then in your exisintg query, replace the subquery with

```<code>SELECT ...
...
...
LEFT JOIN #t as B
    ON B.timekeeper = Trans.Professionals
    ....
</code>```

Body:
I have this query that is used in a SSRS report that someone else created. The left join is the cause of the problem. If I change it to an inner join I get results (not the correct results) in about 15 seconds. With the Left Join I end up canceling the query after 20 minutes.  I added an index to both Budgets.Professionals and Transactions.Professionals with no change in performance. Is there a way to rewrite the query and not use the Left Join?

SELECT
profs.ProfName as orig
,profs.Initials
,DATEPART(year, TransDate) as [Year]
,SUM(CASE WHEN IsFlatFee = 'Y'  OR COALESCE(MT.Admin, 'N') = 'Y'
    THEN 0.0
    ELSE Units * (aph.assignedpercent/100) * isnull(B.rate, 0.0)
    END) AS ctp
,SUM(CASE WHEN IsFlatFee = 'Y'  OR COALESCE(MT.Admin, 'N') = 'Y'
    THEN 0
    ELSE Units
    END * (aph.assignedpercent/100)) AS worked_hours
,SUM(Value * (aph.assignedpercent/100)) AS worked_value
, 0 AS billed_hours
,0 AS billed_value
,0 AS billed_netamt
, 0.0 as paid
, 0.0 as wo
FROM Transactions Trans
INNER JOIN Matters Matts ON Trans.matters  = Matts.matters
INNER JOIN MatterTypes MT ON Matts.mattertype  = MT.mattertypesdesc
and MT.Admin <> 'Y'
INNER JOIN Components Comps ON Comps.components  = Trans.components
and Comps.CompType = 'F'
INNER JOIN AssignedProfsHistory APH on APH.Matters = Trans.Matters
and APH.AssignedType = 'Originating'
and Trans.TransDate between APH.EffectiveDate and
ISNULL(EndDate,'12/31/2099')
INNER JOIN  Professionals profs on profs.Professionals  = APH.Professionals
    and profs.ProfType = 'Member'
    and profs.IsActive = 'Y'
    and profs.IsBillable = 'Y'
**LEFT join** (SELECT Budgets.Professionals as timekeeper, Budgets.Amount as
rate, Budgets.PeriodDate
FROM Matters Matts
INNER JOIN Budgets ON Matts.matters  = Budgets.matters
    and cast(Budgets.PeriodDate as Date) <= '2017-12-31'
    AND MONTH('2017-12-31') = MONTH(Budgets.PeriodDate)
WHERE Matts.MatterID  = '99999-99.003') as B
    *on B.timekeeper = Trans.Professionals*
    and YEAR(B.PeriodDate) = DATEPART(year, TransDate)
WHERE cast(transdate as DATE) between dateadd(day, 1, DATEADD(year, -3,
'2017-12-31')) and '2017-12-31'
GROUP BY profs.ProfName, profs.Initials, DATEPART(year, TransDate)

Body:
As Sean and Aaron said. There are too many things that are potentially an issue.

You seem (I'm guessing from column names) that you are joining on text columns mattertypesdesc for one. In fact most of the work is done against text columns. Even Matts.MatterID is textual. This may not be possible in your scenario but it would perform better if the tables had integer primary keys and you join on those.

Anyway, guessing aside.... You might get a quick win if you replace your sub query in the left join with a temp table.

so before you existing query just do ...

SELECT Budgets.Professionals as timekeeper, Budgets.Amount as rate, Budgets.PeriodDate
INTO #t
FROM Matters Matts
INNER JOIN Budgets ON Matts.matters  = Budgets.matters
    and cast(Budgets.PeriodDate as Date) <= '2017-12-31'
    AND MONTH('2017-12-31') = MONTH(Budgets.PeriodDate)
WHERE Matts.MatterID  = '99999-99.003'

then in your exisintg query, replace the subquery with

SELECT ...
...
...
LEFT JOIN #t as B
    ON B.timekeeper = Trans.Professionals
    ....


问:
Free memory after using sql server
Is there any way to free memory after using sql server. I don't know why it doesn't doing itself

Screen From Manager

I have this problem after using Visual Studio with SSIS to LookUp

答: The memory manager will release memory when the OS "asks" for it. Stop trying to micro manage your instance. And task manager is not an accurate way to measure memory in a server instance. </p>

Title: Free memory after using sql server


问:
Gradient Descent For Mutivariate Linear Regression

Ok, so what does this algorithm exactly mean?

What I know :

i) alpha : how big the step for gradient descent will be.

ii) Now , ∑{ hTheta[x(i)] - y(i) } : refers to Total Error with given values of Theta.

The error refers to the difference between predicted value{ hTheta[x(i)] } and the actual value.[ y(i) ]

∑{ hTheta[x(i)] - y(i) } gives us the summation of all errors from all training examples.

What does Xj^(i) at the end stand for?

Are we doing the following while implementing Gradient Descent for multiple variable Linear Regression?

Theta (j) minus:

alpha

times 1/m

times:

{ error of first training example multiplied by jth element of first training example. PLUS

error of second training example mutiplied by jth element of second training example. PLUS

.

.

.

PLUS error of nth training example multiplied by jth element of nth training example. }

答:
Gradient Descent is an iterative algorithm for finding the minimum of a function. When given a convex function, it is guaranteed to find the global minimum of the function given small enough alpha. Here is gradient descent algorithm to find the minimum of function J:

The idea is to move the parameter in the opposite direction of the gradient at learning rate alpha. Eventually it will go down to the minimum of the function.

We can rewrite this parameter update for each axis of theta:

In multivariate linear regression, the goal of the optimization is to minimize the sum of squared errors:

The partial derivative of this cost function can be derived by using differentiation by substitution, where we use elementary power rule, substracting the power 2 to 1 and putting 2 as coefficient, eliminating the 1/2 coefficient. Then we put the derivative of h(x) to theta_j, which is x_j to the right.

Here, x_j^(i) is stands for the partial derivative of h_theta(x^(i)) to theta_j. x_j^(i) is the j-th element of i-th data.


问:
React state is array of objects which are react elements
I'm running into an issue right now trying to render a list using react, where I'm saving my react elements into the state, but the problem I'm getting is that the console outputs this:

Uncaught Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

Here is what the state looks like which causes the error:

export default class UserData extends Component {
  constructor() {
    super();
    this.state = {
      resultsItems: {}
    }
  };

  componentDidMount() {

    fetch(url)
      .then(results => {
        return results.json();
      }).then(data => {
        console.log(data.items);
        let items = data.items.map((item) => {
          console.log(item.title);
          return (

item.title

          )
        });

        this.setState({resultsItems: items});
        console.log("state", this.state.resultsItems);
      })
      .catch(error => console.log(error))
  };

  render() {
    return (

        <button onClick={() => this.props.updateLoginStatus(false)}>
          Logout
        </button>

          ID: {this.props.user}
          {this.state.resultsItems}

    )
  }
}```

答:
By way of demonstrating the sort of thing Hamms is talking about in their comment:

```<code>class UserData extends Component {
  constructor () {
    super()
    this.state = {
      resultsItems: []
    }
  }

  componentDidMount () {
    // Simulate API response
    const resultsItems = [
      { title: 'foo' },
      { title: 'bar' },
      { title: 'wombat' }
    ]
    this.setState({ resultsItems })
  }

  render () {
    return (
      <div>
        {this.state.resultsItems.map(item => <ResultsItem item={item} />)}
      </div>
    )
  }
}

function ResultsItem ({ item }) {
  return <li>{item.title}</li>
}
</code>```

However, Chris' answer is correct as to the cause of the error message: the first render tries to use an empty object and not an array, which fails.

Body:
By way of demonstrating the sort of thing Hamms is talking about in their comment:

class UserData extends Component {
  constructor () {
    super()
    this.state = {
      resultsItems: []
    }
  }

  componentDidMount () {
    // Simulate API response
    const resultsItems = [
      { title: 'foo' },
      { title: 'bar' },
      { title: 'wombat' }
    ]
    this.setState({ resultsItems })
  }

  render () {
    return (
      <div>
        {this.state.resultsItems.map(item => <ResultsItem item={item} />)}
      </div>
    )
  }
}

function ResultsItem ({ item }) {
  return <li>{item.title}</li>
}

However, Chris' answer is correct as to the cause of the error message: the first render tries to use an empty object and not an array, which fails.


问:
tkinter - pictures from for loop do not appear

I'm making a tkinter application in python, in which I have a frame where I want to show 4-5 pictures. The code above the hashtags is working fine, it shows 1 pictures.

But the code below the picture is bad for some reason. It doesn't show anything, but it should show 4 pictures. Do I need to make a list from the PhotoImages or is something wrong with the self-s?

Thanks

```<code>    self.photo = PhotoImage(file=onlyfiles[0])
    self.photo = self.photo.subsample(4, 4)
    label=Label(self, image=self.photo)
    label.pack()
    ################################################
    image_labels = []
    for i in range(len(onlyfiles)): # 4
        self.gombi = PhotoImage(file=onlyfiles[i])
        self.gombi = self.gombi.subsample(4, 4)
        image_labels.append(Label(self, image=self.gombi))
        image_labels[i].pack()
</code>```

答:
Python does automatic garbage collection, so your images are probably getting gobbled up, even though you think they should still be there. Try storing references to your self.gombi values in another array, as well. That will most likely do the trick.

Try something like this:

```<code>self.photo = PhotoImage(file=onlyfiles[0])
self.photo = self.photo.subsample(4, 4)
label=Label(self, image=self.photo)
label.pack()
################################################
self.image_labels = []
self.image_gombis = []
for i in range(len(onlyfiles)): # 4
    gombi = PhotoImage(file=onlyfiles[i])
    gombi = gombi.subsample(4, 4)
    self.image_gombis.append(gombi)
    self.image_labels.append(Label(self, image=gombi))
    self.image_labels[i].pack()
</code>```

I haven't tried to run this, but it should put you on the right path...

Body:
I'm making a tkinter application in python, in which I have a frame where I want to show 4-5 pictures. The code above the hashtags is working fine, it shows 1 pictures.

But the code below the picture is bad for some reason. It doesn't show anything, but it should show 4 pictures. Do I need to make a list from the PhotoImages or is something wrong with the self-s?

Thanks

    self.photo = PhotoImage(file=onlyfiles[0])
    self.photo = self.photo.subsample(4, 4)
    label=Label(self, image=self.photo)
    label.pack()
    ################################################
    image_labels = []
    for i in range(len(onlyfiles)): # 4
        self.gombi = PhotoImage(file=onlyfiles[i])
        self.gombi = self.gombi.subsample(4, 4)
        image_labels.append(Label(self, image=self.gombi))
        image_labels[i].pack()

Body:
Python does automatic garbage collection, so your images are probably getting gobbled up, even though you think they should still be there. Try storing references to your self.gombi values in another array, as well. That will most likely do the trick.

Try something like this:

self.photo = PhotoImage(file=onlyfiles[0])
self.photo = self.photo.subsample(4, 4)
label=Label(self, image=self.photo)
label.pack()
################################################
self.image_labels = []
self.image_gombis = []
for i in range(len(onlyfiles)): # 4
    gombi = PhotoImage(file=onlyfiles[i])
    gombi = gombi.subsample(4, 4)
    self.image_gombis.append(gombi)
    self.image_labels.append(Label(self, image=gombi))
    self.image_labels[i].pack()

I haven't tried to run this, but it should put you on the right path...


问:
Insert table into QTextEdit with PyQt4
How can I insert a tabel inside a QTextEdit to be printed on A4 paper. I wrote this code but I don't know how I can insert it into the value, just insert first cell:</p>

```<code>self.text = QtGui.QTextEdit()
self.cursor = QtGui.QTextCursor()
self.cursor = self.text.textCursor()
self.cursor.insertTable(2, 5)
self.cursor.insertText("first cell ")
</code>```

答:
Maybe late, but still could be useful for somebody else :)
There are two good options how to insert a table into QTextEdit.

The first one, as mentioned above, is with the means of cursor.
Example:

```<code>headers = ["Number", "Name", "Surname"]
rows = [["1", "Maik", "Mustermann"],
        ["2", "Tom", "Jerry"],
        ["3", "Jonny", "Brown"]]
cursor = results_text.textCursor()
cursor.insertTable(len(rows) + 1, len(headers))
for header in headers:
    cursor.insertText(header)
    cursor.movePosition(QTextCursor.NextCell)
for row in rows:
    for value in row:
        cursor.insertText(str(value))
        cursor.movePosition(QTextCursor.NextCell)
</code>```

The result then looks like following:

There is also another way to do this, and get more beautiful result. Use jinja2 package, as in the example:

```<code>headers = ["Number", "Name", "Surname"]
rows = [["1", "Maik", "Mustermann"],
        ["2", "Tom", "Jerry"],
        ["3", "Jonny", "Brown"]]

from jinja2 import Template
table = """
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: center;
    padding: 8px;
}
</style>

<table border="1" width="100%">
    <tr>{% for header in headers %}<th>{{header}}</th>{% endfor %}</tr>
    {% for row in rows %}<tr>
        {% for element in row %}<td>
            {{element}}
        </td>{% endfor %}
    </tr>{% endfor %}
</table>
"""
results_text.setText(Template(table).render(headers=headers, rows=rows))
</code>```

You get then the styled table, as in the next picture:

Title: Insert table into QTextEdit with PyQt4

Body:
How can I insert a tabel inside a QTextEdit to be printed on A4 paper. I wrote this code but I don't know how I can insert it into the value, just insert first cell:

self.text = QtGui.QTextEdit()
self.cursor = QtGui.QTextCursor()
self.cursor = self.text.textCursor()
self.cursor.insertTable(2, 5)
self.cursor.insertText("first cell ")

Body:
Maybe late, but still could be useful for somebody else :)
There are two good options how to insert a table into QTextEdit.

The first one, as mentioned above, is with the means of cursor.
Example:

headers = ["Number", "Name", "Surname"]
rows = [["1", "Maik", "Mustermann"],
        ["2", "Tom", "Jerry"],
        ["3", "Jonny", "Brown"]]
cursor = results_text.textCursor()
cursor.insertTable(len(rows) + 1, len(headers))
for header in headers:
    cursor.insertText(header)
    cursor.movePosition(QTextCursor.NextCell)
for row in rows:
    for value in row:
        cursor.insertText(str(value))
        cursor.movePosition(QTextCursor.NextCell)

The result then looks like following:

There is also another way to do this, and get more beautiful result. Use jinja2 package, as in the example:

headers = ["Number", "Name", "Surname"]
rows = [["1", "Maik", "Mustermann"],
        ["2", "Tom", "Jerry"],
        ["3", "Jonny", "Brown"]]

from jinja2 import Template
table = """
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: center;
    padding: 8px;
}
</style>

<table border="1" width="100%">
    <tr>{% for header in headers %}<th>{{header}}</th>{% endfor %}</tr>
    {% for row in rows %}<tr>
        {% for element in row %}<td>
            {{element}}
        </td>{% endfor %}
    </tr>{% endfor %}
</table>
"""
results_text.setText(Template(table).render(headers=headers, rows=rows))

You get then the styled table, as in the next picture:


问:
Check signature of iOS app
Is it possible to check if iOS application is signed by its developer at applications runtime? I tried to download .ipa of some apps and resigning them with my developer ID and almost all of them worked on my iOS device. But some of them didn't, so I guess they are somehow checking if signature has changed and forbidding them to run if it is.

I know, there is Code Signing Services for OSX, but I haven't found a way to do this in iOS.

Also I have read that after reviewing, apple signs application with their own signature. Are the _CodeSignature/CodeResources and embedded.mobileprovision files also changed during this process? Is it possible for me to check if it is signed with apples signature at runtime?

答:
I wrote a small signature checker (using openssl). It is available here:  https://github.com/elnormous/signature_check/blob/master/SignatureCheck/main.c

And the answer to the second question is no, _CodeSignature/CodeResources and embedded.mobileprovision are not being changed. Apple changes only the signature of the Mach-O file.

Title: Check signature of iOS app


问:
Safe to release UINavigationController?
I am creating a (UIPopoverController) popover controller and (UINavigationController) navigation controller for the popover, where both controllers are declared in the header file.  Then, when they are created:

```<code>myNavController = [[UINavigationController alloc] initWithRootViewController:[[[MyPopoverControllerClass alloc] initWithNibName:@"MyPopoverNib" bundle:[NSBundle mainBundle]]autorelease]];

myPopoverController = [[UIPopoverController alloc] initWithContentViewController:myNavController];
</code>```

At this point, is it safe to release myNavController?

答:
Just think about Object Ownership and Disposal convention which briefly says that if you've alloc'ed an object, you are its owner.

In other words, you are in all rights to release myNavController as soon as you don't need it.

From another side, UIPopoverController should take ownership over myNavController using retain.

So, (again) yes. You can safely release myNavController.

There are some rare situations when ownership convention rules not respected. These kind of exceptions are mentioned in documentation for specific methods. But here is not the case.

Lets apply these rules for your snippet:
In the first line

```<code>  myNavController = [[UINavigationController alloc] initWithRootViewController:[[[MyPopoverControllerClass alloc] initWithNibName:@"MyPopoverNib" bundle:[NSBundle mainBundle]]autorelease]];
</code>```

retain count for myNavController is at least 1.

The second line

```<code>myPopoverController = [[UIPopoverController alloc] initWithContentViewController:myNavController];
</code>```

will result in retain count for  myNavController to be at least 2, through ownership taken inside initWithContentViewController.

Title: Safe to release UINavigationController?

Body:
I am creating a (UIPopoverController) popover controller and (UINavigationController) navigation controller for the popover, where both controllers are declared in the header file.  Then, when they are created:

myNavController = [[UINavigationController alloc] initWithRootViewController:[[[MyPopoverControllerClass alloc] initWithNibName:@"MyPopoverNib" bundle:[NSBundle mainBundle]]autorelease]];

myPopoverController = [[UIPopoverController alloc] initWithContentViewController:myNavController];

At this point, is it safe to release myNavController?

Body:
Just think about Object Ownership and Disposal convention which briefly says that if you've alloc'ed an object, you are its owner.

In other words, you are in all rights to release myNavController as soon as you don't need it.

From another side, UIPopoverController should take ownership over myNavController using retain.

So, (again) yes. You can safely release myNavController.

There are some rare situations when ownership convention rules not respected. These kind of exceptions are mentioned in documentation for specific methods. But here is not the case.

Lets apply these rules for your snippet:
In the first line

  myNavController = [[UINavigationController alloc] initWithRootViewController:[[[MyPopoverControllerClass alloc] initWithNibName:@"MyPopoverNib" bundle:[NSBundle mainBundle]]autorelease]];

retain count for myNavController is at least 1.

The second line

myPopoverController = [[UIPopoverController alloc] initWithContentViewController:myNavController];

will result in retain count for  myNavController to be at least 2, through ownership taken inside initWithContentViewController.


问:
Highstock Time series not formatting on scatter tooltip
When you have defined the xAxis as a 'dateTime' type the tooltip should be aware of this as the 'point.x' value and convert it to the DateTime format.

```<code>xAxis: {
        title: {
            enabled: true,
            text: 'Time Range'
        },
        type: "datetime"
    },
</code>```

I would expect the tooltip to provide me with the Readable Datetime

http://jsfiddle.net/egf4vbfL/6/

As you can see the X-Axis is correct in that it uses the Time rage however when you view the default tooltip you get the epoch time.

I know you can format this using 'point.key' etc but for every other chart time it works as expected.

Is this a bug with highstock or some expected behavior ?

If expected can someone point out why ?

Note : Same issue applies to highcharts.

答:
With a datetime axis, the x-value in your series data should be a Date. As in this fiddle:

http://jsfiddle.net/Jelmerjellema/egf4vbfL/32/

This will show an ugly formatted date. To show a nicely formated date, you should be able to use tooltip.xDateFormat but that does not work. You can use forced date grouping, is a describe in my own question: Highchart / Highstock shows unformated tooltip lable when data grouping enabled but not used

Body:
When you have defined the xAxis as a 'dateTime' type the tooltip should be aware of this as the 'point.x' value and convert it to the DateTime format.

xAxis: {
        title: {
            enabled: true,
            text: 'Time Range'
        },
        type: "datetime"
    },

I would expect the tooltip to provide me with the Readable Datetime

http://jsfiddle.net/egf4vbfL/6/

As you can see the X-Axis is correct in that it uses the Time rage however when you view the default tooltip you get the epoch time.

I know you can format this using 'point.key' etc but for every other chart time it works as expected.

Is this a bug with highstock or some expected behavior ?

If expected can someone point out why ?

Note : Same issue applies to highcharts.


问:
Pandas DataReader work-around for Google finance
I pull historical data for a large universe of stocks and ETFs daily. Quandl has pretty good free coverage of US Equities, but they do not have historical data for ETFs so I use the Google API as a backup for Quandl.

The recent Google finance "renovation" hasn't left me with a great alternative, so I am trying to apply Brad Solomon's work (thanks Brad, link below) to a list of symbols. Assume it is unlikely without a loop given that he is creating URLs. Any clever ideas welcome.

Related question: How come pandas_datareader for google doesn't work?

Thanks.

答:
Under the hood, pandas-datareader is looping through each symbol that you pass and making http requests one by one.

Here's the function that does that in the base class, from which the google- and yahoo-related classes inherit: base._DailyBaseReader._dl_mult_symbols.

The magic is that these are appended to a list and then aggregated into a pandas Panel.

I would note, however, that Panel is deprecated and you can get the same functionality in a DataFrame with a MultiIndex, a structure that's technically 2-dimenionsal but replicates higher dimensionalities in practice.

So, here's the barebones of what you could do, below.  Please note I'm skipping a lot of the functionality embedded within the package itself, such as parsing string dates to datetime.

```<code>import datetime
from io import StringIO

import requests
from pandas.io.common import urlencode
import pandas as pd

BASE = 'http://finance.google.com/finance/historical'

def get_params(sym, start, end):
    params = {
        'q': sym,
        'startdate': start.strftime('%Y/%m/%d'),
        'enddate': end.strftime('%Y/%m/%d'),
        'output': "csv"
    }
    return params

def build_url(sym, start, end):
    params = get_params(sym, start, end)
    return BASE + '?' + urlencode(params)

def get_one_data(sym, start=None, end=None):
    if not start:
        start = datetime.datetime(2010, 1, 1)
    if not end:
        end = datetime.datetime.today()
    url = build_url(sym, start, end)
    data = requests.get(url).text
    return pd.read_csv(StringIO(data), index_col='Date',
                       parse_dates=True).sort_index()

def get_multiple(sym, start=None, end=None, return_type='Panel'):
    if isinstance(sym, str):
        return get_one_data(sym, start=start, end=end)
    elif isinstance(sym, (list, tuple, set)):
        res = {}
        for s in sym:
            res[s] = get_one_data(s, start, end)
        # The actual module also implements a 'passed' and 'failed'
        #     check here and also using chunking to get around
        #     data retreival limits (I believe)

    if return_type.lower() == 'panel':
        return pd.Panel(res).swapaxes('items', 'minor')
    elif return_type.lower() == 'mi':  # MultiIndex DataFrame
        return pd.concat((res), axis=1)
</code>```

An example:

```<code>syms = ['AAPL', 'GE']
data = get_multiple(syms, return_type='mi')

# Here's how you would filter down to Close prices
#   on MultiIndex columns
data.xs('Close', axis=1, level=1)

              AAPL     GE
Date
2010-01-04   30.57  15.45
2010-01-05   30.63  15.53
2010-01-06   30.14  15.45
2010-01-07   30.08  16.25
2010-01-08   30.28  16.60
...
</code>```

Body:
Under the hood, pandas-datareader is looping through each symbol that you pass and making http requests one by one.

Here's the function that does that in the base class, from which the google- and yahoo-related classes inherit: base._DailyBaseReader._dl_mult_symbols.

The magic is that these are appended to a list and then aggregated into a pandas Panel.

I would note, however, that Panel is deprecated and you can get the same functionality in a DataFrame with a MultiIndex, a structure that's technically 2-dimenionsal but replicates higher dimensionalities in practice.

So, here's the barebones of what you could do, below.  Please note I'm skipping a lot of the functionality embedded within the package itself, such as parsing string dates to datetime.

import datetime
from io import StringIO

import requests
from pandas.io.common import urlencode
import pandas as pd

BASE = 'http://finance.google.com/finance/historical'

def get_params(sym, start, end):
    params = {
        'q': sym,
        'startdate': start.strftime('%Y/%m/%d'),
        'enddate': end.strftime('%Y/%m/%d'),
        'output': "csv"
    }
    return params

def build_url(sym, start, end):
    params = get_params(sym, start, end)
    return BASE + '?' + urlencode(params)

def get_one_data(sym, start=None, end=None):
    if not start:
        start = datetime.datetime(2010, 1, 1)
    if not end:
        end = datetime.datetime.today()
    url = build_url(sym, start, end)
    data = requests.get(url).text
    return pd.read_csv(StringIO(data), index_col='Date',
                       parse_dates=True).sort_index()

def get_multiple(sym, start=None, end=None, return_type='Panel'):
    if isinstance(sym, str):
        return get_one_data(sym, start=start, end=end)
    elif isinstance(sym, (list, tuple, set)):
        res = {}
        for s in sym:
            res[s] = get_one_data(s, start, end)
        # The actual module also implements a 'passed' and 'failed'
        #     check here and also using chunking to get around
        #     data retreival limits (I believe)

    if return_type.lower() == 'panel':
        return pd.Panel(res).swapaxes('items', 'minor')
    elif return_type.lower() == 'mi':  # MultiIndex DataFrame
        return pd.concat((res), axis=1)

An example:

syms = ['AAPL', 'GE']
data = get_multiple(syms, return_type='mi')

# Here's how you would filter down to Close prices
#   on MultiIndex columns
data.xs('Close', axis=1, level=1)

              AAPL     GE
Date
2010-01-04   30.57  15.45
2010-01-05   30.63  15.53
2010-01-06   30.14  15.45
2010-01-07   30.08  16.25
2010-01-08   30.28  16.60
...


问:
Errors in Code (Need Help)
I am trying to get this code to work, as it is essential for a project that I am currently working on.

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

public class BinarySearch
{
    int binarySearch(int arr[], int l, int r, int x)
    {
        if (r>=l)
    {
        int mid = l + (r - l)/2;

        if (arr[mid] == x)
           return mid;

        if (arr[mid] > x)
           return binarySearch(arr, l, mid-1, x);

        return binarySearch(arr, mid+1, r, x);
    }
    return -1;
}

public static void main(String args[])
{
    BinarySearch ob = new BinarySearch();
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of inputs:");
        int i = sc.nextInt();
        int arr[] = new int[i];
    System.out.println("Enter array of inputs:");
        for(int j = 0;j < i; j++){
            arr[j] = sc.nextInt();
    }
    System.out.println("What number do you want the index from");
        int n = arr.length;
        int x = sc.nextInt();
        int result = ob.binarySearch(arr,0,n-1,x);
        if (result == -1)
            System.out.println("FAILURE");
        else
            System.out.println("Element found at index "+result + ".");
    }
}
</code>```

I expect the result to be a normal input, in which the array can function.
The actual result I get is a Timeout error for "maybe having an endless loop."

答:
The binarySearch seems fine to me.

However binary search only works on an array sorted (by the comparison made).

A timeout indeed would mean that a loop or recursion would not end.
Considering

case for recursion: l <= r

given int mid = l + (r - l)/2

hence l <= mid && mid <= r

then binarySearch(arr, l, mid-1, x); works on [l, <r] (smaller)

then binarySearch(arr, mid+1, r, x); works on [>l, r] (smaller)

the recursion will terminate.

Even on an unordered array (yielding garbage).

It looks more like the usage of the Scanner is problematic. I did not see  a clean usage with hasNextLine, hasNextInt, nextInt and nextLine.

The class Arrays can provide a sort (and also has its own binarySearch).

Code

Not tested, and generally I do not use Scanner for System.in,
so probably can be written more succinct:

```<code>BinarySearch ob = new BinarySearch();
Scanner sc = new Scanner(System.in);

System.out.println("Enter number of inputs:");
if (sc.hasNextLine() && sc.hasNextInt()) {
    int i = sc.nextInt();
    sc.nextLine();

    int arr[] = new int[i];
    int n = arr.length;

    System.out.println("Enter array of inputs:");
    for (int j = 0; j < i; j++) {
        if (sc.hasNextLine() && sc.hasNextInt()) {
            arr[j] = sc.nextInt();
            sc.nextLine();
        } else {
            ...
            System.exit(1);
        }
    }

    // Important, binary search relies on the array being sorted:
    Arrays.sort(arr);
    System.out.printf("The sorted array is %s%n", Arrays.toString(arr));

    System.out.println("What number do you want the index from?");
    if (sc.hasNextLine() && sc.hasNextInt()) {
        int x = sc.nextInt();
        sc.nextLine();
        int result = ob.binarySearch(arr, 0, n-1, x);
</code>```

Title: Errors in Code (Need Help)

Body:
I am trying to get this code to work, as it is essential for a project that I am currently working on.

import java.util.Scanner;

public class BinarySearch
{
    int binarySearch(int arr[], int l, int r, int x)
    {
        if (r>=l)
    {
        int mid = l + (r - l)/2;

        if (arr[mid] == x)
           return mid;

        if (arr[mid] > x)
           return binarySearch(arr, l, mid-1, x);

        return binarySearch(arr, mid+1, r, x);
    }
    return -1;
}

public static void main(String args[])
{
    BinarySearch ob = new BinarySearch();
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of inputs:");
        int i = sc.nextInt();
        int arr[] = new int[i];
    System.out.println("Enter array of inputs:");
        for(int j = 0;j < i; j++){
            arr[j] = sc.nextInt();
    }
    System.out.println("What number do you want the index from");
        int n = arr.length;
        int x = sc.nextInt();
        int result = ob.binarySearch(arr,0,n-1,x);
        if (result == -1)
            System.out.println("FAILURE");
        else
            System.out.println("Element found at index "+result + ".");
    }
}

I expect the result to be a normal input, in which the array can function.
The actual result I get is a Timeout error for "maybe having an endless loop."

Body:
The binarySearch seems fine to me.

However binary search only works on an array sorted (by the comparison made).

A timeout indeed would mean that a loop or recursion would not end.
Considering

case for recursion: l <= r

given int mid = l + (r - l)/2

hence l <= mid && mid <= r

then binarySearch(arr, l, mid-1, x); works on [l, <r] (smaller)

then binarySearch(arr, mid+1, r, x); works on [>l, r] (smaller)

the recursion will terminate.

Even on an unordered array (yielding garbage).

It looks more like the usage of the Scanner is problematic. I did not see  a clean usage with hasNextLine, hasNextInt, nextInt and nextLine.

The class Arrays can provide a sort (and also has its own binarySearch).

Code

Not tested, and generally I do not use Scanner for System.in,
so probably can be written more succinct:

BinarySearch ob = new BinarySearch();
Scanner sc = new Scanner(System.in);

System.out.println("Enter number of inputs:");
if (sc.hasNextLine() && sc.hasNextInt()) {
    int i = sc.nextInt();
    sc.nextLine();

    int arr[] = new int[i];
    int n = arr.length;

    System.out.println("Enter array of inputs:");
    for (int j = 0; j < i; j++) {
        if (sc.hasNextLine() && sc.hasNextInt()) {
            arr[j] = sc.nextInt();
            sc.nextLine();
        } else {
            ...
            System.exit(1);
        }
    }

    // Important, binary search relies on the array being sorted:
    Arrays.sort(arr);
    System.out.printf("The sorted array is %s%n", Arrays.toString(arr));

    System.out.println("What number do you want the index from?");
    if (sc.hasNextLine() && sc.hasNextInt()) {
        int x = sc.nextInt();
        sc.nextLine();
        int result = ob.binarySearch(arr, 0, n-1, x);


问:
Laravel: Show multiple rows one by one under same id in a table
I have a table which has multiple rows under same id (quiz_id). I'm trying to show all of those rows one-by-one by clicking next button in the view file. In the picture below there are 2 quiz ids 1 and 2. Every Id has 3 questions. When a user first goes to my view page with quiz_id 1 they may see the 1st question and answer this. After, the user clicks next button and can answer 2nd question. Finally the 3rd.

Can anyone please tell me how to do this in Laravel 5.5? I am a newbie in Laravel and sorry for poor English.

答:
With the question, you asked it's hard to answer with such little detail.

I'm going to assume you have a controller and model "Question". You can use a for-loop in your blade file to achieve what you want.

```<code>class QuestionController extends Controller{
    public function showbyQuizId($id){
        $questions = Question::where('quiz_id', $id)->get();
        return view('question')->with('questions', $questions);
    }
}
</code>```

And for your blade file question.blade.php

```<code>@foreach($questions as $question)
    <h1>{{$question->question}} ?</h1>
    <p>Pick from these 4 options</p>

    <button>{{$question->choice1}}</button>
    <button>{{$question->choice2}}</button>
    <button>{{$question->choice3}}</button>
    <button>{{$question->choice4}}</button>
@endforeach
</code>```

From there you can set up a form or javascript to test if the selected button was correct with the server, and then redirect to the next question.

If you need any more help, let me know.

Body:
With the question, you asked it's hard to answer with such little detail.

I'm going to assume you have a controller and model "Question". You can use a for-loop in your blade file to achieve what you want.

class QuestionController extends Controller{
    public function showbyQuizId($id){
        $questions = Question::where('quiz_id', $id)->get();
        return view('question')->with('questions', $questions);
    }
}

And for your blade file question.blade.php

@foreach($questions as $question)
    <h1>{{$question->question}} ?</h1>
    <p>Pick from these 4 options</p>

    <button>{{$question->choice1}}</button>
    <button>{{$question->choice2}}</button>
    <button>{{$question->choice3}}</button>
    <button>{{$question->choice4}}</button>
@endforeach

From there you can set up a form or javascript to test if the selected button was correct with the server, and then redirect to the next question.

If you need any more help, let me know.