问:
CSS trouble to place buttom border under logos top right of the page
I'm trying to put a border under my  logos at the top of the page right.

Before I'm adding position:absolute; to the div, my 2 logos are placed where I want them to be under the contact me top right. But the border on the left side of the page, when I put position:absolute; it moves but the logos jump down the page.

css #para {
  margin-right: 1.66%;
  float: right;
  font-family: indie flower;
  position: absolute;
  top: 0px;
  right: 0px;
}

.fb {
  width: 27px;
  float: right;
  right: 5px;
  position: absolute;
  margin-top: 3px;
  top: 35px;
}

#in {
  margin-top: 4px;
  width: 25px;
  float: right;
  position: absolute;
  right: 40px;
  top: 35px;
}

div {
  border-bottom: 1.5px solid red;
  width: 60px;
  right: 5px;
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="para">Contact me </p>
<div>
  <img class="fb" width="10" src="https://cdn3.iconfinder.com/data/icons/picons-social/57/46-facebook-512.png">
  <img id="in" width="25" src="https://image.flaticon.com/icons/png/512/69/69366.png">
</div></code>```

答:
Just use float: right on your #para and div. Use a  with clear attribute to prevent div from overlapping. No need for any absolute positioning. As you can see this simplifies the code a lot.

```<code>.clear {
  display: block;
  clear: both;
}
</code>```

PS: Avoid adding CSS to tags like div.

#para {
  margin-right: 1.66%;
  float: right;
  font-family: indie flower;
}

.clear {
  display: block;
  clear: both;
}

.fb {
  width: 27px;
  margin-top: 3px;
}

#in {
  margin-top: 4px;
  width: 25px;
}

#icons {
  float: right;
  border-bottom: 1.5px solid red;
  width: 60px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="para">Contact me </p>
<span class="clear"></span>
<div id="icons">
  <img class="fb" src="https://cdn3.iconfinder.com/data/icons/picons-social/57/46-facebook-512.png">
  <img id="in" src="https://image.flaticon.com/icons/png/512/69/69366.png">
</div></code>```

Body:
I'm trying to put a border under my  logos at the top of the page right.

Before I'm adding position:absolute; to the div, my 2 logos are placed where I want them to be under the contact me top right. But the border on the left side of the page, when I put position:absolute; it moves but the logos jump down the page.

css #para {
  margin-right: 1.66%;
  float: right;
  font-family: indie flower;
  position: absolute;
  top: 0px;
  right: 0px;
}

.fb {
  width: 27px;
  float: right;
  right: 5px;
  position: absolute;
  margin-top: 3px;
  top: 35px;
}

#in {
  margin-top: 4px;
  width: 25px;
  float: right;
  position: absolute;
  right: 40px;
  top: 35px;
}

div {
  border-bottom: 1.5px solid red;
  width: 60px;
  right: 5px;
  position: absolute;
}

Contact me

Body:
Just use float: right on your #para and div. Use a <span> with clear attribute to prevent div from overlapping. No need for any absolute positioning. As you can see this simplifies the code a lot.

.clear {
  display: block;
  clear: both;
}

PS: Avoid adding CSS to tags like div.

#para {
  margin-right: 1.66%;
  float: right;
  font-family: indie flower;
}

.clear {
  display: block;
  clear: both;
}

.fb {
  width: 27px;
  margin-top: 3px;
}

#in {
  margin-top: 4px;
  width: 25px;
}

#icons {
  float: right;
  border-bottom: 1.5px solid red;
  width: 60px;
}

<p id="para">Contact me </p>
<span class="clear"></span>
<div id="icons">
  <img class="fb" src="https://cdn3.iconfinder.com/data/icons/picons-social/57/46-facebook-512.png">
  <img id="in" src="https://image.flaticon.com/icons/png/512/69/69366.png">
</div>


来源: stackexchange

问:
select large table in laravel 5
I would like to know how to get very large number of rows in the controller, and dispay it to the view. my current code looks likes below.

this is the controller.

```<code>$users = \App\Models\User::select ('id','first_name','last_name','created_at')
            ->where('friend_id', '=', 0)
            ->orderBy('created_at')->get();

return view('layouts.users.friends', compact('users'));
</code>```

this is the view.

```<code>@if (!empty($users))
                    @foreach($users as $user)
                        <tr>
                            <?php $count++ ?>
                            <td>
                                {!! $user->id !!}
                            </td>
                            <td>{!! $user->first_name .'   ' .$user->last_name !!}</td>
                            <td> {!! $user->created_at->format("d-m-y") !!} </td>
                        </tr>
                    @endforeach
                @endif
</code>```

Now i have 40,000 rows in the table, and when try to get the view error code 500, outof memory. I have to get all the rows. Please advice me what should be done. here. I have heard about laravel 5 chunk. but dont know who to display it on the view. Please help.

答:
There are few things that are possible here, The one I would personally attempt to do as a hack is to chunk the result and in the process assemble the view portion I need then pass it to the main view:

So you can have something like this:

```<code>$the_view = "";
\App\Models\User::select('id', 'first_name', 'last_name', 'created_at')
        ->where('friend_id', '=', 0)
        ->orderBy('created_at')->chunk(4000, function ($user_chunk) use (&$the_view) {
            foreach ($user_chunk as $user) {
                $the_view .= "<td >" . $user->id . "</td >" .
                    "<td >" . $user->first_name . " " . $user->last_name . "</td >" .
                    "<td > " . $user->created_at->format('d-m-y') .
                    " </td ></tr >";
            }
});
return view('layouts.users.friends', compact('the_view'));
</code>```

Then in your view, simply escape it as html:

```<code>{ !! $the_view !! }
</code>```

I will not say this is proven to work but I think it should.

Other Not recommended way is to play around with your memory limit example:

```<code>ini_set('memory_limit', '256M');
</code>```

PS: Like I said its not recommended. Try the chunk and see it gives an Idea of what you can do.

ContentLicense: CC BY-SA 3.0

Title: select large table in laravel 5

Body:
I would like to know how to get very large number of rows in the controller, and dispay it to the view. my current code looks likes below.

this is the controller.

$users = \App\Models\User::select ('id','first_name','last_name','created_at')
            ->where('friend_id', '=', 0)
            ->orderBy('created_at')->get();

return view('layouts.users.friends', compact('users'));

this is the view.

@if (!empty($users))
                    @foreach($users as $user)

                            <?php $count++ ?>

                                {!! $user->id !!}

                            {!! $user->first_name .'   ' .$user->last_name !!}
                             {!! $user->created_at->format("d-m-y") !!}

                    @endforeach
                @endif

Now i have 40,000 rows in the table, and when try to get the view error code 500, outof memory. I have to get all the rows. Please advice me what should be done. here. I have heard about laravel 5 chunk. but dont know who to display it on the view. Please help.

Body:
There are few things that are possible here, The one I would personally attempt to do as a hack is to chunk the result and in the process assemble the view portion I need then pass it to the main view:

So you can have something like this:

$the_view = "";
\App\Models\User::select('id', 'first_name', 'last_name', 'created_at')
        ->where('friend_id', '=', 0)
        ->orderBy('created_at')->chunk(4000, function ($user_chunk) use (&$the_view) {
            foreach ($user_chunk as $user) {
                $the_view .= "<td >" . $user->id . "</td >" .
                    "<td >" . $user->first_name . " " . $user->last_name . "</td >" .
                    "<td > " . $user->created_at->format('d-m-y') .
                    " </td ></tr >";
            }
});
return view('layouts.users.friends', compact('the_view'));

Then in your view, simply escape it as html:

{ !! $the_view !! }

I will not say this is proven to work but I think it should.

Other Not recommended way is to play around with your memory limit example:

ini_set('memory_limit', '256M');

PS: Like I said its not recommended. Try the chunk and see it gives an Idea of what you can do.


问:
Select values from multiple dictionaries into list of objects with LINQ
I want to select OrderId & Row from multiple dictionaries and create a list of Orders which contains a list of Rows.

The code I'm struggling with this far is:

```<code>var listOfDictionaries = new List<Dictionary<string, string>>();

var dict1 = new Dictionary<string, string>();
dict1.Add("OrderId", "12345");
dict1.Add("Row", "1");
listOfDictionaries.Add(dict1);

var dict2 = new Dictionary<string, string>();
dict2.Add("OrderId", "97845");
dict2.Add("Row", "10");
listOfDictionaries.Add(dict2);

var dict3 = new Dictionary<string, string>();
dict3.Add("OrderId", "12345");
dict3.Add("Row", "2");
listOfDictionaries.Add(dict3);

var grouped = listOfDictionaries.SelectMany(d =>
                 d.Where(kvp =>
                    kvp.Key.ToLower().Contains("orderid") || kvp.Key.ToLower().Contains("row")))
              .GroupBy(a => a.Key).ToList();

public class Order
{
    public Order()
    {
       OrderRows = new List<OrderRow>();
    }

    public string OrderId { get; set; }
    public List<OrderRow> OrderRows { get; set; }
}

public class OrderRow
{
    public string OrderRowId { get; set; }
}
</code>```

Anyone have a good idea how to solve this?

答:
Just like @Nikhil Agrawal said:

Check this

```<code>var result = listOfDictionaries
            .Select(x => new { OrderId = x["OrderId"], Row = x["Row"] })
            .GroupBy(x => x.OrderId)
            .Select(x => new Order{
                OrderId = x.Key,
                OrderRows = x.Select(y => new OrderRow{OrderRowId = y.Row}).ToList()
            });
</code>```

Body:
I want to select OrderId & Row from multiple dictionaries and create a list of Orders which contains a list of Rows.

The code I'm struggling with this far is:

var listOfDictionaries = new List<Dictionary<string, string>>();

var dict1 = new Dictionary<string, string>();
dict1.Add("OrderId", "12345");
dict1.Add("Row", "1");
listOfDictionaries.Add(dict1);

var dict2 = new Dictionary<string, string>();
dict2.Add("OrderId", "97845");
dict2.Add("Row", "10");
listOfDictionaries.Add(dict2);

var dict3 = new Dictionary<string, string>();
dict3.Add("OrderId", "12345");
dict3.Add("Row", "2");
listOfDictionaries.Add(dict3);

var grouped = listOfDictionaries.SelectMany(d =>
                 d.Where(kvp =>
                    kvp.Key.ToLower().Contains("orderid") || kvp.Key.ToLower().Contains("row")))
              .GroupBy(a => a.Key).ToList();

public class Order
{
    public Order()
    {
       OrderRows = new List<OrderRow>();
    }

    public string OrderId { get; set; }
    public List<OrderRow> OrderRows { get; set; }
}

public class OrderRow
{
    public string OrderRowId { get; set; }
}

Anyone have a good idea how to solve this?

Body:
Just like @Nikhil Agrawal said:

Check this

var result = listOfDictionaries
            .Select(x => new { OrderId = x["OrderId"], Row = x["Row"] })
            .GroupBy(x => x.OrderId)
            .Select(x => new Order{
                OrderId = x.Key,
                OrderRows = x.Select(y => new OrderRow{OrderRowId = y.Row}).ToList()
            });


问:
time difference in pandas with yesterday time
I have a pandas Dataframe that includes the times in the following format:

```<code>2017-05-02  00:00:00+00:00
2017-05-03  01:00:00+00:00
</code>```

I want to find their difference with a specific time in the previous day, say for the above example:

```<code>2017-05-01  10:00:00
2017-05-02  10:00:00
</code>```

I know that timedelta is the solution, but how I should use it?

答:
Use floor, substract one day and add 10 hours in Timedelatas to new Series dates which is substract from column date.

Advantage of solution is not necessary create helper column and then drop it.

```<code>print (df)
                        date
0  2017-05-02 00:00:00+00:00
1  2017-05-03 01:00:00+00:00

#if necessary convert to datetime
df['date']= pd.to_datetime(df['date'])
dates = df['date'].dt.floor('D') - pd.Timedelta(1, unit='d') + pd.Timedelta(10, unit='h')
print (dates)
0   2017-05-01 10:00:00
1   2017-05-02 10:00:00
Name: date, dtype: datetime64[ns]

df['timedelta'] = df['date'] - dates
print (df)
                 date timedelta
0 2017-05-02 00:00:00  14:00:00
1 2017-05-03 01:00:00  15:00:00
</code>```

For seconds from timedelata is possible use total_seconds and another solutions:

```<code>df['seconds'] = (df['date'] - dates).dt.total_seconds().astype(int)
print (df)
                 date  seconds
0 2017-05-02 00:00:00    50400
1 2017-05-03 01:00:00    54000
</code>```

Same solution, only with new column is better if also need new column for another processing:

```<code>df['date']= pd.to_datetime(df['date'])
df['new'] = df['date'].dt.floor('D') - pd.Timedelta(1, unit='d') + pd.Timedelta(10, unit='h')
print (df)
                 date                 new
0 2017-05-02 00:00:00 2017-05-01 10:00:00
1 2017-05-03 01:00:00 2017-05-02 10:00:00

df['seconds'] = (df['date'] - df['new']).dt.total_seconds().astype(int)
print (df)
                 date                 new  seconds
0 2017-05-02 00:00:00 2017-05-01 10:00:00    50400
1 2017-05-03 01:00:00 2017-05-02 10:00:00    54000
</code>```

Body:
I have a pandas Dataframe that includes the times in the following format:

2017-05-02  00:00:00+00:00
2017-05-03  01:00:00+00:00

I want to find their difference with a specific time in the previous day, say for the above example:

2017-05-01  10:00:00
2017-05-02  10:00:00

I know that timedelta is the solution, but how I should use it?

Body:
Use floor, substract one day and add 10 hours in Timedelatas to new Series dates which is substract from column date.

Advantage of solution is not necessary create helper column and then drop it.

print (df)
                        date
0  2017-05-02 00:00:00+00:00
1  2017-05-03 01:00:00+00:00

#if necessary convert to datetime
df['date']= pd.to_datetime(df['date'])
dates = df['date'].dt.floor('D') - pd.Timedelta(1, unit='d') + pd.Timedelta(10, unit='h')
print (dates)
0   2017-05-01 10:00:00
1   2017-05-02 10:00:00
Name: date, dtype: datetime64[ns]

df['timedelta'] = df['date'] - dates
print (df)
                 date timedelta
0 2017-05-02 00:00:00  14:00:00
1 2017-05-03 01:00:00  15:00:00

For seconds from timedelata is possible use total_seconds and another solutions:

df['seconds'] = (df['date'] - dates).dt.total_seconds().astype(int)
print (df)
                 date  seconds
0 2017-05-02 00:00:00    50400
1 2017-05-03 01:00:00    54000

Same solution, only with new column is better if also need new column for another processing:

df['date']= pd.to_datetime(df['date'])
df['new'] = df['date'].dt.floor('D') - pd.Timedelta(1, unit='d') + pd.Timedelta(10, unit='h')
print (df)
                 date                 new
0 2017-05-02 00:00:00 2017-05-01 10:00:00
1 2017-05-03 01:00:00 2017-05-02 10:00:00

df['seconds'] = (df['date'] - df['new']).dt.total_seconds().astype(int)
print (df)
                 date                 new  seconds
0 2017-05-02 00:00:00 2017-05-01 10:00:00    50400
1 2017-05-03 01:00:00 2017-05-02 10:00:00    54000


问:
Adding Shuffle, Repeat & Random to Android Music Player App
I'm working on a open source Android Music player app I'm using some code I found from a tutorial but it doesn't have Shuffle, Repeat & Random buttons included so I need help on adding it to my code. I have no idea how to add it to my app so I'm looking for assistance. I am a complete noob when it comes to Android coding and I'm trying to learn.

Here's my code:

```<code>/**
 * Created by Technologx
 * Visit & signup on https://technologx.com
 * Do not remove this removing this avoids the license
 */

package com.technologx.blaze.player;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PersistableBundle;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    public static final String Broadcast_PLAY_NEW_AUDIO = "com.technologx.blaze.player.PlayNewAudio";

    private MediaPlayerService player;
    boolean serviceBound = false;
    ArrayList<Audio> audioList;

    ImageView collapsingImageView;

    int imageIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        collapsingImageView = (ImageView) findViewById(R.id.collapsingImageView);

        loadCollapsingImage(imageIndex);
        loadAudio();
        initRecyclerView();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                playAudio("https://upload.wikimedia.org/wikipedia/commons/6/6c/Grieg_Lyric_Pieces_Kobold.ogg");
                //play the first audio in the ArrayList
//                playAudio(2);
                if (imageIndex == 4) {
                    imageIndex = 0;
                    loadCollapsingImage(imageIndex);
                } else {
                    loadCollapsingImage(++imageIndex);
                }
            }
        });

    }

    private void initRecyclerView() {
        if (audioList.size() > 0) {
            RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
            RecyclerView_Adapter adapter = new RecyclerView_Adapter(audioList, getApplication());
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.addOnItemTouchListener(new CustomTouchListener(this, new onItemClickListener() {
                @Override
                public void onClick(View view, int index) {
                    playAudio(index);
                }
            }));

        }
    }

    private void loadCollapsingImage(int i) {
        TypedArray array = getResources().obtainTypedArray(R.array.images);
        collapsingImageView.setImageDrawable(array.getDrawable(i));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        outState.putBoolean("serviceStatus", serviceBound);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        serviceBound = savedInstanceState.getBoolean("serviceStatus");
    }

    //Binding this Client to the AudioPlayer Service
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
            player = binder.getService();
            serviceBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            serviceBound = false;
        }
    };

    private void playAudio(int audioIndex) {
        //Check is service is active
        if (!serviceBound) {
            //Store Serializable audioList to SharedPreferences
            StorageUtil storage = new StorageUtil(getApplicationContext());
            storage.storeAudio(audioList);
            storage.storeAudioIndex(audioIndex);

            Intent playerIntent = new Intent(this, MediaPlayerService.class);
            startService(playerIntent);
            bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
        } else {
            //Store the new audioIndex to SharedPreferences
            StorageUtil storage = new StorageUtil(getApplicationContext());
            storage.storeAudioIndex(audioIndex);

            //Service is active
            //Send a broadcast to the service -> PLAY_NEW_AUDIO
            Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
            sendBroadcast(broadcastIntent);
        }
    }

    private void loadAudio() {
        ContentResolver contentResolver = getContentResolver();

        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
        Cursor cursor = contentResolver.query(uri, null, selection, null, sortOrder);

        if (cursor != null && cursor.getCount() > 0) {
            audioList = new ArrayList<>();
            while (cursor.moveToNext()) {
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));

                // Save to audioList
                audioList.add(new Audio(data, title, album, artist));
            }
        }
        cursor.close();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (serviceBound) {
             unbindService(serviceConnection);
            //service is active
            player.stopSelf();
        }
    }
}
</code>```

Here's the MusicService.java code:
https://ghostbin.com/paste/x4fyf

I'd like to replace the image shuffle button with a actual shuffle button. I want to add the repeat & random buttons to the menu. Also not in the questions title but how would I go about replacing the images included with the app in the code with the now playing artwork?

Here's the source code to my project with screens: https://github.com/Technologx/Blaze-Player

答:
Try to use this:</p>

```<code>int position = (Math.Random() * mySongsArray.size());
play(position);
</code>```

Body:
I'm working on a open source Android Music player app I'm using some code I found from a tutorial but it doesn't have Shuffle, Repeat & Random buttons included so I need help on adding it to my code. I have no idea how to add it to my app so I'm looking for assistance. I am a complete noob when it comes to Android coding and I'm trying to learn.

Here's my code:

/**
 * Created by Technologx
 * Visit & signup on https://technologx.com
 * Do not remove this removing this avoids the license
 */

package com.technologx.blaze.player;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PersistableBundle;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    public static final String Broadcast_PLAY_NEW_AUDIO = "com.technologx.blaze.player.PlayNewAudio";

    private MediaPlayerService player;
    boolean serviceBound = false;
    ArrayList<Audio> audioList;

    ImageView collapsingImageView;

    int imageIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        collapsingImageView = (ImageView) findViewById(R.id.collapsingImageView);

        loadCollapsingImage(imageIndex);
        loadAudio();
        initRecyclerView();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                playAudio("https://upload.wikimedia.org/wikipedia/commons/6/6c/Grieg_Lyric_Pieces_Kobold.ogg");
                //play the first audio in the ArrayList
//                playAudio(2);
                if (imageIndex == 4) {
                    imageIndex = 0;
                    loadCollapsingImage(imageIndex);
                } else {
                    loadCollapsingImage(++imageIndex);
                }
            }
        });

    }

    private void initRecyclerView() {
        if (audioList.size() > 0) {
            RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
            RecyclerView_Adapter adapter = new RecyclerView_Adapter(audioList, getApplication());
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.addOnItemTouchListener(new CustomTouchListener(this, new onItemClickListener() {
                @Override
                public void onClick(View view, int index) {
                    playAudio(index);
                }
            }));

        }
    }

    private void loadCollapsingImage(int i) {
        TypedArray array = getResources().obtainTypedArray(R.array.images);
        collapsingImageView.setImageDrawable(array.getDrawable(i));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        outState.putBoolean("serviceStatus", serviceBound);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        serviceBound = savedInstanceState.getBoolean("serviceStatus");
    }

    //Binding this Client to the AudioPlayer Service
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
            player = binder.getService();
            serviceBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            serviceBound = false;
        }
    };

    private void playAudio(int audioIndex) {
        //Check is service is active
        if (!serviceBound) {
            //Store Serializable audioList to SharedPreferences
            StorageUtil storage = new StorageUtil(getApplicationContext());
            storage.storeAudio(audioList);
            storage.storeAudioIndex(audioIndex);

            Intent playerIntent = new Intent(this, MediaPlayerService.class);
            startService(playerIntent);
            bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
        } else {
            //Store the new audioIndex to SharedPreferences
            StorageUtil storage = new StorageUtil(getApplicationContext());
            storage.storeAudioIndex(audioIndex);

            //Service is active
            //Send a broadcast to the service -> PLAY_NEW_AUDIO
            Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
            sendBroadcast(broadcastIntent);
        }
    }

    private void loadAudio() {
        ContentResolver contentResolver = getContentResolver();

        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
        Cursor cursor = contentResolver.query(uri, null, selection, null, sortOrder);

        if (cursor != null && cursor.getCount() > 0) {
            audioList = new ArrayList<>();
            while (cursor.moveToNext()) {
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));

                // Save to audioList
                audioList.add(new Audio(data, title, album, artist));
            }
        }
        cursor.close();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (serviceBound) {
             unbindService(serviceConnection);
            //service is active
            player.stopSelf();
        }
    }
}

Here's the MusicService.java code:
https://ghostbin.com/paste/x4fyf

I'd like to replace the image shuffle button with a actual shuffle button. I want to add the repeat & random buttons to the menu. Also not in the questions title but how would I go about replacing the images included with the app in the code with the now playing artwork?

Here's the source code to my project with screens: https://github.com/Technologx/Blaze-Player

Body:
Try to use this:

int position = (Math.Random() * mySongsArray.size());
play(position);


问:
How to set public key in RSAParameters
I have RSA public key encoded in Base64.
After decoding I can get RSA public key like:

-----BEGIN PUBLIC KEY----- XXXXXXXXXXXXXXXXXXXXXXX
  -----END PUBLIC KEY-----

Now I need to import this key into RSACryptoServiceProvider.
I was looking for solution but wasn't able to find anything working.
From pieces I found, I created such code sample

```<code>    public static string Encrypt(string input, string base64PublicKey)
    {
        var rsa = new RSACryptoServiceProvider();
        var byteKey = System.Convert.FromBase64String(base64PublicKey);
        var byteInput = Encoding.UTF8.GetBytes(input);

        var parameters = rsa.ExportParameters(false);
        parameters.Modulus = byteKey;

        rsa.ImportParameters(parameters);

        var bytesEncrypted = rsa.Encrypt(byteInput, false);

        var result = System.Convert.ToBase64String(bytesEncrypted);

        return result;
    }
</code>```

I suppose it is not working correctly, because I always get response with error from the system I'm integrating with.

Is it a correct way to import public key?
If not how should I do it?

答:
The public key you have is presumably encoded in the PKCS#1 format, which is the common standard for encoding RSA public keys.

The .NET crypto classes do not understand this format directly, you will have to parse the ASN.1 encoding yourself to get the modulus and public exponent from your key and set the corresponding parameters ouf your RSAParameters object.

Title: How to set public key in RSAParameters

Body:
I have RSA public key encoded in Base64.
After decoding I can get RSA public key like:

-----BEGIN PUBLIC KEY----- XXXXXXXXXXXXXXXXXXXXXXX
  -----END PUBLIC KEY-----

Now I need to import this key into RSACryptoServiceProvider.
I was looking for solution but wasn't able to find anything working.
From pieces I found, I created such code sample

    public static string Encrypt(string input, string base64PublicKey)
    {
        var rsa = new RSACryptoServiceProvider();
        var byteKey = System.Convert.FromBase64String(base64PublicKey);
        var byteInput = Encoding.UTF8.GetBytes(input);

        var parameters = rsa.ExportParameters(false);
        parameters.Modulus = byteKey;

        rsa.ImportParameters(parameters);

        var bytesEncrypted = rsa.Encrypt(byteInput, false);

        var result = System.Convert.ToBase64String(bytesEncrypted);

        return result;
    }

I suppose it is not working correctly, because I always get response with error from the system I'm integrating with.

Is it a correct way to import public key?
If not how should I do it?


问:
in one class run many class, PHP OOP
i have class "User_registration" and in this class i need use many class: "Location", "Links", "Mail", "Module".

i create include all class in file:
include 'class/location.php';
include 'class/links.php';
include 'class/mail.php';
include 'class/modules.php';

Now create "User_registration" class.

```<code><?php
class User_registration{

    public function insert_to_db($name, $country_code, $home_page)
    {
        //work with data

        return id;
    }

    public function show_info($id)
    {
        //work with data
    }

}

$reg_u = new User_registration;
$res = $reg_u->insert_to_db($name, $country_code, $home_page);

if($res){
    $reg_u->show_info($res);
}
?>
</code>```

I need in method "insert_to_db" run class: "Location", "Links", "Mail" methods
and in "show_info" run some methods of "Location", "Links", "Module" class.

How? How in one class run another class (no't one)

Thanks for help ;)

答:
As good practice I always use an include_once/require_once when I call a class from a class. That way I know no matter where a use a class its references are taken care of and don't over lap.

Well initialize an instance of each and call your methods from there. Don't be afraid of static references.

ContentLicense: CC BY-SA 2.5

Title: in one class run many class, PHP OOP

Body:
i have class "User_registration" and in this class i need use many class: "Location", "Links", "Mail", "Module".

i create include all class in file:
include 'class/location.php';
include 'class/links.php';
include 'class/mail.php';
include 'class/modules.php';

Now create "User_registration" class.

<?php
class User_registration{

    public function insert_to_db($name, $country_code, $home_page)
    {
        //work with data

        return id;
    }

    public function show_info($id)
    {
        //work with data
    }

}

$reg_u = new User_registration;
$res = $reg_u->insert_to_db($name, $country_code, $home_page);

if($res){
    $reg_u->show_info($res);
}
?>

I need in method "insert_to_db" run class: "Location", "Links", "Mail" methods
and in "show_info" run some methods of "Location", "Links", "Module" class.

How? How in one class run another class (no't one)

Thanks for help ;)


问:
VB.NET Delete specific number of last characters in string in excel
I have a column where I have an ID. I have to match data from one file with other, however in one table there is pure ID, in the other there are ID+year, so I have to delete four last characters in every cell of that column. I tried this:

```<code>For i=2 to ArraySize
    ExWorkSheet.Cells(i, ColumnNumber) = ExWorkSheet.Cells(i, ColumnNumber).remove(len(string)-4,4)
Next
</code>```

This code works but it is very slow. I have 17k+ rows in table.
I also tried to use function replace, it is faster because it works on whole range, but it delete every string 2017(or 2016, etc.), even if it is in the middle of ID.

答:
Its way faster to read the range into an array, process the array and write it back.

Try the following code:

```<code>Sub del_4_chars()
Const ColumnNumber As Integer = 4
Dim Arr, ArraySize As Long, I As Long
ArraySize = 100
    Arr = ExWorkSheet.Range(Cells(2, ColumnNumber), Cells(ArraySize, ColumnNumber)).Value2
    For I = 1 To ArraySize - 1
        Arr(I, 1) = Left(Arr(I, 1), Len(Arr(I, 1)) - 4)
    Next I
    ExWorkSheet.Range(Cells(2, ColumnNumber), Cells(ArraySize, ColumnNumber)).Value2 = Arr
End Sub
</code>```

Body:
I have a column where I have an ID. I have to match data from one file with other, however in one table there is pure ID, in the other there are ID+year, so I have to delete four last characters in every cell of that column. I tried this:

For i=2 to ArraySize
    ExWorkSheet.Cells(i, ColumnNumber) = ExWorkSheet.Cells(i, ColumnNumber).remove(len(string)-4,4)
Next

This code works but it is very slow. I have 17k+ rows in table.
I also tried to use function replace, it is faster because it works on whole range, but it delete every string 2017(or 2016, etc.), even if it is in the middle of ID.

Body:
Its way faster to read the range into an array, process the array and write it back.

Try the following code:

Sub del_4_chars()
Const ColumnNumber As Integer = 4
Dim Arr, ArraySize As Long, I As Long
ArraySize = 100
    Arr = ExWorkSheet.Range(Cells(2, ColumnNumber), Cells(ArraySize, ColumnNumber)).Value2
    For I = 1 To ArraySize - 1
        Arr(I, 1) = Left(Arr(I, 1), Len(Arr(I, 1)) - 4)
    Next I
    ExWorkSheet.Range(Cells(2, ColumnNumber), Cells(ArraySize, ColumnNumber)).Value2 = Arr
End Sub


问:
Combination of 2 tables into one query
i have 2 tables Sales and Employees per attached in postgresql.
I need to calculate:
Query that returns top 4 employees with the most high sales on 2015. In addition, sales of employess that have been already left the company should be under employee number 999
Thanks in advance foy your help

Sales

答:
Recommended SQL Already Tested:

```<code>SELECT
s.employee_id, emp.first_name,
emp.last_name, s.department,
sum(s.num_of_products) as total_product,
sum(s.total_price) as total_price,
s.branch_id, s.branch_city,
s.date
FROM sales s
JOIN employees emp
ON s.employee_id = emp.employee_id
WHERE date_part('year',s.date) = '2014'
-- '2014' is year depend on the input ex. '2015'
GROUP BY s.employee_id, emp.first_name,emp.last_name,
s.department, s.branch_id, s.branch_city, s.date
-- add non aggregate function (sum,count,max,etc) field to group by if you want to show the field.
-- not add in group by cause error 'field must appear in group by'
ORDER BY total_product
-- order by total_product based on total_product
-- order by for choose order by product or price using alias
-- order by without alias ORDER BY sum(s.num_of_products)
-- order by will be error caused error if use num_of_products
-- order by total_price if the TOP 4 based on total_price
LIMIT 4;
-- top 4
-- top n => LIMIT n
</code>```

Title: Combination of 2 tables into one query

Body:
Recommended SQL Already Tested:

SELECT
s.employee_id, emp.first_name,
emp.last_name, s.department,
sum(s.num_of_products) as total_product,
sum(s.total_price) as total_price,
s.branch_id, s.branch_city,
s.date
FROM sales s
JOIN employees emp
ON s.employee_id = emp.employee_id
WHERE date_part('year',s.date) = '2014'
-- '2014' is year depend on the input ex. '2015'
GROUP BY s.employee_id, emp.first_name,emp.last_name,
s.department, s.branch_id, s.branch_city, s.date
-- add non aggregate function (sum,count,max,etc) field to group by if you want to show the field.
-- not add in group by cause error 'field must appear in group by'
ORDER BY total_product
-- order by total_product based on total_product
-- order by for choose order by product or price using alias
-- order by without alias ORDER BY sum(s.num_of_products)
-- order by will be error caused error if use num_of_products
-- order by total_price if the TOP 4 based on total_price
LIMIT 4;
-- top 4
-- top n => LIMIT n


问:
Why can't have I a pure virtual assignment operator?
I'm a bit lost in C++ operators. I'd like to enforce the assignment operator for two different classes, i.e. so one can assign one to each other:

```<code>class A {
public:
    virtual A &operator =(const A &a) = 0;
};

class B : public A {
public:
    virtual A &operator =(const A &a) override {
        std::cout << "B" << std::endl;
        return *this;
    }
};

class C : public A {
public:
    virtual A &operator =(const A &a) override {
        std::cout << "C" << std::endl;
        return *this;
    }
};

int main(int argc, char *argv[])
{
    B b;
    C c;
    b = c;

    // leads to a linker error: undefined reference to `A::operator=(A const&)'
    //B b2;
    //b = b2;
}
</code>```

The first assignment seems to do the job, "B" is called. Similarly, for "c = b", "C" is called. However when I uncomment the second part, I get the linker error. If I define A's operator like:

```<code>virtual A &operator =(const A &a) {
        std::cout << "A" << std::endl;
        return *this;
}
</code>```

I get "B", "A". Huh? Can somebody explain why "A" is needed when two B's are assigned but not when B <- C is?

答:
According to standard overriding virtual assignment operator of base class in derived class does not prevent generation of default copy assignment operator which is being invoked in your case. This default copy assignment operator of class B will directly call copy assignment operator of class A hence you are getting undefined reference error.

13.5.3 Assignment [over.ass]

2 Any assignment operator, even the copy and move assignment operators, can be virtual. [Note: For a derived class D with a base class B for which a virtual copy/move assignment has been declared, the copy/move assignment operator in D does not override B’s virtual copy/move assignment operator. [Example:

```<code>struct B {
    virtual int operator= (int);
    virtual B& operator= (const B&);
};

struct D : B {
    virtual int operator= (int);
    virtual D& operator= (const B&);
};

D dobj1;
D dobj2;
B* bptr = &dobj1;

void f()
{
    bptr->operator=(99); // calls D::operator=(int)
    *bptr = 99; // ditto
    bptr->operator=(dobj2); // calls D::operator=(const B&)
    *bptr = dobj2; // ditto
    dobj1 = dobj2; // calls implicitly-declared D::operator=(const D&)
}
</code>```

Body:
I'm a bit lost in C++ operators. I'd like to enforce the assignment operator for two different classes, i.e. so one can assign one to each other:

class A {
public:
    virtual A &operator =(const A &a) = 0;
};

class B : public A {
public:
    virtual A &operator =(const A &a) override {
        std::cout << "B" << std::endl;
        return *this;
    }
};

class C : public A {
public:
    virtual A &operator =(const A &a) override {
        std::cout << "C" << std::endl;
        return *this;
    }
};

int main(int argc, char *argv[])
{
    B b;
    C c;
    b = c;

    // leads to a linker error: undefined reference to `A::operator=(A const&)'
    //B b2;
    //b = b2;
}

The first assignment seems to do the job, "B" is called. Similarly, for "c = b", "C" is called. However when I uncomment the second part, I get the linker error. If I define A's operator like:

virtual A &operator =(const A &a) {
        std::cout << "A" << std::endl;
        return *this;
}

I get "B", "A". Huh? Can somebody explain why "A" is needed when two B's are assigned but not when B <- C is?

Body:
According to standard overriding virtual assignment operator of base class in derived class does not prevent generation of default copy assignment operator which is being invoked in your case. This default copy assignment operator of class B will directly call copy assignment operator of class A hence you are getting undefined reference error.

13.5.3 Assignment [over.ass]

2 Any assignment operator, even the copy and move assignment operators, can be virtual. [Note: For a derived class D with a base class B for which a virtual copy/move assignment has been declared, the copy/move assignment operator in D does not override B’s virtual copy/move assignment operator. [Example:

struct B {
    virtual int operator= (int);
    virtual B& operator= (const B&);
};

struct D : B {
    virtual int operator= (int);
    virtual D& operator= (const B&);
};

D dobj1;
D dobj2;
B* bptr = &dobj1;

void f()
{
    bptr->operator=(99); // calls D::operator=(int)
    *bptr = 99; // ditto
    bptr->operator=(dobj2); // calls D::operator=(const B&)
    *bptr = dobj2; // ditto
    dobj1 = dobj2; // calls implicitly-declared D::operator=(const D&)
}


问:
Is it possible to extract contents of a *non* self-extracting .exe file?
Well.... the question sort of says it all. If possible I would like to be able to do so from a Linux or macOS environment, but I have virtualized Windows if need be.

Thanks in advance!

答: It depends. Assuming you have a PE file (windows executable), you can use a resource editor https://stefansundin.github.io/xn_resource_editor/ to extract icons, messages or dialog layouts. This assumes that the author of that file used the native resource system. Other data would only be available if you knew the address within the PE file, or had appropriate debug symbols. But then, you must guess content type, and maybe also file size.</p>


问:
return values after timeout
How to return value after timeout in this function</p>

```<code>$get: function($timeout) {
        var breadcrumbs;
        data = [];

        $timeout(function() {
          data = crateBreadcrumbs();
          console.log(data);
        });
        return data;
</code>```

答:
You need to return a promise. The promise will signify that you have not yet returned data, but you will resolve that promise once your $timeout service is completed.

You can use the $q service to achieve this. docs

Essentially,

```<code>function($timeout) {
    var deferred = $q.defer();

    $timeout(function() {
        data = createBreadcrumbs();
        deferred.resolve(data);
    }, 1000);

    return deferred.promise;
}
</code>```

Per @Bergi's comment,

```<code>$get: function($timeout) {
    return $timeout(function() { return createBreadcrumbs();})
}
</code>```

Title: return values after timeout

Body:
How to return value after timeout in this function

$get: function($timeout) {
        var breadcrumbs;
        data = [];

        $timeout(function() {
          data = crateBreadcrumbs();
          console.log(data);
        });
        return data;

Body:
You need to return a promise. The promise will signify that you have not yet returned data, but you will resolve that promise once your $timeout service is completed.

You can use the $q service to achieve this. docs

Essentially,

function($timeout) {
    var deferred = $q.defer();

    $timeout(function() {
        data = createBreadcrumbs();
        deferred.resolve(data);
    }, 1000);

    return deferred.promise;
}

Per @Bergi's comment,

$get: function($timeout) {
    return $timeout(function() { return createBreadcrumbs();})
}


问:
Get Image from the Storage Folder in View - Laravel 5.4
I'm trying to show the default.jpg avatar picture in my Laravel 5.4 profile.blade.php.

I created a link between the public folder and the storage folder with: php artisan storage:link.

The file is stored:

I check in the source code of my webpage which showed the src="/public/storage/uploads/avatar/default.jpg"

But still no image could be found. Could someone explain to me what I am missing?

答: remove public from path and image will be shown if you set correct link


问:
convert date format to 'YYYYMMDD'
In Javascript, I have date string as shown below:

```<code>var dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";
</code>```

I need to convert it to  "YYYYMMDD" format. For example the above date should be : "20150325"

答:
```<code>function getFormattedDate(date) {
  var year = date.getFullYear();

  var month = (1 + date.getMonth()).toString();
  month = month.length > 1 ? month : '0' + month;

  var day = date.getDate().toString();
  day = day.length > 1 ? day : '0' + day;

  return year + month + day;
}
</code>```

And then just call the function :

```<code>alert(getFormattedDate(new Date());
</code>```

Title: convert date format to 'YYYYMMDD'

Body:
In Javascript, I have date string as shown below:

var dateStr = "Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)";

I need to convert it to  "YYYYMMDD" format. For example the above date should be : "20150325"

Body:
function getFormattedDate(date) {
  var year = date.getFullYear();

  var month = (1 + date.getMonth()).toString();
  month = month.length > 1 ? month : '0' + month;

  var day = date.getDate().toString();
  day = day.length > 1 ? day : '0' + day;

  return year + month + day;
}

And then just call the function :

alert(getFormattedDate(new Date());


问:
Ruby query need to update
Relationship:

account has_many users

user has_one sima

primary_partner_id is "account_id" which is passing as params.

```<code>User.where(primary_partner_id: 2).map{|a| a.sima}.reject{ |e| e.to_s.empty?}
</code>```

Results as below:

```<code> [
    #<Sima id: 93, user_id: 7, interviewer_account_user_id: 1945, interviewer_completion_date: "2017-06-09", transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27381", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:17:57", updated_at: "2017-06-09 10:04:33", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"easylims.xlsx", :user_name=>"Mike Burns", :created_at=>2017-06-06 20:17:57 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:19:33 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>,
    #<Sima id: 92, user_id: 1, interviewer_account_user_id: nil, interviewer_completion_date: nil, transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27437", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:01:50", updated_at: "2017-06-06 20:22:50", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"original_msg (1).txt", :user_name=>"bild_cloud@bild.org", :created_at=>2017-06-06 20:01:50 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:22:05 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>
 ]
</code>```

Sima has field like status and I have three statuses as "pending, accepted, declined"

Question:

Now I want to show the result as per status which will pass by the user as params. So the result should be as per status from Sima. If params is status=" accepted" then Sima list will have only which has status "accepted"

答:
As I am understanding your above all statements. End user us passing account id and you want to take sima status from the end user as well.

You can file all users id from account first. then find sima which will belong to that user and here you can pass sima status as well.

@aBadAssCowboy given the correct answer which is first one only. But from that query, you will get all Sima either nil or with value.

```<code>user_ids = User.where(primary_partner_id: params[:account_id]).pluck(:id)
Sima.where(user_id: user_ids, status: params[:status]).reject{ |e| e.to_s.empty?}
</code>```

Hope this will help you.

Title: Ruby query need to update

Body:
Relationship:

account has_many users

user has_one sima

primary_partner_id is "account_id" which is passing as params.

User.where(primary_partner_id: 2).map{|a| a.sima}.reject{ |e| e.to_s.empty?}

Results as below:

 [
    #<Sima id: 93, user_id: 7, interviewer_account_user_id: 1945, interviewer_completion_date: "2017-06-09", transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27381", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:17:57", updated_at: "2017-06-09 10:04:33", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"easylims.xlsx", :user_name=>"Mike Burns", :created_at=>2017-06-06 20:17:57 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:19:33 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>,
    #<Sima id: 92, user_id: 1, interviewer_account_user_id: nil, interviewer_completion_date: nil, transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27437", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:01:50", updated_at: "2017-06-06 20:22:50", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"original_msg (1).txt", :user_name=>"bild_cloud@bild.org", :created_at=>2017-06-06 20:01:50 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:22:05 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>
 ]

Sima has field like status and I have three statuses as "pending, accepted, declined"

Question:

Now I want to show the result as per status which will pass by the user as params. So the result should be as per status from Sima. If params is status=" accepted" then Sima list will have only which has status "accepted"

Body:
As I am understanding your above all statements. End user us passing account id and you want to take sima status from the end user as well.

You can file all users id from account first. then find sima which will belong to that user and here you can pass sima status as well.

@aBadAssCowboy given the correct answer which is first one only. But from that query, you will get all Sima either nil or with value.

user_ids = User.where(primary_partner_id: params[:account_id]).pluck(:id)
Sima.where(user_id: user_ids, status: params[:status]).reject{ |e| e.to_s.empty?}

Hope this will help you.


问:
How to trigger on click event when user clicks on pagination page numbers in datatables?
I am using datatables in which I want to trigger an on click event with alert box when user clicks on the datatable pagination numbers.

Below is the code I tried, but it works for next button.

```<code>$(document).ready(function (){
  var table = $('#example').DataTable({
    drawCallback: function(){
      $('.paginate_button.next', this.api().table().container())
         .on('click', function(){
            alert('next') ;
         });
    }
  });
});
</code>```

Live Example

答:
try this

```<code> $(document).ready(function (){
    var table = $('#example').DataTable({
       drawCallback: function(){
          $('.paginate_button', this.api().table().container())
             .on('click', function(){
                alert('next') ;
             });
       }
    });
}
</code>```

just remove .next

Body:
I am using datatables in which I want to trigger an on click event with alert box when user clicks on the datatable pagination numbers.

Below is the code I tried, but it works for next button.

$(document).ready(function (){
  var table = $('#example').DataTable({
    drawCallback: function(){
      $('.paginate_button.next', this.api().table().container())
         .on('click', function(){
            alert('next') ;
         });
    }
  });
});

Live Example

Body:
try this

 $(document).ready(function (){
    var table = $('#example').DataTable({
       drawCallback: function(){
          $('.paginate_button', this.api().table().container())
             .on('click', function(){
                alert('next') ;
             });
       }
    });
}

just remove .next


问:
Creating persistent unique links
I'm building an app that allows users to search and create a list of their favourite music albums. So far the users can create the list.

But now I need to be able to create a new and unique link for each list created so that users can share it on social media. Can anybody tell me how to go about doing this? Thanks!

答:
As you are already done with the part of creating a new list, the rest is pretty straightforward.

I am assuming you store these lists in a database somewhere. What you need now is create separate routes for each list with its unique identifier. This unique identifier can be something generated by you ( like say alphanumeric string ) or something as simple as the id of this list in your DB.

Once that is done, you can create a component ( say ListItemComponent )
and then use it in your router modules routes.

```<code>{ path: 'list/:id', component: ListItemComponent },
</code>```

Inside your component's OnInit, you can get this ID,

```<code>constructor(private route : ActivatedRoute) {}

ngOnInit() {
 var id = this.route.snapshot.params['id'];
}
</code>```

You can use this ID to fetch the list from your backend.

Also, since you want social media sharing, if you want to set meta tags (title, description etc.) for these routes when sharing on fb etc, I sugges you look into Server side rendering.

Based on what you wanted in the comments.

https://developer.github.com/v3/gists/

Refer this API. You can make calls to this API to create a gist whenever the user wants to share their list. You will get the URL to that gist as part of the response. It is very clearly explained in the documentation.

```<code>POST /gists
</code>```

Say the URL of this new gist is -

https://api.github.com/gists/aa5a315d61ae9438b18d

Now, what you could do is use this ID ('aa5a315d61ae9438b18d') in your website as well.
That is, say yoursite.com/lists/aa5a315d61ae9438b18d
From the method above, fetch the ID, use it to get the gist from github and you are done!

```<code>GET /gists/:id
</code>```

This should work. Not just with github gists but with any such thing that provides an API.
Hoping this helps!

Title: Creating persistent unique links

Body:
As you are already done with the part of creating a new list, the rest is pretty straightforward.

I am assuming you store these lists in a database somewhere. What you need now is create separate routes for each list with its unique identifier. This unique identifier can be something generated by you ( like say alphanumeric string ) or something as simple as the id of this list in your DB.

Once that is done, you can create a component ( say ListItemComponent )
and then use it in your router modules routes.

{ path: 'list/:id', component: ListItemComponent },

Inside your component's OnInit, you can get this ID,

constructor(private route : ActivatedRoute) {}

ngOnInit() {
 var id = this.route.snapshot.params['id'];
}

You can use this ID to fetch the list from your backend.

Also, since you want social media sharing, if you want to set meta tags (title, description etc.) for these routes when sharing on fb etc, I sugges you look into Server side rendering.

Based on what you wanted in the comments.

https://developer.github.com/v3/gists/

Refer this API. You can make calls to this API to create a gist whenever the user wants to share their list. You will get the URL to that gist as part of the response. It is very clearly explained in the documentation.

POST /gists

Say the URL of this new gist is -

https://api.github.com/gists/aa5a315d61ae9438b18d

Now, what you could do is use this ID ('aa5a315d61ae9438b18d') in your website as well.
That is, say yoursite.com/lists/aa5a315d61ae9438b18d
From the method above, fetch the ID, use it to get the gist from github and you are done!

GET /gists/:id

This should work. Not just with github gists but with any such thing that provides an API.
Hoping this helps!


问:
Support vector machine overfitting my data
I am trying to make predictions for the iris dataset. I have decided to use svms for this purpose. But, it gives me an accuracy 1.0. Is it a case of overfitting or is it because the model is very good? Here is my code.

```<code>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
svm_model = svm.SVC(kernel='linear', C=1,gamma='auto')
svm_model.fit(X_train,y_train)
predictions = svm_model.predict(X_test)
accuracy_score(predictions, y_test)
</code>```

Here, accuracy_score returns a value of 1. Please help me. I am a beginner in machine learning.

答:
You can try cross validation:

Example:

```<code>from sklearn.model_selection import LeaveOneOut
from sklearn import datasets
from sklearn.svm import SVC
from sklearn.model_selection import cross_val_score

#load iris data
iris = datasets.load_iris()
X = iris.data
Y = iris.target

#build the model
svm_model = SVC( kernel ='linear', C = 1, gamma = 'auto',random_state = 0 )

#create the Cross validation object
loo = LeaveOneOut()

#calculate cross validated (leave one out) accuracy score
scores = cross_val_score(svm_model, X,Y, cv = loo, scoring='accuracy')

print( scores.mean() )
</code>```

Result (the mean accuracy of the 150 folds since we used leave-one-out):

```<code>0.97999999999999998
</code>```

Bottom line:

Cross validation (especially LeaveOneOut) is a good way to avoid overfitting and to get robust results.

Body:
I am trying to make predictions for the iris dataset. I have decided to use svms for this purpose. But, it gives me an accuracy 1.0. Is it a case of overfitting or is it because the model is very good? Here is my code.

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
svm_model = svm.SVC(kernel='linear', C=1,gamma='auto')
svm_model.fit(X_train,y_train)
predictions = svm_model.predict(X_test)
accuracy_score(predictions, y_test)

Here, accuracy_score returns a value of 1. Please help me. I am a beginner in machine learning.

Body:
You can try cross validation:

Example:

from sklearn.model_selection import LeaveOneOut
from sklearn import datasets
from sklearn.svm import SVC
from sklearn.model_selection import cross_val_score

#load iris data
iris = datasets.load_iris()
X = iris.data
Y = iris.target

#build the model
svm_model = SVC( kernel ='linear', C = 1, gamma = 'auto',random_state = 0 )

#create the Cross validation object
loo = LeaveOneOut()

#calculate cross validated (leave one out) accuracy score
scores = cross_val_score(svm_model, X,Y, cv = loo, scoring='accuracy')

print( scores.mean() )

Result (the mean accuracy of the 150 folds since we used leave-one-out):

0.97999999999999998

Bottom line:

Cross validation (especially LeaveOneOut) is a good way to avoid overfitting and to get robust results.


问:
what is the exception being thrown in this code:
```<code>public class Testex
{
    public static void main ( String[] args ) {
       double [] scores = new double [5];
       scores [5] = 95.75;

    }
}
</code>```

im not sure what exception is being thrown here, any help please

答: The Exception would be an IndexOutOfBoundsException because arrays are are 0-based. So the first index is [0].  When you reference [5] this is the 6th slot but the array only has 5 slots.</p>

Body:
public class Testex
{
    public static void main ( String[] args ) {
       double [] scores = new double [5];
       scores [5] = 95.75;

    }
}

im not sure what exception is being thrown here, any help please


问:
String mismatch index
I have two strings and I want to get the index where the mismatch happens:

```<code>str = "abcdef"
str2 = "abddef"

Output: 2
</code>```

So can anyone tell me is there an inbuilt function in java to get the index? If not can someone give me a hint to do so? Thank You!

答:
Here is a step by step description on how the problem could be solved. I assume that you want to implement it as a function:

First handle the case where the strings are equal. If they are, return an appropriate value.

Next, find the length of the shortest string.

Then for loop over the length of the shortest string comparing the ith letter of the strings. Return the index of any mismatch found.

If no mismatch was found return the length of the shorter string.

Hint: The .length(), .equals() and .charAt() methods of the string class will be useful.

Title: String mismatch index

Body:
I have two strings and I want to get the index where the mismatch happens:

str = "abcdef"
str2 = "abddef"

Output: 2

So can anyone tell me is there an inbuilt function in java to get the index? If not can someone give me a hint to do so? Thank You!


问:
what is correct way to reference a div inside ReactDOMBuilder.render?
I've been converting this code:

https://github.com/Kotlin/kotlin-fullstack-sample/blob/master/frontend/src/org/jetbrains/demo/thinkter/HomeView.kt

to my own needs and got to a point where inside the render method I need to do:

```<code>val div = document.getElementById("map")
kotlinGoogleMap(div)
</code>```

this comes from https://blog.frankel.ch/kotlin-front-end-developers/  so the actual line I'm trying to call is line 33 here https://github.com/nfrankel/kotlin-frontend/blob/master/src/script.kt#L33

Is there a good way to do this from my HomeView.kt render method?

答:
I was able to solve this with componentDidMount:

```<code>   override fun componentDidMount() {
      super.componentDidMount()
      val div = document.getElementsByClassName("thegmap").item(0)
      kotlinGoogleMap(div)
    }
</code>```

where render makes the thegmap div:

```<code>override fun ReactDOMBuilder.render() {
  div {
    div(classes = "thegmap") {
    }
  }
}
</code>```

follow up question if anyone is reading - why can't I give that div an id vs classes?

Body:
I've been converting this code:

https://github.com/Kotlin/kotlin-fullstack-sample/blob/master/frontend/src/org/jetbrains/demo/thinkter/HomeView.kt

to my own needs and got to a point where inside the render method I need to do:

val div = document.getElementById("map")
kotlinGoogleMap(div)

this comes from https://blog.frankel.ch/kotlin-front-end-developers/  so the actual line I'm trying to call is line 33 here https://github.com/nfrankel/kotlin-frontend/blob/master/src/script.kt#L33

Is there a good way to do this from my HomeView.kt render method?

Body:
I was able to solve this with componentDidMount:

   override fun componentDidMount() {
      super.componentDidMount()
      val div = document.getElementsByClassName("thegmap").item(0)
      kotlinGoogleMap(div)
    }

where render makes the thegmap div:

override fun ReactDOMBuilder.render() {
  div {
    div(classes = "thegmap") {
    }
  }
}

follow up question if anyone is reading - why can't I give that div an id vs classes?


问:
Modify date structure
I want to change the day part of a year-month-day structure. For example, from 1990-01-03 to 1990-01-01. Is the code below correct?

```<code>d<-as.POSIXlt("1990-01-03")
d$mday<-1
</code>```

wday and yday are not changed, so the result is somewhat inconsistent. I use the result only for conversion to character strings. Other date representations I know(Date, POSIXct) are inconvenient for this task.

答:
use lubridate package to parse date and then subtract days

```<code>library(lubridate)

a=ymd("1990-01-03")
</code>```

From How to subtract days in R?

```<code>a-2
</code>```

or day(a)=1

Title: Modify date structure

Body:
I want to change the day part of a year-month-day structure. For example, from 1990-01-03 to 1990-01-01. Is the code below correct?

d<-as.POSIXlt("1990-01-03")
d$mday<-1

wday and yday are not changed, so the result is somewhat inconsistent. I use the result only for conversion to character strings. Other date representations I know(Date, POSIXct) are inconvenient for this task.

Body:
use lubridate package to parse date and then subtract days

library(lubridate)

a=ymd("1990-01-03")

From How to subtract days in R?

a-2

or day(a)=1


问:
Ionic v2 : Push notification to open specific page
I try to build an android App with push notification and I want to open a specific component when sur touch a received notification.

https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md

http://docs.ionic.io/services/push/

In my app.component.ts constructor I try this :

```<code>platform.ready().then(() => {
      //StatusBar.styleDefault();
      Splashscreen.hide();
      this.push.rx.notification()
          .subscribe((msg) => {
            alert(msg.title + ': ' + msg.text);
            console.log(msg.app, "app");
            console.log(msg.count, "count");
            console.log(msg.image, "image");
            console.log(msg.raw, "raw");
            console.log(msg.sound, "sound");
            console.log(msg.text, "text");
            console.log(msg.title, "title");
          });
    });
</code>```

It work well when my app isn't close or on pause. I can see my logs.
But when my app is closed or onpause, if I touch notification, my app open but I can't have my logs.

I tried this too :

```<code>this.push.on('notification', function(data) {
      // do something with the push data
      // then call finish to let the OS know we are done
      this.push.finish(function() {
        console.log("processing of push data is finished");
      }, function() {
        console.log("something went wrong with push.finish for ID = " + data.additionalData.notId)
      }, data.additionalData.notId);
    });
</code>```

But I had this error :

```<code>Object [object Object] has no method 'on'
</code>```

What I have to do ?

答:
To have your notification event called when your application isn't in foreground, you have to add content-available: 1 into your push message.

Read this link

Body:
I try to build an android App with push notification and I want to open a specific component when sur touch a received notification.

https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md

http://docs.ionic.io/services/push/

In my app.component.ts constructor I try this :

platform.ready().then(() => {
      //StatusBar.styleDefault();
      Splashscreen.hide();
      this.push.rx.notification()
          .subscribe((msg) => {
            alert(msg.title + ': ' + msg.text);
            console.log(msg.app, "app");
            console.log(msg.count, "count");
            console.log(msg.image, "image");
            console.log(msg.raw, "raw");
            console.log(msg.sound, "sound");
            console.log(msg.text, "text");
            console.log(msg.title, "title");
          });
    });

It work well when my app isn't close or on pause. I can see my logs.
But when my app is closed or onpause, if I touch notification, my app open but I can't have my logs.

I tried this too :

this.push.on('notification', function(data) {
      // do something with the push data
      // then call finish to let the OS know we are done
      this.push.finish(function() {
        console.log("processing of push data is finished");
      }, function() {
        console.log("something went wrong with push.finish for ID = " + data.additionalData.notId)
      }, data.additionalData.notId);
    });

But I had this error :

Object [object Object] has no method 'on'

What I have to do ?


问:
Conditional statement in Magento 2 phtml file
I want to display 2 custom product attributes I created in the admin on the frontend with conditional statement.

The first is Availability, and the second is shipping_rate.

I have edited the defauproduct page template located in:

```<code>/vendor/magento/module-catalog/view/frontend/templates/product/view/type/default.phtml
</code>```

to this:

```<code><?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php /* @var $block \Magento\Catalog\Block\Product\View\AbstractView */?>
<?php $_product = $block->getProduct() ?>

<?php if ($block->displayProductStockStatus()): ?>
    <?php if ($_product->isAvailable()): ?>
        <div class="stock available" title="<?php /* @escapeNotVerified */ echo __('Availability') ?>">
            <span><?php /* @escapeNotVerified */ echo __('In stock') ?></span>
        </div>
        <span class="estimated-delivery">
        <?php /* @escapeNotVerified */ if ($_product->getResource()->getAttribute('availability')->getValue($_product) != '0'): ?>
            Livraison estimée dans <?php /* @escapeNotVerified */ echo $_product->getResource()->getAttribute('availability')->getFrontend()->getValue($_product); ?> jour(s)</span>
        <?php endif; ?>
        <span>Livraison à partir de <?php /* @escapeNotVerified */ echo $_product->getResource()->getAttribute('shipping_rate')->getFrontend()->getValue($_product); ?> €</span>
    <?php else: ?>
        <div class="stock unavailable" title="<?php /* @escapeNotVerified */ echo __('Availability') ?>">
            <span><?php /* @escapeNotVerified */ echo __('Out of stock') ?></span>
        </div>
    <?php endif; ?>
<?php endif; ?>
</code>```

My problem is:
When the availability is equal to 0, I would like to display something, and when it's different than 0, something else. It's a classic conditional statement, but I'm not succeeding :S

Here is what I did, and it didn't work.

```<code><span class="estimated-delivery">
    <?php /* @escapeNotVerified */ if ($_product->getResource()->getAttribute('availability')->getValue($_product) != '0'): ?>
            Livraison estimée dans <?php /* @escapeNotVerified */ echo $_product->getResource()->getAttribute('availability')->getFrontend()->getValue($_product); ?> jour(s)</span>
        <?php else ?>
             Disponibilité: <strong>En Stock</strong> </span>
    <?php endif; ?>
</code>```

Can someone help me to write this conditional statement?

Thanks

答:
To answer my own question...

You have a M2 global variable called $product.
Then to access your product attributes, let's say availability, you should access it like this:

```<code>$product->[attribute-slug]
</code>```

so in my case, this was $product->availability.

Then I use on my template (default-luma), on the product page description template, with some conditional:

```<code><?php if ($product->availability > 0 ) {?>
  <span>Product will be delivered in <?php echo $product->availability; ?> days.</span>
<?php} else {?>
  <span> Product is in stock </span>
<?php }?>
</code>```

Hope this helps someone.

Body:
I want to display 2 custom product attributes I created in the admin on the frontend with conditional statement.

The first is Availability, and the second is shipping_rate.

I have edited the defauproduct page template located in:

/vendor/magento/module-catalog/view/frontend/templates/product/view/type/default.phtml

to this:

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php /* @var $block \Magento\Catalog\Block\Product\View\AbstractView */?>
<?php $_product = $block->getProduct() ?>

<?php if ($block->displayProductStockStatus()): ?>
    <?php if ($_product->isAvailable()): ?>
        <div class="stock available" title="<?php /* @escapeNotVerified */ echo __('Availability') ?>">
            <?php /* @escapeNotVerified */ echo __('In stock') ?>

        <?php /* @escapeNotVerified */ if ($_product->getResource()->getAttribute('availability')->getValue($_product) != '0'): ?>
            Livraison estimée dans <?php /* @escapeNotVerified */ echo $_product->getResource()->getAttribute('availability')->getFrontend()->getValue($_product); ?> jour(s)
        <?php endif; ?>
        Livraison à partir de <?php /* @escapeNotVerified */ echo $_product->getResource()->getAttribute('shipping_rate')->getFrontend()->getValue($_product); ?> €
    <?php else: ?>
        <div class="stock unavailable" title="<?php /* @escapeNotVerified */ echo __('Availability') ?>">
            <?php /* @escapeNotVerified */ echo __('Out of stock') ?>

    <?php endif; ?>
<?php endif; ?>

My problem is:
When the availability is equal to 0, I would like to display something, and when it's different than 0, something else. It's a classic conditional statement, but I'm not succeeding :S

Here is what I did, and it didn't work.

    <?php /* @escapeNotVerified */ if ($_product->getResource()->getAttribute('availability')->getValue($_product) != '0'): ?>
            Livraison estimée dans <?php /* @escapeNotVerified */ echo $_product->getResource()->getAttribute('availability')->getFrontend()->getValue($_product); ?> jour(s)
        <?php else ?>
             Disponibilité: En Stock
    <?php endif; ?>

Can someone help me to write this conditional statement?

Thanks

Body:
To answer my own question...

You have a M2 global variable called $product.
Then to access your product attributes, let's say availability, you should access it like this:

$product->[attribute-slug]

so in my case, this was $product->availability.

Then I use on my template (default-luma), on the product page description template, with some conditional:

<?php if ($product->availability > 0 ) {?>
  <span>Product will be delivered in <?php echo $product->availability; ?> days.</span>
<?php} else {?>
  <span> Product is in stock </span>
<?php }?>

Hope this helps someone.


问:
load/using .jar or .so with delphi xe5
I would like to use the lib https://sourceforge.net/p/zbar/news/2012/03/zbar-android-sdk-version-01-released/ with delphi XE5, but the lib and. Jar and. So, You can use it with delphi XE5, how do? I need to read the barcode on my webcam!</p>

答:
There is a library for Delphi XE7 for reading/scanning barcodes. This library was released in 2015 and is actively supported.

ZXing.Delphi - barcode scanning object Pascal library for Delphi XE7-Berlin.

So now if you want to read the barcode on a webcam, you don't need to tinker with .jar / .so files.

Title: load/using .jar or .so with delphi xe5


问:
Autofilter to remove all EXCEPT a set of values
I am using a macro in Excel which applies a filter to a column, selects the values I no longer wish to keep and then deletes them. The problem I have is my macro requires me to know all of the values I do not want. In reality, I have a defined list of the ones that I want to keep, and all others should be removed. Can anyone help me switch this macro around so I can pass it the list of values to keep, and all others are removed? Here's what I have so far...</p>

```<code>    Columns("C:C").Select
    Selection.AutoFilter
    Dim LR As Long
    LR = ActiveSheet.UsedRange.Rows.Count
    ActiveSheet.Range("B2:B" & LR).AutoFilter Field:=1, Criteria1:=Array( _
        "A1", "AC", "AV", "BF", "BK", "BR", "C8", "CB", "CG", "CI", "CJ", "CM", "CO", "CR", "CS", "CT" _
        , "DR", "DN", "DS", "DU", "EF", "FC", "FE", "FI", "FO", "GD", "GE", "GO", "GR", "GW", "HA", "HD", _
        "HI", "KH", "KU", "LV", "MI", "MS", "MV", "MZ", "NE", "NO", "P4", "PI", "RS", "RT", "S9", "SC", "SU" _
        , "SY", "TO", "TX", "UR", "VN", "VR", "WI", "WN", "YA", "YO", "ZZ", "AO", "GS", "KR", "F5", "A2", _
        "LD", "ZE", "TG", "MX", "JI", "A9"), _
        Operator:=xlFilterValues
    Rows("2:" & LR).Select
    Selection.Delete Shift:=xlUp
    Selection.AutoFilter
    Range("A1").Select
</code>```

答:
using temp sheet it seems to be possilbe.</p>

```<code>Dim LR As Long
Dim rngDB As Range
Dim Ws As Worksheet, Temp As Worksheet
Set Ws = ActiveSheet
LR = Ws.UsedRange.Rows.Count
Set rngDB = ActiveSheet.Range("B2:B" & LR)
rngDB.AutoFilter Field:=1, Criteria1:=Array( _
    "A1", "AC", "AV", "BF", "BK", "BR", "C8", "CB", "CG", "CI", "CJ", "CM", "CO", "CR", "CS", "CT" _
    , "DR", "DN", "DS", "DU", "EF", "FC", "FE", "FI", "FO", "GD", "GE", "GO", "GR", "GW", "HA", "HD", _
    "HI", "KH", "KU", "LV", "MI", "MS", "MV", "MZ", "NE", "NO", "P4", "PI", "RS", "RT", "S9", "SC", "SU" _
    , "SY", "TO", "TX", "UR", "VN", "VR", "WI", "WN", "YA", "YO", "ZZ", "AO", "GS", "KR", "F5", "A2", _
    "LD", "ZE", "TG", "MX", "JI", "A9"), _
    Operator:=xlFilterValues

Set Temp = Sheets.Add

rngDB.SpecialCells(xlCellTypeVisible).EntireRow.Copy Temp.Range("a1")
Ws.ShowAllData
rngDB.EntireRow.ClearContents

Temp.Range("a1").CurrentRegion.Copy Ws.Range("a2")
Application.DisplayAlerts = False
Temp.Delete
Application.DisplayAlerts = True
</code>```

Body:
I am using a macro in Excel which applies a filter to a column, selects the values I no longer wish to keep and then deletes them. The problem I have is my macro requires me to know all of the values I do not want. In reality, I have a defined list of the ones that I want to keep, and all others should be removed. Can anyone help me switch this macro around so I can pass it the list of values to keep, and all others are removed? Here's what I have so far...

    Columns("C:C").Select
    Selection.AutoFilter
    Dim LR As Long
    LR = ActiveSheet.UsedRange.Rows.Count
    ActiveSheet.Range("B2:B" & LR).AutoFilter Field:=1, Criteria1:=Array( _
        "A1", "AC", "AV", "BF", "BK", "BR", "C8", "CB", "CG", "CI", "CJ", "CM", "CO", "CR", "CS", "CT" _
        , "DR", "DN", "DS", "DU", "EF", "FC", "FE", "FI", "FO", "GD", "GE", "GO", "GR", "GW", "HA", "HD", _
        "HI", "KH", "KU", "LV", "MI", "MS", "MV", "MZ", "NE", "NO", "P4", "PI", "RS", "RT", "S9", "SC", "SU" _
        , "SY", "TO", "TX", "UR", "VN", "VR", "WI", "WN", "YA", "YO", "ZZ", "AO", "GS", "KR", "F5", "A2", _
        "LD", "ZE", "TG", "MX", "JI", "A9"), _
        Operator:=xlFilterValues
    Rows("2:" & LR).Select
    Selection.Delete Shift:=xlUp
    Selection.AutoFilter
    Range("A1").Select

Body:
using temp sheet it seems to be possilbe.

Dim LR As Long
Dim rngDB As Range
Dim Ws As Worksheet, Temp As Worksheet
Set Ws = ActiveSheet
LR = Ws.UsedRange.Rows.Count
Set rngDB = ActiveSheet.Range("B2:B" & LR)
rngDB.AutoFilter Field:=1, Criteria1:=Array( _
    "A1", "AC", "AV", "BF", "BK", "BR", "C8", "CB", "CG", "CI", "CJ", "CM", "CO", "CR", "CS", "CT" _
    , "DR", "DN", "DS", "DU", "EF", "FC", "FE", "FI", "FO", "GD", "GE", "GO", "GR", "GW", "HA", "HD", _
    "HI", "KH", "KU", "LV", "MI", "MS", "MV", "MZ", "NE", "NO", "P4", "PI", "RS", "RT", "S9", "SC", "SU" _
    , "SY", "TO", "TX", "UR", "VN", "VR", "WI", "WN", "YA", "YO", "ZZ", "AO", "GS", "KR", "F5", "A2", _
    "LD", "ZE", "TG", "MX", "JI", "A9"), _
    Operator:=xlFilterValues

Set Temp = Sheets.Add

rngDB.SpecialCells(xlCellTypeVisible).EntireRow.Copy Temp.Range("a1")
Ws.ShowAllData
rngDB.EntireRow.ClearContents

Temp.Range("a1").CurrentRegion.Copy Ws.Range("a2")
Application.DisplayAlerts = False
Temp.Delete
Application.DisplayAlerts = True


问:
Eclipse Maven project structure
I am fairly new to maven. In Eclipse, I created a maven project
Inside this I can see src/main/java and src/test/java also there is one more src folder which again contains main and test folder. Here I am confused in which src folder I need to write the code. What is the main benefit of using main and test folder? Why there are two main and two src folder

答:
I can see, you are confused with both src/main or src/test folders.

You should notice that src/main/java at the top is how maven shows the folders.
and src->main->java (one folder inside another) is how your files actually gets stored in the workspace on the disk.

So if you would look at your workspace you would find folders like you have at the bottom. One inside another.

Now you ask why there are two copies: First one at the top is where we write the code. In the second src (which is actual folders on the disk) at the bottom it gets automatically reflected all the files that you created in the top src. So apparently src at the top is not actual folders on the disk, it is just how maven shows the source folders.

Main is where your business logic resides, Test is where you place your testing code for above logic!

Title: Eclipse Maven project structure


问:
Algolia WordPress - how can I only index published posts and exclude all the drafts and private
I have red the Algolia documentation (https://www.algolia.com/doc/) but I have never found any mention on how to exclude "draft" and "private" pages from being indexed. Moreover does anyone know how to do this for specific CPT?</p>

答:
I believe the default behavior of the official Algolia for WordPress extension is to only index the published post.

Custom Post types are handled by default but you may have to customize the attributes to index. You can find more details in the plugin documentation
https://community.algolia.com/wordpress/advanced-custom-fields.html
(example with ACF field but also works with standard meta field)


问:
Geonames bounding box
I use geonames API to validate whether a "string" is a place/location. The following is a snippet of my code.

```<code>import geonames.adapters.search

sa = geonames.adapters.search.Search(my_user_name)
result = sa.query('bordeaux').east_west_north_south_box([141.021805, 95.009331, 5.904417, -10.941861]).execute()

theresult = set()
for id_, name in result.get_flat_results():
    theresult.add(name.lower())
print 'bordeaux' in theresult
</code>```

As you can see I added a bounding box of Indonesia when I did the search. But to my surprise the result of this code is "True" where we all know that Bordeaux is located in France. Is there something wrong with my code?

答:
Instead of using coordinates bounding box use the country code, for example:

```<code>result = sa.query('bordeaux').country('id').execute()
</code>```

returns no results, whereas:

```<code>result = sa.query('jakarta').country('id').execute()
</code>```

returns some appropriate results, as does:

```<code>result = sa.query('bordeaux').country('fr').execute()
</code>```

and also:

```<code>result = sa.query('bordeaux').country('us').execute()
</code>```

Update:

Did some research and the geonames_rdf library doesn't convert the bounding box parameter into HTTP/REST parameters correctly - it applies a single parameter "east,west,south,north" when they should all be separate values.

To fix this, in c:\python27\lib\site-packages\geonames\adapters\base.py, change:

```<code>def east_west_north_south_box(self, value):
    return self.set_string_parameter('east,west,north,south', value)
</code>```

to (works for my simple testing):

```<code>def east_west_north_south_box(self, value):
    for coord,val in zip(['east','west','north','south'],value):
        self.set_string_parameter(coord, val)
    return self
</code>```

Personally, using the country name seems preferable to the rather crude bounding box.

Title: Geonames bounding box

Body:
I use geonames API to validate whether a "string" is a place/location. The following is a snippet of my code.

import geonames.adapters.search

sa = geonames.adapters.search.Search(my_user_name)
result = sa.query('bordeaux').east_west_north_south_box([141.021805, 95.009331, 5.904417, -10.941861]).execute()

theresult = set()
for id_, name in result.get_flat_results():
    theresult.add(name.lower())
print 'bordeaux' in theresult

As you can see I added a bounding box of Indonesia when I did the search. But to my surprise the result of this code is "True" where we all know that Bordeaux is located in France. Is there something wrong with my code?

Body:
Instead of using coordinates bounding box use the country code, for example:

result = sa.query('bordeaux').country('id').execute()

returns no results, whereas:

result = sa.query('jakarta').country('id').execute()

returns some appropriate results, as does:

result = sa.query('bordeaux').country('fr').execute()

and also:

result = sa.query('bordeaux').country('us').execute()

Update:

Did some research and the geonames_rdf library doesn't convert the bounding box parameter into HTTP/REST parameters correctly - it applies a single parameter "east,west,south,north" when they should all be separate values.

To fix this, in c:\python27\lib\site-packages\geonames\adapters\base.py, change:

def east_west_north_south_box(self, value):
    return self.set_string_parameter('east,west,north,south', value)

to (works for my simple testing):

def east_west_north_south_box(self, value):
    for coord,val in zip(['east','west','north','south'],value):
        self.set_string_parameter(coord, val)
    return self

Personally, using the country name seems preferable to the rather crude bounding box.


问:
4 different elements, similar function
I'm new in JQuery and I'm trying to find out how I can use the similar function to different elements in JQuery.

It is for input radio button,

function *_check(), *_UNcheck() are do the same thing, but for different elements.

How to simplify the JQuery code:

$('.A').click(function () {
    if ($("#A_a").hasClass("un_check") && $("#B_b").hasClass("un_check")) {
        A_check();
    } else if ($("#A_a").hasClass("un_check") && $("#B_b").hasClass("check")) {
        A_check();

        B_UNcheck();
    };
});
$('.B').click(function () {
    if ($("#A_a").hasClass("un_check") && $("#B_b").hasClass("un_check")) {
        B_check();
    } else if ($("#A_a").hasClass("check") && $("#B_b").hasClass("un_check")) {
        B_check();

        A_UNcheck();
    };
});

//------------------------------------------------------------------------------
function A_check() {
    $("#A_a").removeClass("_hover");
    $("#A_a").addClass("_check");

    $("#A").prop("checked", true);
    $("#B").prop("checked", false);

    $("#A_a").removeClass("un_check").addClass("check");
};
function A_UNcheck() {
    $("#A_a").removeClass("_check");

    $("#A_a").removeClass("check").addClass("un_check");
};
function B_check() {
    $("#B_b").removeClass("_hover");
    $("#B_b").addClass("_check");

    $("#A").prop("checked", false);
    $("#B").prop("checked", true);

    $("#B_b").removeClass("un_check").addClass("check");
};
function B_UNcheck() {
    $("#B_b").removeClass("_check");

    $("#B_b").removeClass("check").addClass("un_check");
};
```

答:
Hope this helps:

```<code>$('.A').click(function () {
        check("A_a", "A", "B");
        unCheck("B_b");
});
$('.B').click(function () {
        check("B_b", "B", "A");
        unCheck("A_a");
});

function check(firstId, secondId, thirdId){
    $("#"+firstId).removeClass("_hover");
    $("#"+firstId).addClass("_check");

    $("#"+secondId).prop("checked", true);
    $("#"+thirdId).prop("checked", false);

    $("#"+firstId).removeClass("un_check").addClass("check");
}

function unCheck(firstId) {
    $("#"+firstId).removeClass("_check");
    $("#"+firstId).removeClass("check").addClass("un_check");
};
</code>```

Thanks

Title: 4 different elements, similar function

Body:
Hope this helps:

$('.A').click(function () {
        check("A_a", "A", "B");
        unCheck("B_b");
});
$('.B').click(function () {
        check("B_b", "B", "A");
        unCheck("A_a");
});

function check(firstId, secondId, thirdId){
    $("#"+firstId).removeClass("_hover");
    $("#"+firstId).addClass("_check");

    $("#"+secondId).prop("checked", true);
    $("#"+thirdId).prop("checked", false);

    $("#"+firstId).removeClass("un_check").addClass("check");
}

function unCheck(firstId) {
    $("#"+firstId).removeClass("_check");
    $("#"+firstId).removeClass("check").addClass("un_check");
};

Thanks