问:
Change font for TextView in ArrayAdapter in Android
I can't figure out away to change the textView font in an Array Adapter. I usually change the font using the code below

```<code>TextView textview = (TextView) findViewById(R.id.textViewsawtyat1);
Typeface face2 = Typeface.createFromAsset(textview.getContext().getAssets(), "fonts/Israr.ttf");
textview.setTypeface(face2);
</code>```

but i am getting an error when i try to use that method because it tries to run this code before creating the Array Adapter. Here is the code for the whole class.

```<code>public class PlayerMainScreen extends Activity implements View.OnTouchListener, AdapterView.OnItemClickListener{
    private ListView listView;
    private String TAG = "Album Main Screen";
    private FirebaseDatabase firebaseDatabaseInstance;
    private DatabaseReference booksInstance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player_main_screen);
        init();
        getData();
    }

    private void init(){

        listView = (ListView) findViewById(R.id.listView);

        listView.setOnItemClickListener(this);

    }
    private void getData(){

        Constants.showLoadingDialog(this);
        firebaseDatabaseInstance = FirebaseDatabase.getInstance();

        // get reference to 'users' node
        booksInstance = firebaseDatabaseInstance.getReference("sawtyat");

        booksInstance.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                setData(dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
    }

    List<List<String>> playerList;
    List<String> temp1, temp2;
    private void setData(DataSnapshot dataSnapshot){
        playerList = new ArrayList<>();
        temp1 = new ArrayList<>();
        temp2 = new ArrayList<>();

        for (DataSnapshot alert: dataSnapshot.getChildren()) {
            Log.d("cover_image_name", (String) alert.child("book_name").getValue());
            Log.d("cover_image_path", (String) alert.child("sound_path").getValue());

            temp1.add((String) alert.child("book_name").getValue());
            temp2.add((String) alert.child("sound_path").getValue());
        }
        playerList.add(temp1);
        playerList.add(temp2);
        if(playerList.size() > 0){
            setListView();
        }else{
            Toast.makeText(this, "No data Found.", Toast.LENGTH_SHORT).show();
        }
    }

    private void setListView(){
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.fragment_player_main_screen, R.id.textViewsawtyat1, playerList.get(0));

        listView.setAdapter(arrayAdapter);

TextView textview = (TextView) findViewById(R.id.textViewsawtyat1);
        Typeface face3 = Typeface.createFromAsset(textview.getContext().getAssets(), "fonts/Isra.ttf");
        textview.setTypeface(face3);

        Constants.hideDialog();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

        PlayAudio(position);
    }

    private void PlayAudio(int position){

        try {

            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri data = Uri.parse(playerList.get(1).get(position));
            intent.setDataAndType(data, "audio/*");
            startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this, "No player Found.", Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

the text view font i wanna change is in the method setListView

This is the error i am getting

```<code>                 --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.metwally.almostshar.almostshar, PID: 3116
                  java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.widget.TextView.getContext()' on a null object reference
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen.setListView(PlayerMainScreen.java:190)
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen.setData(PlayerMainScreen.java:179)
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen.access$000(PlayerMainScreen.java:40)
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen$5.onDataChange(PlayerMainScreen.java:151)
                      at com.google.android.gms.internal.zzbpx.zza(Unknown Source)
                      at com.google.android.gms.internal.zzbqx.zzZS(Unknown Source)
                      at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
Pass the correct Context :
change this </p>

```<code>Typeface face2 = Typeface.createFromAsset(textview.getContext().getAssets(), "fonts/Israr.ttf");
</code>```

<p>to </p>

```<code>Typeface face2 = Typeface.createFromAsset(PlayerMainScreen.this.getAssets(), "fonts/Israr.ttf");
</code>```

Body:
I can't figure out away to change the textView font in an Array Adapter. I usually change the font using the code below

TextView textview = (TextView) findViewById(R.id.textViewsawtyat1);
Typeface face2 = Typeface.createFromAsset(textview.getContext().getAssets(), "fonts/Israr.ttf");
textview.setTypeface(face2);

but i am getting an error when i try to use that method because it tries to run this code before creating the Array Adapter. Here is the code for the whole class.

public class PlayerMainScreen extends Activity implements View.OnTouchListener, AdapterView.OnItemClickListener{
    private ListView listView;
    private String TAG = "Album Main Screen";
    private FirebaseDatabase firebaseDatabaseInstance;
    private DatabaseReference booksInstance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player_main_screen);
        init();
        getData();
    }

    private void init(){

        listView = (ListView) findViewById(R.id.listView);

        listView.setOnItemClickListener(this);

    }
    private void getData(){

        Constants.showLoadingDialog(this);
        firebaseDatabaseInstance = FirebaseDatabase.getInstance();

        // get reference to 'users' node
        booksInstance = firebaseDatabaseInstance.getReference("sawtyat");

        booksInstance.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                setData(dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
    }

    List<List<String>> playerList;
    List<String> temp1, temp2;
    private void setData(DataSnapshot dataSnapshot){
        playerList = new ArrayList<>();
        temp1 = new ArrayList<>();
        temp2 = new ArrayList<>();

        for (DataSnapshot alert: dataSnapshot.getChildren()) {
            Log.d("cover_image_name", (String) alert.child("book_name").getValue());
            Log.d("cover_image_path", (String) alert.child("sound_path").getValue());

            temp1.add((String) alert.child("book_name").getValue());
            temp2.add((String) alert.child("sound_path").getValue());
        }
        playerList.add(temp1);
        playerList.add(temp2);
        if(playerList.size() > 0){
            setListView();
        }else{
            Toast.makeText(this, "No data Found.", Toast.LENGTH_SHORT).show();
        }
    }

    private void setListView(){
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.fragment_player_main_screen, R.id.textViewsawtyat1, playerList.get(0));

        listView.setAdapter(arrayAdapter);

TextView textview = (TextView) findViewById(R.id.textViewsawtyat1);
        Typeface face3 = Typeface.createFromAsset(textview.getContext().getAssets(), "fonts/Isra.ttf");
        textview.setTypeface(face3);

        Constants.hideDialog();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

        PlayAudio(position);
    }

    private void PlayAudio(int position){

        try {

            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri data = Uri.parse(playerList.get(1).get(position));
            intent.setDataAndType(data, "audio/*");
            startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this, "No player Found.", Toast.LENGTH_SHORT).show();
        }
    }
}

the text view font i wanna change is in the method setListView

This is the error i am getting

                 --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.metwally.almostshar.almostshar, PID: 3116
                  java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.widget.TextView.getContext()' on a null object reference
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen.setListView(PlayerMainScreen.java:190)
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen.setData(PlayerMainScreen.java:179)
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen.access$000(PlayerMainScreen.java:40)
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen$5.onDataChange(PlayerMainScreen.java:151)
                      at com.google.android.gms.internal.zzbpx.zza(Unknown Source)
                      at com.google.android.gms.internal.zzbqx.zzZS(Unknown Source)
                      at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
Pass the correct Context :
change this

Typeface face2 = Typeface.createFromAsset(textview.getContext().getAssets(), "fonts/Israr.ttf");

to

Typeface face2 = Typeface.createFromAsset(PlayerMainScreen.this.getAssets(), "fonts/Israr.ttf");


来源: stackexchange

问:
Moving outward a range of numbers plotted on a curve line
I was wondering how to make the numbers currently plotted on the curve line below to move a bit outward such that however a and b in my R code are changed the distance between the numbers and the curve line remain the same (i.e., constant)?

Please see my R code below the following image:

```<code> a = 0  ;  b = 1

curve( dnorm(x, mean = a, sd = b ), -4, 4, axes = F, ann = F)

xx <- -4:4

yy <- dnorm(xx, mean = a, sd = b)

text(xx, yy, paste(round(yy, 2) ), font = 2 )
</code>```

答:
As other colleagues also mentioned, the calculation of this distance can be taken care of by text() itself. One of the most suitable arguments in text() for this purpose is pos. Per R documentation pos takes 4 integer values, each of which move the text in one one of the 4 main directions: see ?text. In this case, 3 produces the desired effect.

Thus, the following might resolve the problem:

```<code>  a = 0  ;  b = 1

 curve( dnorm(x, mean = a, sd = b ), -4, 4, axes = F, ann = F)

 xx <- -4:4

 yy <- dnorm(xx, mean = a, sd = b)

 text(xx, yy, paste(round(yy, 2) ), font = 2, pos = 3 )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was wondering how to make the numbers currently plotted on the curve line below to move a bit outward such that however a and b in my R code are changed the distance between the numbers and the curve line remain the same (i.e., constant)?

Please see my R code below the following image:

 a = 0  ;  b = 1

curve( dnorm(x, mean = a, sd = b ), -4, 4, axes = F, ann = F)

xx <- -4:4

yy <- dnorm(xx, mean = a, sd = b)

text(xx, yy, paste(round(yy, 2) ), font = 2 )

Body:
As other colleagues also mentioned, the calculation of this distance can be taken care of by text() itself. One of the most suitable arguments in text() for this purpose is pos. Per R documentation pos takes 4 integer values, each of which move the text in one one of the 4 main directions: see ?text. In this case, 3 produces the desired effect.

Thus, the following might resolve the problem:

  a = 0  ;  b = 1

 curve( dnorm(x, mean = a, sd = b ), -4, 4, axes = F, ann = F)

 xx <- -4:4

 yy <- dnorm(xx, mean = a, sd = b)

 text(xx, yy, paste(round(yy, 2) ), font = 2, pos = 3 )


问:
What is wrong with this return statement?
```<code>return state$.select(state => {
     return state.user.access_token !== ''});
</code>```

This is the error i am getting,

[tslint] Missing Semicolon (semicolon)

答:
Add a semicolon:

```<code>return state$.select(state => {
    return state.user.access_token !== '';
});
</code>```

Or just do:

```<code>return state$.select(state => state.user.access_token !== '');
</code>```

Body:
return state$.select(state => {
     return state.user.access_token !== ''});

This is the error i am getting,

[tslint] Missing Semicolon (semicolon)

Body:
Add a semicolon:

return state$.select(state => {
    return state.user.access_token !== '';
});

Or just do:

return state$.select(state => state.user.access_token !== '');


问:
How to grey out data placeholder on kendo multiselect dropdown

I am having placeholder on kendo multiselect drop down and I wanted
  that placeholder to be greyed out. how can I do that?

答:
A placeholder in kendo multiselect widget is treated as input text so you can do this:

```<code>div.k-multiselect input{
    color: #adadad;
}
</code>```

Hope this works for you.

ContentLicense: CC BY-SA 4.0

Body:
A placeholder in kendo multiselect widget is treated as input text so you can do this:

div.k-multiselect input{
    color: #adadad;
}

Hope this works for you.


Title: saving numpy array to a file without brackets and white spaces

Body:
I have been trying to save numpy array to a file without brackets and white spaces at the beginning of each line. Unfortunately the last one does not work.
Array:

[[ 6.         -2.86751284 -0.35808319  1.79360812]
 [ 6.         -1.59351284 -0.02808319 -0.47039188]
 [ 6.          0.51848716  0.21791681  0.17060812]
 [ 6.         -1.63251284 -0.12208319  0.90460812]
 [ 6.         -0.26051284  0.03991681  1.33660812]
 [ 6.          1.87948716  0.43391681  0.21960812]
 [ 6.          2.52048716  0.45191681  1.44760812]
 [ 6.          0.40448716  0.04591681  2.58360812]
 [ 6.          1.81248716  0.30391681  2.62260812]]

Code:

f = open('result.txt','a')
f.write(str(geometry.shape[0]))
f.write(re.sub('[\[\]]', '', np.array_str(geometry))).lstrip()
f.write('\n')
f.close()

How can I fix it up?

Body:
What about this option:

a = np.array([[ 6, -2.86751284, -0.35808319,  1.79360812],
[ 6., -1.59351284, -0.02808319, -0.47039188],
[ 6., 0.51848716,  0.21791681,  0.17060812],
[ 6., 1.63251284, -0.12208319,  0.90460812],
[ 6., -0.26051284,  0.03991681,  1.33660812],
[ 6., 1.87948716,  0.43391681,  0.21960812],
[ 6., 2.52048716,  0.45191681,  1.44760812],
[ 6., 0.40448716,  0.04591681,  2.58360812],
[ 6., 1.81248716,  0.30391681,  2.62260812]], np.float32)

np.savetxt('outfile.txt', a)

no unnecessary white space and no brackets, but formatted in one line.


问:
How to auto format JSON on save in Vim
To be honest go has spoiled me. With go I got used to having a strict formatting standard that is being enforced by my editor (vim) and is almost accepted and followed by everybody else on the team and around the world.

I wanted to format JSON files on save the same way.

Question: How to auto format/indent/lint json files on save in vim.

答:
you can search for 'vim-json-line-format' plugin, Open a file in Normal mode, move your cursor on the json line, use <leader>pj to show formated json by print it, use <leader>wj could change the text to formatted json.
Invalid json can not format!

Title: How to auto format JSON on save in Vim


问:
Devise, how to reset password without current password?
I am trying when a user signs in for the first time is redirected to update(change) his password, but it seems I am missing something because the password is not changing.

Here is my code, am I missing?

ApplicationHelper.rb

```<code>  def after_sign_in_path_for(resource)
    if current_user.sign_in_count == 1
      edit_passwords_path
    else
      root_path
    end
  end
</code>```

PasswordsController.rb

```<code>class PasswordsController < ApplicationController

  def edit
  end

  def update
    if current_user.update_without_password(user_params)
      flash[:notice] = "Password updated successfully."
      redirect_to signed_in_root_path(current_user)
    else
      flash[:alert] = "There was a problem, please try again."
      render :edit
    end
  end

  private

    def user_params
      params.require(:user).permit(:password, :password_confirmation)
    end
end
</code>```

views/passwords/_form.html.eb

```<code><%= form_for current_user, url: passwords_path do |f| %>

  current_password:<br />
  <%#= f.password_field :current_password %><br />
  password:<br />
  <%= f.password_field :password %><br />
  password_confirmation:<br />
  <%= f.password_field :password_confirmation %><br />
  <br />
  <%= f.submit %>
<% end %>
</code>```

routes.rb

```<code>Rails.application.routes.draw do
  resources :tasks
  devise_for :users
  root 'tasks#index'
  resource :passwords
end
</code>```

Log

```<code>Started PATCH "/passwords" for ::1 at 2017-03-29 15:01:07 -0400
Processing by PasswordsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"FIxTxsfOML7P7L+xWxznRDcedXOralm7PjSJtpUi+C/4erA6VsvLJACUPFNE+yYXjJFLKWLRYkn0n5VZV2R+6A==", "user"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Update User"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
   (0.0ms)  begin transaction
   (0.0ms)  commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 3ms (ActiveRecord: 0.2ms)

Started GET "/" for ::1 at 2017-03-29 15:01:07 -0400
Processing by TasksController#index as HTML
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  Task Load (0.1ms)  SELECT "tasks".* FROM "tasks"
  Rendered tasks/index.html.erb within layouts/application (0.7ms)
  Rendered layouts/_messages.html.erb (0.0ms)
Completed 200 OK in 28ms (Views: 25.0ms | ActiveRecord: 0.2ms)
</code>```

答:
You can do this in various ways.

views/passwords/_form.html.eb

```<code><%= form_for current_user, url: passwords_path do |f| %>
  password:<br />
  <%= f.password_field :password %><br />

  password_confirmation:<br />
  <%= f.password_field :password_confirmation %><br />

  <br />
  <%= f.submit %>
<% end %>
</code>```

PasswordsController.rb

```<code>class PasswordsController < ApplicationController
  def update
    if current_user.update_attributes(user_params)
      flash[:notice] = "Password updated successfully."
      redirect_to signed_in_root_path(current_user)
    else
      flash[:alert] = current_user.errors.full_messages.join(', ')
      render :edit
    end
  end

  private

    def user_params
      params.require(:user).permit(:password, :password_confirmation)
    end
end
</code>```

Body:
I am trying when a user signs in for the first time is redirected to update(change) his password, but it seems I am missing something because the password is not changing.

Here is my code, am I missing?

ApplicationHelper.rb

  def after_sign_in_path_for(resource)
    if current_user.sign_in_count == 1
      edit_passwords_path
    else
      root_path
    end
  end

PasswordsController.rb

class PasswordsController < ApplicationController

  def edit
  end

  def update
    if current_user.update_without_password(user_params)
      flash[:notice] = "Password updated successfully."
      redirect_to signed_in_root_path(current_user)
    else
      flash[:alert] = "There was a problem, please try again."
      render :edit
    end
  end

  private

    def user_params
      params.require(:user).permit(:password, :password_confirmation)
    end
end

views/passwords/_form.html.eb

<%= form_for current_user, url: passwords_path do |f| %>

  current_password:

  <%#= f.password_field :current_password %>

  password:

  <%= f.password_field :password %>

  password_confirmation:

  <%= f.password_field :password_confirmation %>

  <%= f.submit %>
<% end %>

routes.rb

Rails.application.routes.draw do
  resources :tasks
  devise_for :users
  root 'tasks#index'
  resource :passwords
end

Log

Started PATCH "/passwords" for ::1 at 2017-03-29 15:01:07 -0400
Processing by PasswordsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"FIxTxsfOML7P7L+xWxznRDcedXOralm7PjSJtpUi+C/4erA6VsvLJACUPFNE+yYXjJFLKWLRYkn0n5VZV2R+6A==", "user"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Update User"}
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
   (0.0ms)  begin transaction
   (0.0ms)  commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 3ms (ActiveRecord: 0.2ms)

Started GET "/" for ::1 at 2017-03-29 15:01:07 -0400
Processing by TasksController#index as HTML
  User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  Task Load (0.1ms)  SELECT "tasks".* FROM "tasks"
  Rendered tasks/index.html.erb within layouts/application (0.7ms)
  Rendered layouts/_messages.html.erb (0.0ms)
Completed 200 OK in 28ms (Views: 25.0ms | ActiveRecord: 0.2ms)

Body:
You can do this in various ways.

views/passwords/_form.html.eb

<%= form_for current_user, url: passwords_path do |f| %>
  password:<br />
  <%= f.password_field :password %><br />

  password_confirmation:<br />
  <%= f.password_field :password_confirmation %><br />

  <br />
  <%= f.submit %>
<% end %>

PasswordsController.rb

class PasswordsController < ApplicationController
  def update
    if current_user.update_attributes(user_params)
      flash[:notice] = "Password updated successfully."
      redirect_to signed_in_root_path(current_user)
    else
      flash[:alert] = current_user.errors.full_messages.join(', ')
      render :edit
    end
  end

  private

    def user_params
      params.require(:user).permit(:password, :password_confirmation)
    end
end


问:
Select columns from function call in sqlalchemy core
In postgresql I have select col1, col2 from my_function(). How can I do that in sqlalchemy core?

select(func.my_function()) gives the result as a string, but I want a tuple.

答:
You'll want to use FunctionElement.alias() and the light weight column():

```<code>from sqlalchemy import func, select, column

stmt = select([column('col1'), column('col2')]).\
    select_from(func.my_function().alias())
</code>```

The documentation specifically mentions Postgresql as a use case for this construct. The above produces:

```<code>SELECT col1, col2
FROM my_function() AS anon_1
</code>```

Using the parameter _selectable of column() you could also:

```<code>In [4]: fn = func.my_function().alias()

In [5]: stmt = select([column('col1', _selectable=fn),
   ...:                column('col2', _selectable=fn)])

In [6]: print(stmt)
SELECT anon_1.col1, anon_1.col2
FROM my_function() AS anon_1
</code>```

but since _selectable is left undocumented, this might not be a good idea.

Body:
You'll want to use FunctionElement.alias() and the light weight column():

from sqlalchemy import func, select, column

stmt = select([column('col1'), column('col2')]).\
    select_from(func.my_function().alias())

The documentation specifically mentions Postgresql as a use case for this construct. The above produces:

SELECT col1, col2
FROM my_function() AS anon_1

Using the parameter _selectable of column() you could also:

In [4]: fn = func.my_function().alias()

In [5]: stmt = select([column('col1', _selectable=fn),
   ...:                column('col2', _selectable=fn)])

In [6]: print(stmt)
SELECT anon_1.col1, anon_1.col2
FROM my_function() AS anon_1

but since _selectable is left undocumented, this might not be a good idea.


问:
PHP: Need to convert imagemagick command to php script
I use this command to batch modify images for a site. They need to be this size to suit the theme.

Now I also want to use these images in Facebook Ads, but they have to be resized. The command I use (which works fine) is:

```<code>for i in `ls -1 *.jpg`; do convert $i -fuzz 10% -trim +repage -resize 980x1200 -background white -gravity center -extent 980x1200 $i; done
</code>```

Now I need to make a PHP script that does the same, but also returns the image as response.

I came up with the following:

```<code><?php

/* Create the object and read the image in */
$im = new Imagick("image.jpg");

/* Trim the image with 10% fuzz */
$im->trimImage(10);

/* Repage */
$im->setImagePage(0, 0, 0, 0);

/* Resize */
$im->resizeImage(1200,628,Imagick::FILTER_LANCZOS,0);

/* Add Borders*/
$im->setImageBackgroundColor('White');
$im->setGravity('Centre');
$im->setImageExtent(1200,628);

/* Output the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>
</code>```

Unfortunately it doesn't seem to work. All it does is return a black rectangle (which looks like the right dimensions as used in the script).

答:
you can run commands in php using " shell_exec(your command) ". Try once this may works for you.
Refer http://php.net/manual/en/function.shell-exec.php </p>

Body:
I use this command to batch modify images for a site. They need to be this size to suit the theme.

Now I also want to use these images in Facebook Ads, but they have to be resized. The command I use (which works fine) is:

for i in `ls -1 *.jpg`; do convert $i -fuzz 10% -trim +repage -resize 980x1200 -background white -gravity center -extent 980x1200 $i; done

Now I need to make a PHP script that does the same, but also returns the image as response.

I came up with the following:

<?php

/* Create the object and read the image in */
$im = new Imagick("image.jpg");

/* Trim the image with 10% fuzz */
$im->trimImage(10);

/* Repage */
$im->setImagePage(0, 0, 0, 0);

/* Resize */
$im->resizeImage(1200,628,Imagick::FILTER_LANCZOS,0);

/* Add Borders*/
$im->setImageBackgroundColor('White');
$im->setGravity('Centre');
$im->setImageExtent(1200,628);

/* Output the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>

Unfortunately it doesn't seem to work. All it does is return a black rectangle (which looks like the right dimensions as used in the script).


问:
How to use Scala's this typing, abstract types, etc. to implement a Self type?
I couldn't find the answer to this in any other question. Suppose that I have an abstract superclass Abstract0 with two subclasses, Concrete1 and Concrete1. I want to be able to define in Abstract0 something like

```<code>def setOption(...): Self = {...}
</code>```

where Self would be the concrete subtype. This would allow chaining calls to setOption like this:

```<code>val obj = new Concrete1.setOption(...).setOption(...)
</code>```

and still get Concrete1 as the inferred type of obj.

What I don't want is to define this:

```<code>abstract class Abstract0[T <: Abstract0[T]]
</code>```

because it makes it harder for clients to handle this type. I tried various possibilities including an abstract type:

```<code>abstract class Abstract0 {
  type Self <: Abstract0
}

class Concrete1 extends Abstract0 {
  type Self = Concrete1
}
</code>```

but then it is impossible to implement setOption, because this in Abstract0 does not have type Self. And using this: Self => also doesn't work in Abstract0.

What solutions are there to this issue?

答:
This is the exact use case of this.type. It would be like:

```<code>def setOption(...): this.type = {
  // Do stuff ...
  this
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I couldn't find the answer to this in any other question. Suppose that I have an abstract superclass Abstract0 with two subclasses, Concrete1 and Concrete1. I want to be able to define in Abstract0 something like

def setOption(...): Self = {...}

where Self would be the concrete subtype. This would allow chaining calls to setOption like this:

val obj = new Concrete1.setOption(...).setOption(...)

and still get Concrete1 as the inferred type of obj.

What I don't want is to define this:

abstract class Abstract0[T <: Abstract0[T]]

because it makes it harder for clients to handle this type. I tried various possibilities including an abstract type:

abstract class Abstract0 {
  type Self <: Abstract0
}

class Concrete1 extends Abstract0 {
  type Self = Concrete1
}

but then it is impossible to implement setOption, because this in Abstract0 does not have type Self. And using this: Self => also doesn't work in Abstract0.

What solutions are there to this issue?

Body:
This is the exact use case of this.type. It would be like:

def setOption(...): this.type = {
  // Do stuff ...
  this
}


问:
Big-Oh ascending order of some functions f(n)
Put these function in the ascending order of their growth in terms of n:
 2^((log n)^0.5), 2^n, 2^(n/2), n^(4/3), n(log n)^3, n^(log n), 2^(n^2), n!</p>

答:
Partial answer: 2^((log n)^0.5), 2^(n/2), 2^n, n!, 2^(n^2).

Need to put these as well: n^(4/3), n(log n)^3, n^(log n)


问:
Jump directly to certain parts of a function
I would like a hint on how to complete this puzzle. I need to be able to print what is normally printed out in reverse. Normally this prints, hello there. I need it to print there hello. I am only allowed to add code where it is commented.

Here are some of my thoughts that don't work.

I thought about using the heap to store some data but I can't because stdlib.h is not included.

Can't use goto because I can't add labels and what I would goto is all in one line

Can't use recursion because there are no input parameters and no global variables to modify.

Can't possibly think of a way assembly could help but hey maybe?

I can't do anything obvious like just calling printf's and quitting the program early.

Thoughts on something to do with function pointers? I still don't see how they would help.

```<code>#include <stdio.h>
void f1(); void f2(); void f3();

int main() { f1(); printf("\n"); return 0; }

void f1() { f2(); printf(" there "); }

void f2() { f3(); printf(" hello "); }

void f3(){
    int x;
    //Can add whatever under here
}
</code>```

答:
This should be a portable solution that doesn't mess with the stack and return addresses. Most probably not what was expected by who wrote that challenge, but it's way more fun to think out of the box.

```<code>void f3(){
    int x;
    //Can add whatever under here
    static count = 0;
    static char buf[256];
    if(count==0) {
        setvbuf(stdout, buf, _IOFBF, sizeof(buf));
        int atexit (void (*func)(void));
        atexit(f3);
        count = 1;
    } else {
        const char *src = " there  hello \n";
        char *dest = buf;
        for(; *src;) *dest++ = *src++;
    }
}
</code>```

http://ideone.com/S4zMHP

This works by first using setvbuf to replace the stdout buffer with one that we provide, and switching it to full buffering (instead of line buffering) to make sure that no flush happens before the end of the program (notice that no output has been written yet, so calling setvbuf is legal). We also call atexit to make sure we get called before the end of the program (we don't have stdlib.h, but who needs headers when the required prototypes are already known).

When we are called again (thanks to atexit), the two printf have been called, but the buffer hasn't been flushed yet. We outright replace its content with the string of our interest (which is just as big as what has been written), and return. The subsequent implicit fclose will dump out the modified content of our buffer instead of what was written by the printf.

Body:
I would like a hint on how to complete this puzzle. I need to be able to print what is normally printed out in reverse. Normally this prints, hello there. I need it to print there hello. I am only allowed to add code where it is commented.

Here are some of my thoughts that don't work.

I thought about using the heap to store some data but I can't because stdlib.h is not included.

Can't use goto because I can't add labels and what I would goto is all in one line

Can't use recursion because there are no input parameters and no global variables to modify.

Can't possibly think of a way assembly could help but hey maybe?

I can't do anything obvious like just calling printf's and quitting the program early.

Thoughts on something to do with function pointers? I still don't see how they would help.

#include <stdio.h>
void f1(); void f2(); void f3();

int main() { f1(); printf("\n"); return 0; }

void f1() { f2(); printf(" there "); }

void f2() { f3(); printf(" hello "); }

void f3(){
    int x;
    //Can add whatever under here
}

Body:
This should be a portable solution that doesn't mess with the stack and return addresses. Most probably not what was expected by who wrote that challenge, but it's way more fun to think out of the box.

void f3(){
    int x;
    //Can add whatever under here
    static count = 0;
    static char buf[256];
    if(count==0) {
        setvbuf(stdout, buf, _IOFBF, sizeof(buf));
        int atexit (void (*func)(void));
        atexit(f3);
        count = 1;
    } else {
        const char *src = " there  hello \n";
        char *dest = buf;
        for(; *src;) *dest++ = *src++;
    }
}

http://ideone.com/S4zMHP

This works by first using setvbuf to replace the stdout buffer with one that we provide, and switching it to full buffering (instead of line buffering) to make sure that no flush happens before the end of the program (notice that no output has been written yet, so calling setvbuf is legal). We also call atexit to make sure we get called before the end of the program (we don't have stdlib.h, but who needs headers when the required prototypes are already known).

When we are called again (thanks to atexit), the two printf have been called, but the buffer hasn't been flushed yet. We outright replace its content with the string of our interest (which is just as big as what has been written), and return. The subsequent implicit fclose will dump out the modified content of our buffer instead of what was written by the printf.


问:
ffmpeg library is not working
I have got FFmpeg compiled (libffmpeg.so) on Android. Now I have to build either an application like RockPlayer or use existing Android multimedia framework to invoke FFmpeg along with video playing.

Do you have steps / procedures / code / example on integrating FFmpeg on Android / StageFright?

Can you please guide me on how can I use this library for multimedia
  playback?

I already did rendering, mixing.

答:
Download ffmpeg from here: http://bambuser.com/opensource.  It contains scripts to build ffmpeg for android.
Modify build.sh. Replace "com.bambuser.broadcaster" with your package name.  You also need to set the ffmpeg flags to enable to codecs you're interested in.
Run build.sh, and copy the build/ffmpeg directory into your apps jni/lib directory.
Use fasaxc's makefile from the SO post.
Create a native.c file in your jni directory and a java wrapper.  To start with you can model it after hello-jni in NDK samples (/samples/hello-jni).
Include headers in your native.c file like this: #include "libavcodec/avcodec.h".  And call the functions you need: avcodec_register_all(), etc...
Include the native libraries in your root activity by adding: static { System.loadLibraries(""); }</p>

Title: ffmpeg library is not working


问:
What's the max amount of files per directory? (Linux)
I have to store a lot of image files, but I'm not sure about how to organize my directory structure.

Is there a limit of files per directory, or directories per directory?

Also, should I create the filenames randomly so they are not guessable? (so I don't get my bandwith hammered by someone trying to download all the files)

答: Wikipedia has a nice overview: http://en.wikipedia.org/wiki/Comparison_of_file_systems</p>


问:
Regular expression to match (name="myName".*house="myHouse"|house="myHouse".*name="myName") without using OR
I am writing a regular expression which needs below criteria to satisfy.

```<code>(name="myName".*house="myHouse"|house="myHouse".*name="myName")
</code>```

Either name or house can come first. My Regex should match both.

Actually my real code is even more bigger after writing the repeated code.

Is there any way to use the regular expression without Repetition like above ?

答:
You can use positive lookahead assertions for this. It's a bit jejune, but if you're trying to keep things simple, it should work. What you want to do is confirm:

```<code>I am looking at .*house

    AND

I am looking at .*name
</code>```

without regard to the lengths of the two .* parts.

So, since lookahead expressions are zero width (that is, they match without actually consuming any characters - they just "look ahead") you can paste together as many as you'd like.

Please be aware: doing this can get really expensive, performance-wise. You will have to scan, and then re-scan, for each extra term that you match. If the strings you are matching against are long, this will slow you down a lot.

Sample regex:

```<code>(?=.*name="myName")(?=.*house="myHouse")
</code>```

Body:
I am writing a regular expression which needs below criteria to satisfy.

(name="myName".*house="myHouse"|house="myHouse".*name="myName")

Either name or house can come first. My Regex should match both.

Actually my real code is even more bigger after writing the repeated code.

Is there any way to use the regular expression without Repetition like above ?

Body:
You can use positive lookahead assertions for this. It's a bit jejune, but if you're trying to keep things simple, it should work. What you want to do is confirm:

I am looking at .*house

    AND

I am looking at .*name

without regard to the lengths of the two .* parts.

So, since lookahead expressions are zero width (that is, they match without actually consuming any characters - they just "look ahead") you can paste together as many as you'd like.

Please be aware: doing this can get really expensive, performance-wise. You will have to scan, and then re-scan, for each extra term that you match. If the strings you are matching against are long, this will slow you down a lot.

Sample regex:

(?=.*name="myName")(?=.*house="myHouse")


问:
OpenCms tags in OpenCms tags
I know this may be a silly question but I ma trying to understand the jsp templates in opencms.

Even though we have htm tags in jsp. what is the actual use of cms tags such as :

```<code> <cms:template element="body">
<cms:include element="body" />
</code>```

答:
The cms:template tag

With the  tag, you can add control structures to the template which allows it to deal with multiple page elements.

The cms:include tag

This tag is used to include files from the OpenCms VFS dynamically at runtime. The included file is treated like a request with optional additional request parameters.
There are different options to determine the name of the included file by using one of the following attributes:
 - page
 - property
 - attribute

If none of these attributes has been set, the body of the  tag is evaluated and the result is used as filename.

```<code><%@ page session="false" %>
<%@ taglib prefix="cms" uri="http://www.opencms.org/taglib/cms" %>

<cms:template element="head">

<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title><cms:property name="title" escapeHtml="true" /></title>

<meta HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; CHARSET=<cms:property name="content-encoding" default="ISO-8859-1" />">

<link type="text/css" rel="stylesheet" href="<cms:link>../resources/mystyle.css</cms:link>">

<cms:editable />

</head>
<body>

<h2>My first template head</h2>

<!-- Main page body starts here -->
</cms:template>

<cms:template element="body">

<h2>This is the first page element:</h2>

<cms:include element="body" editable="true"/>

<cms:template ifexists="body2">
<h2>This is the second page element:</h2>
<cms:include element="body2" editable= "true"/>
</cms:template>

</cms:template>

<cms:template element="foot">
<!-- Main page body ends here -->

<h2>My first template foot</h2>

</body>
</html>
</cms:template>
</code>```

Title: OpenCms tags in OpenCms tags

Body:
I know this may be a silly question but I ma trying to understand the jsp templates in opencms.

Even though we have htm tags in jsp. what is the actual use of cms tags such as :

 <cms:template element="body">
<cms:include element="body" />

Body:
The cms:template tag

With the  tag, you can add control structures to the template which allows it to deal with multiple page elements.

The cms:include tag

This tag is used to include files from the OpenCms VFS dynamically at runtime. The included file is treated like a request with optional additional request parameters.
There are different options to determine the name of the included file by using one of the following attributes:
 - page
 - property
 - attribute

If none of these attributes has been set, the body of the  tag is evaluated and the result is used as filename.

<%@ page session="false" %>
<%@ taglib prefix="cms" uri="http://www.opencms.org/taglib/cms" %>

<cms:template element="head">

<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title><cms:property name="title" escapeHtml="true" /></title>

<meta HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; CHARSET=<cms:property name="content-encoding" default="ISO-8859-1" />">

<link type="text/css" rel="stylesheet" href="<cms:link>../resources/mystyle.css</cms:link>">

<cms:editable />

</head>
<body>

<h2>My first template head</h2>

<!-- Main page body starts here -->
</cms:template>

<cms:template element="body">

<h2>This is the first page element:</h2>

<cms:include element="body" editable="true"/>

<cms:template ifexists="body2">
<h2>This is the second page element:</h2>
<cms:include element="body2" editable= "true"/>
</cms:template>

</cms:template>

<cms:template element="foot">
<!-- Main page body ends here -->

<h2>My first template foot</h2>

</body>
</html>
</cms:template>


问:
jQuery trigger("click") not working
Can someone please explain what is wrong with the pasted code. It shows alert on hover but does not perform click event like I expect, and click does not work on either  tag or <select> tag. My purpose is to expand the select element on hover by triggering click event

```<code><!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>

<body>
    <a id="linkElement" href="www.google.co.uk">click</a>

    <select name="cars" id="selectElemet">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>

    <script>
        $(document).ready(function () {
            $("#selectElement").mouseover(function () {
                $("#selectElement").trigger("click");
            });

            $("#linkElement").mouseover(function () {
                alert('here');
                $("#linkElement").trigger("click");
            });
        });
    </script>
</body>

</html>
</code>```

答:
.trigger("click") will not actually click the element, it will only trigger click handler attached with the element. Since you have not attached any none is triggered.

You can use native .click()

```<code>$("#selectElement").get(0).click(); //get(0) returns reference to DOM element
</code>```

Title: jQuery trigger("click") not working

Body:
Can someone please explain what is wrong with the pasted code. It shows alert on hover but does not perform click event like I expect, and click does not work on either  tag or <select> tag. My purpose is to expand the select element on hover by triggering click event

<!DOCTYPE html>

    click

    <select name="cars" id="selectElemet">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>

Body:
.trigger("click") will not actually click the element, it will only trigger click handler attached with the element. Since you have not attached any none is triggered.

You can use native .click()

$("#selectElement").get(0).click(); //get(0) returns reference to DOM element


问:
Understanding how parameters are passed to functions in Assembly
I am reading this writeup on how to perform a ret2libc exploit.  It states that the arguments passed to a function are stored at ebp+8.

Now, if I take a simple C program

```<code>#include <stdlib.h>

int main() {
  system("/bin/sh");
}
</code>```

And compile it:
gcc -m32 -o test_sh test_sh.c

and look at the disassembly of it with
objdump -d -M intel test_sh

```<code>0804840b <main>:
 804840b:       8d 4c 24 04             lea    ecx,[esp+0x4]
 804840f:       83 e4 f0                and    esp,0xfffffff0
 8048412:       ff 71 fc                push   DWORD PTR [ecx-0x4]
 8048415:       55                      push   ebp
 8048416:       89 e5                   mov    ebp,esp
 8048418:       51                      push   ecx
 8048419:       83 ec 04                sub    esp,0x4
 804841c:       83 ec 0c                sub    esp,0xc
 804841f:       68 c4 84 04 08          push   0x80484c4
 8048424:       e8 b7 fe ff ff          call   80482e0 <system@plt>
 8048429:       83 c4 10                add    esp,0x10
 804842c:       b8 00 00 00 00          mov    eax,0x0
 8048431:       8b 4d fc                mov    ecx,DWORD PTR [ebp-0x4]
 8048434:       c9                      leave
 8048435:       8d 61 fc                lea    esp,[ecx-0x4]
 8048438:       c3                      ret
 8048439:       66 90                   xchg   ax,ax
 804843b:       66 90                   xchg   ax,ax
 804843d:       66 90                   xchg   ax,ax
 804843f:       90                      nop
</code>```

The line

```<code>804841f:       68 c4 84 04 08          push   0x80484c4
</code>```

Pushes the address of the string "/bin/sh" onto the stack.  Immediately afterwards the system@plt function is called.  So how does one arrive to ebp+8 from the above output?

Help would be appreciated!

答:
The arguments passed to a function are stored at ebp+8.

That's from the called function's point of view, not from the calling function's point of view.  The calling function has its own arguments at ebp+8, and your main() does not use any of its arguments, hence, you don't see any use of ebp+8 in your main().

You can see ebp+8 being used as follows:

Try writing a second function, with arguments, and calling it from main(), instead of invoking system().  You still won't see any use of ebp+8 within main(), but you will see it being used in your second function.

Try declaring your main() to accept its char** argv argument, then try sending argv[0] to printf().

Body:
I am reading this writeup on how to perform a ret2libc exploit.  It states that the arguments passed to a function are stored at ebp+8.

Now, if I take a simple C program

#include <stdlib.h>

int main() {
  system("/bin/sh");
}

And compile it:
gcc -m32 -o test_sh test_sh.c

and look at the disassembly of it with
objdump -d -M intel test_sh

0804840b :
 804840b:       8d 4c 24 04             lea    ecx,[esp+0x4]
 804840f:       83 e4 f0                and    esp,0xfffffff0
 8048412:       ff 71 fc                push   DWORD PTR [ecx-0x4]
 8048415:       55                      push   ebp
 8048416:       89 e5                   mov    ebp,esp
 8048418:       51                      push   ecx
 8048419:       83 ec 04                sub    esp,0x4
 804841c:       83 ec 0c                sub    esp,0xc
 804841f:       68 c4 84 04 08          push   0x80484c4
 8048424:       e8 b7 fe ff ff          call   80482e0 <system@plt>
 8048429:       83 c4 10                add    esp,0x10
 804842c:       b8 00 00 00 00          mov    eax,0x0
 8048431:       8b 4d fc                mov    ecx,DWORD PTR [ebp-0x4]
 8048434:       c9                      leave
 8048435:       8d 61 fc                lea    esp,[ecx-0x4]
 8048438:       c3                      ret
 8048439:       66 90                   xchg   ax,ax
 804843b:       66 90                   xchg   ax,ax
 804843d:       66 90                   xchg   ax,ax
 804843f:       90                      nop

The line

804841f:       68 c4 84 04 08          push   0x80484c4

Pushes the address of the string "/bin/sh" onto the stack.  Immediately afterwards the system@plt function is called.  So how does one arrive to ebp+8 from the above output?

Help would be appreciated!


问:
Change R class package android/eclipse
Im working on a little interface in android and when I run it the "xxx application has stopped unexpectedly" appears. Im looking for posible errors but I don't find anything.

Anyway I would like to change the R class package name, when I refactor->rename it eclipse generates another one in the old package,even if I delete that package eclipse generates it again, I can't get rid of it!

答: To change the package name of the generated R class, change the package property of the <manifest> tag in AndroidManifest.xml

Title: Change R class package android/eclipse


问:
opencv template matching result
When using matchTemplate from OpenCV, how do you programmatically know if the call returned a good result or not?

The function always returns an array image and the location of the top-left or the bottom-right angle of the detected area depending on the method but no information is returned about whether the match is good or not.

Is visual inspection the only way to do this?

答:
Template matching is a method that check how much two images are similar to each other.

The process of images comparison is done by correlation methods, in order to understand better you'll have to understand the equations

The most common method (I believe) is Normalize Cross Correlation

```<code>CV_TM_CCORR_NORMED
</code>```

This method calculate all the correlation coefficients for every displacement between the input images.

After the template matching, you can filter the results by decent threshold, lets say 0.5, to check if the images are similar (this threshold depends on your input images, e.g lightning, different sensor types ect.), than look for the max value displacement.

```<code>Mat frame, subFrame, result;
MatchTemplate(frame, subFrame, result, CV_TM_CCORR_NORMED);
double minVal; double maxVal; Point minLoc; Point maxLoc;
Point matchLoc;
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc);
if (maxVal < 0.5)
{
    // No match
     return;
}
</code>```

This means that if you shift subFrame by minLoc, maxLoc pixels to each direction you'd received the most similar displacement for subFrame to match Frame.

Title: opencv template matching result

Body:
Template matching is a method that check how much two images are similar to each other.

The process of images comparison is done by correlation methods, in order to understand better you'll have to understand the equations

The most common method (I believe) is Normalize Cross Correlation

CV_TM_CCORR_NORMED

This method calculate all the correlation coefficients for every displacement between the input images.

After the template matching, you can filter the results by decent threshold, lets say 0.5, to check if the images are similar (this threshold depends on your input images, e.g lightning, different sensor types ect.), than look for the max value displacement.

Mat frame, subFrame, result;
MatchTemplate(frame, subFrame, result, CV_TM_CCORR_NORMED);
double minVal; double maxVal; Point minLoc; Point maxLoc;
Point matchLoc;
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc);
if (maxVal < 0.5)
{
    // No match
     return;
}

This means that if you shift subFrame by minLoc, maxLoc pixels to each direction you'd received the most similar displacement for subFrame to match Frame.


问:
APNS Payload Size issue
I'm writing an VOIP based iOS application. As per official doc, we can send data upto 5KB using VOIP, but in my case it getting failed in less then 1KB data.

I'm using "body" under "alert" attribute tag to send Big content.
Alert attribute size get truncate if text size exceeded.

In document read I also got dependency to use HTTP/2 Protocol, How this is dependent while APNS server do use XMPP protocol to send message ?

Any suggestion ?

答:
Basically you want to get 5KB data and it is getting failed with 1KB.

Try scheduling local notification as per pushkit payload you receive and keep data in local notification's user info, that way you can keep your data within app.

Once sound file of local notification plays ( Max 30 seconds ) App will get invoke in background then you can save data in NSUserDefault or SQLite or use it for some purpose.

Pushkit reference

Title: APNS Payload Size issue


问:
Angular form save not working with dynamic push data
I am new to angular and stuck with dynamic data binding. I have four data
   fields 2 static and 2 dynamically adding after add button. When I click add
   button only two of the fields are shown on the display and remaining data
   is not populated. I might had make some mistake in data passing.
   The first two fields are static and second two are dynamic need to add as
   user clicks. The same happens when using form.
   Will any one please help me resolve this. Thanks in advance.
   Below is my code:</p>

Controller:

```<code>var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.items = [];

  $scope.itemsToAdd = [{
    firstName: '',
    lastName: ''
  }];

  $scope.add = function(itemToAdd) {

    var index = $scope.itemsToAdd.indexOf(itemToAdd);

    $scope.itemsToAdd.splice(index, 1);

    $scope.items.push(angular.copy(itemToAdd))
  }

  $scope.addNew = function() {

    $scope.itemsToAdd.push({
      firstName: '',
      lastName: ''
    })
  }
});
</code>```

View (HTML):

```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="plunker" ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>

  <div ng-repeat="item in items">
     {{item.regno}} {{item.section}}
    {{item.firstName}} {{item.lastName}}
  </div>
    <input type="text" ng-model="itemToAdd.regno" />
    <input type="text" ng-model="itemToAdd.section" />
  <div ng-repeat="itemToAdd in itemsToAdd">
    <input type="text" ng-model="itemToAdd.firstName" />
    <input type="text" ng-model="itemToAdd.lastName" />
    <button ng-click="add(itemToAdd)">Add</button>
  </div>
  <div>
    <button ng-click="addNew()">Add new</button>
  </div>
</body>
</code>```

答:
From directives-that-create-scopes angular docs

some directives, such as ng-controller and ng-repeat, create new child scopes and attach the child scope to the corresponding DOM element

In your case,

```<code>itemToAdd.regno & itemToAdd.section are different modals and in different scope
</code>```

compare to itemToAdd.firstName & itemToAdd.lastName.

So,regno & section are not part of inner itemToAdd of ng-repeat.

Thats why,you are not able to get in your $scope.items

You have to add regno & section in add function

```<code>$scope.add = function(itemToAdd) {

    itemToAdd.regno = $scope.itemsToAdd.regno;
    itemToAdd.section = $scope.itemsToAdd.section;

    $scope.items.push(angular.copy(itemToAdd))
    console.log($scope.items);
  }
</code>```

Body:
I am new to angular and stuck with dynamic data binding. I have four data
   fields 2 static and 2 dynamically adding after add button. When I click add
   button only two of the fields are shown on the display and remaining data
   is not populated. I might had make some mistake in data passing.
   The first two fields are static and second two are dynamic need to add as
   user clicks. The same happens when using form.
   Will any one please help me resolve this. Thanks in advance.
   Below is my code:

Controller:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.items = [];

  $scope.itemsToAdd = [{
    firstName: '',
    lastName: ''
  }];

  $scope.add = function(itemToAdd) {

    var index = $scope.itemsToAdd.indexOf(itemToAdd);

    $scope.itemsToAdd.splice(index, 1);

    $scope.items.push(angular.copy(itemToAdd))
  }

  $scope.addNew = function() {

    $scope.itemsToAdd.push({
      firstName: '',
      lastName: ''
    })
  }
});

View (HTML):

Hello {{name}}!

     {{item.regno}} {{item.section}}
    {{item.firstName}} {{item.lastName}}

    <input type="text" ng-model="itemToAdd.regno" />
    <input type="text" ng-model="itemToAdd.section" />

    <input type="text" ng-model="itemToAdd.firstName" />
    <input type="text" ng-model="itemToAdd.lastName" />
    <button ng-click="add(itemToAdd)">Add</button>

    <button ng-click="addNew()">Add new</button>

Body:
From directives-that-create-scopes angular docs

some directives, such as ng-controller and ng-repeat, create new child scopes and attach the child scope to the corresponding DOM element

In your case,

itemToAdd.regno & itemToAdd.section are different modals and in different scope

compare to itemToAdd.firstName & itemToAdd.lastName.

So,regno & section are not part of inner itemToAdd of ng-repeat.

Thats why,you are not able to get in your $scope.items

You have to add regno & section in add function

$scope.add = function(itemToAdd) {

    itemToAdd.regno = $scope.itemsToAdd.regno;
    itemToAdd.section = $scope.itemsToAdd.section;

    $scope.items.push(angular.copy(itemToAdd))
    console.log($scope.items);
  }


问:
How to stop Camel Context immediately?
I have a camel application where I create below structure

```<code>main thread
        create Camel Context
          addRoute(routeBuilder1)
          addRoute(routeBuilder2)
        context.start
</code>```

RouteBuilder1

```<code>    R11
    R12
    R13
    R14
</code>```

RouteBuilder2

```<code>    R21
    R22
</code>```

In very specific situation, I need to stop the context(stop all processing right now). When I use context.shutdown,I noticed that if a route processing is in progress, camel is not able to stop it(called as gracefull shutdown), and that route continue processing. Whereas,in my case I need to hard stop everything immediately.

How can we achieve that?

答:
Have you seen this related question?

How to properly stop camelContext from being killed in a standalone application

Maybe you can try it in the same way using "kill -9".

Title: How to stop Camel Context immediately?

Body:
I have a camel application where I create below structure

main thread
        create Camel Context
          addRoute(routeBuilder1)
          addRoute(routeBuilder2)
        context.start

RouteBuilder1

    R11
    R12
    R13
    R14

RouteBuilder2

    R21
    R22

In very specific situation, I need to stop the context(stop all processing right now). When I use context.shutdown,I noticed that if a route processing is in progress, camel is not able to stop it(called as gracefull shutdown), and that route continue processing. Whereas,in my case I need to hard stop everything immediately.

How can we achieve that?


问:
Why the values of a function are not reflecting their values during function call in angularjs?(new to angularjs)
I need to display a div of comment box section on ng-click of the button invoking the function from controller as defined in the below HTML...picking up the index values from the table and validating the ng-if condition as shown in the code

```<code><button class="btn btn-outlined" ng-click="vm.showCommentBox1($parent.$index, $index)">Save All</button>
   <div class="comment-box custom saveAll" ng-if="tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].toBeCommented">
      <div class="panel panel-default">
          <div class="panel-heading">
              <button type="button" class="close" aria-label="Close" ng-click="baseline.toBeSaved = false" title="Close comment box"><span aria-hidden="true">Ã—</span>
              </button>
              <h3 class="panel-title blue-30">Comment</h3>
          </div>
          <div class="panel-body">
              <form>
                  <div class="form-group">
                    <textarea class="form-control bg-white" ng-model="tableData.template.selectedTowers[$parent.$parent.$parent.$parent.$index].baselines[$index].comment"
                      placeholder="Add your description"></textarea>
                  </div>
                  <button ng-click="saveAllRows(tableData.dealName, tower.towerName, baseline, $parent.$parent.$parent.$parent.$index, $index, tower.towerGeo, tableData.template.selectedTowers[$parent.$parent.$parent.$parent.$index].baselines[$index].comment)"
                    class="btn btn-filled btn-xs pull-right">Submit</button>
                </form>
            </div>
        </div>
    </div>
</code>```

The function with the arguments are going undefined while the same arguments in different function possess some values

```<code> vm.showCommentBox1 = function (towerIndex, baselineIndex) {
  $scope.tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].toBeCommented = true;
  $scope.tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].toBeSaved = true;
  $scope.tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].showPreviousComments = false;
}
</code>```

in the above code towerIndex and baselineIndex are going undefined while the same has some values intended when different functions are invoked

Example:the below function possess the values for both the arguments

```<code> vm.enableSaveButton = function (towerIndex, baselineIndex) {
  // console.log("Changed", baseline);
  $scope.tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].toBeCommented = true;
}
</code>```

By,this situation im stuck and im not able pass the ng-if condition true in my HTML so that i can display the comment box.

please,help on this

Thank you

答: As it was a button outside the table i can't pass the parameters as ($parent.$index,$index) from controllers because only table possess the $index values...it was my bad i didn't notice that at beginning.</p>

Body:
I need to display a div of comment box section on ng-click of the button invoking the function from controller as defined in the below HTML...picking up the index values from the table and validating the ng-if condition as shown in the code

<button class="btn btn-outlined" ng-click="vm.showCommentBox1($parent.$index, $index)">Save All</button>

              <button type="button" class="close" aria-label="Close" ng-click="baseline.toBeSaved = false" title="Close comment box">Ã—
              </button>

Comment

              <form>

                    <textarea class="form-control bg-white" ng-model="tableData.template.selectedTowers[$parent.$parent.$parent.$parent.$index].baselines[$index].comment"
                      placeholder="Add your description"></textarea>

                  <button ng-click="saveAllRows(tableData.dealName, tower.towerName, baseline, $parent.$parent.$parent.$parent.$index, $index, tower.towerGeo, tableData.template.selectedTowers[$parent.$parent.$parent.$parent.$index].baselines[$index].comment)"
                    class="btn btn-filled btn-xs pull-right">Submit</button>
                </form>

The function with the arguments are going undefined while the same arguments in different function possess some values

 vm.showCommentBox1 = function (towerIndex, baselineIndex) {
  $scope.tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].toBeCommented = true;
  $scope.tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].toBeSaved = true;
  $scope.tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].showPreviousComments = false;
}

in the above code towerIndex and baselineIndex are going undefined while the same has some values intended when different functions are invoked

Example:the below function possess the values for both the arguments

 vm.enableSaveButton = function (towerIndex, baselineIndex) {
  // console.log("Changed", baseline);
  $scope.tableData.template.selectedTowers[towerIndex].baselines[baselineIndex].toBeCommented = true;
}

By,this situation im stuck and im not able pass the ng-if condition true in my HTML so that i can display the comment box.

please,help on this

Thank you


问:
Fatal error: Call to a member function prepare() on null
I'm getting this error and i can't find whats wrong.

I've read through the other posts about this error but none of them seemed to help.

Fatal error: Call to a member function prepare() on null on line 92

```<code>        <?php

  include 'config.php';

   $lengd = $_POST["lengd"];
      $height = $_POST["height"];
       $width = $_POST["width"];

     $min_lengd = $lengd * 0.9; $max_lengd = $lengd * 1.1;
              $min_height = $height * 0.9; $max_height= $height * 1.1;
                 $min_width = $width * 0.9; $max_width= $width * 1.1;

$sql = "SELECT lengd, height, width FROM filters;

      WHERE $lengd BETWEEN :min_lengd AND :max_lengd

        AND $height BETWEEN :min_height AND :max_height

            AND $width BETWEEN :min_width AND :max_width

             LIMIT 2";

            $params = [
            'min_lengd' => $min_lengd,
               'max_lengd' => $max_lengd,
                  'min_height' => $min_height,
                   'max_height' => $max_height,
                      'min_width' => $min_width,
                        'max_width' => $max_width, ];

  $stmt = $conn->prepare($sql);  // LINE 92
  $stmt->execute($params);

?>
</code>```

答:
you must remove the ; in SELECT line:

```<code>$sql = "SELECT lengd, height, width FROM filters;
</code>```

into this:

```<code>$sql = "SELECT lengd, height, width FROM filters
</code>```

And remove the $ sign in select statement if this is a column in table:

```<code>$sql = "SELECT lengd, height, width FROM filters

      WHERE lengd BETWEEN :min_lengd AND :max_lengd

        AND height BETWEEN :min_height AND :max_height

            AND width BETWEEN :min_width AND :max_width

             LIMIT 2";
</code>```

Body:
I'm getting this error and i can't find whats wrong.

I've read through the other posts about this error but none of them seemed to help.

Fatal error: Call to a member function prepare() on null on line 92

        <?php

  include 'config.php';

   $lengd = $_POST["lengd"];
      $height = $_POST["height"];
       $width = $_POST["width"];

     $min_lengd = $lengd * 0.9; $max_lengd = $lengd * 1.1;
              $min_height = $height * 0.9; $max_height= $height * 1.1;
                 $min_width = $width * 0.9; $max_width= $width * 1.1;

$sql = "SELECT lengd, height, width FROM filters;

      WHERE $lengd BETWEEN :min_lengd AND :max_lengd

        AND $height BETWEEN :min_height AND :max_height

            AND $width BETWEEN :min_width AND :max_width

             LIMIT 2";

            $params = [
            'min_lengd' => $min_lengd,
               'max_lengd' => $max_lengd,
                  'min_height' => $min_height,
                   'max_height' => $max_height,
                      'min_width' => $min_width,
                        'max_width' => $max_width, ];

  $stmt = $conn->prepare($sql);  // LINE 92
  $stmt->execute($params);

?>

Body:
you must remove the ; in SELECT line:

$sql = "SELECT lengd, height, width FROM filters;

into this:

$sql = "SELECT lengd, height, width FROM filters

And remove the $ sign in select statement if this is a column in table:

$sql = "SELECT lengd, height, width FROM filters

      WHERE lengd BETWEEN :min_lengd AND :max_lengd

        AND height BETWEEN :min_height AND :max_height

            AND width BETWEEN :min_width AND :max_width

             LIMIT 2";


问:
Detect when font changes in EPUB
I am trying to use or create and event listener when the user changes the font size of the EPUB in an ereader with Javascript but I haven't find the way.

What I have tried without success:

A resize event listener.

A timing event that measures the font size.

A listener that measures the scale of the viewport.

In ebook-viewer (aka Calibre viewer) I can see in the inspector that every time I change the font size the console prints Viewport cfi: /2/4/2/2/1:1. I see that when 1:1 changes, it's some sort of scale in int numbers.

That is why I tried to detect the viewport scale with this or this.

So I suppose it is possible only because I can see trough the inspector of ebook-viewer...

All the tries didn't work on iOS either.

Update

I know about the epubReadingSystem and its limitations. Also that JS is optional for EPUB3. What I am trying to solve is that in spanish poetry when a verse is larger that the box's size, it has to be a break and the next line has to be right aligned with a bracket:

A short verse.
A very very long
         [verse.

I figured out how to make this change. The issue is that when the user changes the font, the calculation has to be done again. I tried to solve this by doing a fixed EPUB, but iBooks and ebook-viewer allow the font increase...

A working example: jsfiddle.net/dxr9azy7

答:
Thanks to this post we found a way to detect the font size change in an EPUB, at least in Calibre, ADE, and iBooks for Mac and iOS. It would be nice to try it in Readium and EPUBReader...

You have to create an iframe:

```<code>window.addEventListener("load", function () {
    iframe = document.createElement("iframe");
    iframe.id = "some_id";
    iframe.style.top = "0";
    iframe.style.left = "0";
    iframe.style.width = "100%";
    iframe.style.height = "5em";
    iframe.style.zIndex = "-1";
    iframe.style.visibility = "hidden";

    document.body.insertBefore(iframe, document.body.childNodes[0]);

    window.frames["some_id"].addEventListener("resize", function () {
        // Event when font size changes.
    });
});
</code>```

If you are looking for a working script for spanish poetry, see this. Download the sample: mobileread.com/forums/attachment.php?attachmentid=155891&d=1490939383.

Thanks!

Title: Detect when font changes in EPUB

Body:
Thanks to this post we found a way to detect the font size change in an EPUB, at least in Calibre, ADE, and iBooks for Mac and iOS. It would be nice to try it in Readium and EPUBReader...

You have to create an iframe:

window.addEventListener("load", function () {
    iframe = document.createElement("iframe");
    iframe.id = "some_id";
    iframe.style.top = "0";
    iframe.style.left = "0";
    iframe.style.width = "100%";
    iframe.style.height = "5em";
    iframe.style.zIndex = "-1";
    iframe.style.visibility = "hidden";

    document.body.insertBefore(iframe, document.body.childNodes[0]);

    window.frames["some_id"].addEventListener("resize", function () {
        // Event when font size changes.
    });
});

If you are looking for a working script for spanish poetry, see this. Download the sample: mobileread.com/forums/attachment.php?attachmentid=155891&d=1490939383.

Thanks!


问:
How to return the value of SELECT COUNT in C
Well I was wondering if it is possible to use the result of count counts in a printf.

I have a code that does the count in mysql.

```<code>void count_sql(void) {

    if (SQL_ENTER == SQL_ROWS(mysql, "SELECT COUNT(*) FROM `login_client` WHERE `ID` < DATE(NOW() + INTERVAL 1 DAY)"))
        sqldebug(mysql);

    printf("Counted users\n");
    return;
}
</code>```

I wanted to return the count value by leaving the message as below for example:

printf("150 users were found\n");

答:
I was unable to find a data type similar to SQL_ENTER so I'm not sure if this is a variable or not in your code, here is the documentation I was looking at

26.8.7 C API Function Descriptions
below I included my int main but you should be able to use just the void count_sql, also worth noting I passed the MYSQL object to the fucntion this could have also been part of your issue.

also worth noting I built and tested this code on a windows environment using MinGW compiler and the mysql-connector-c-6.1.9-win32 library so it might not work in your environment

```<code>#include<winsock2.h>
#include<stdio.h>
#include<mysql.h>

int main(){
    /* initialize MYSQL connection */
    MYSQL *mysql = mysql_init(NULL);

    if(mysql == NULL){
        sqldebug(mysql);
    }

    /* pass credentials here */
    if(mysql_real_connect(mysql, "localhost", "user", "password", "database", 0, NULL, 0) == NULL){
        sqldebug(mysql);
    }

    /* run query and count results */
    count_sql(mysql);

    /*close connection and exit void*/
    mysql_close(mysql);
    exit(0);
}

void sqldebug(MYSQL *mysql)
{
  fprintf(stderr, "%s\n", mysql_error(mysql));
  mysql_close(mysql);
  exit(1);
}

void count_sql(MYSQL *mysql){
    /* run query */
    if(mysql_query(mysql, "SELECT COUNT(*) FROM `login_client` WHERE `ID` < DATE(NOW() + INTERVAL 1 DAY)")){
        sqldebug(mysql);
    }

    /* store the results */
    MYSQL_RES *result = mysql_store_result(mysql);

    if(result == NULL){
        finish_with_error(mysql);
    }

    /* check the result has records ** don't really need this part */
    int num_fields = mysql_num_fields(result);
    if(num_fields<1){
        printf("no fields returned");
        exit(1);
    }

    /* row record */
    MYSQL_ROW row;

    if(row=mysql_fetch_row(result)){
       printf("Counted users %s\n", row[0]);
    }
    return;
}
</code>```

Body:
Well I was wondering if it is possible to use the result of count counts in a printf.

I have a code that does the count in mysql.

void count_sql(void) {

    if (SQL_ENTER == SQL_ROWS(mysql, "SELECT COUNT(*) FROM `login_client` WHERE `ID` < DATE(NOW() + INTERVAL 1 DAY)"))
        sqldebug(mysql);

    printf("Counted users\n");
    return;
}

I wanted to return the count value by leaving the message as below for example:

printf("150 users were found\n");

Body:
I was unable to find a data type similar to SQL_ENTER so I'm not sure if this is a variable or not in your code, here is the documentation I was looking at

26.8.7 C API Function Descriptions
below I included my int main but you should be able to use just the void count_sql, also worth noting I passed the MYSQL object to the fucntion this could have also been part of your issue.

also worth noting I built and tested this code on a windows environment using MinGW compiler and the mysql-connector-c-6.1.9-win32 library so it might not work in your environment

#include<winsock2.h>
#include<stdio.h>
#include<mysql.h>

int main(){
    /* initialize MYSQL connection */
    MYSQL *mysql = mysql_init(NULL);

    if(mysql == NULL){
        sqldebug(mysql);
    }

    /* pass credentials here */
    if(mysql_real_connect(mysql, "localhost", "user", "password", "database", 0, NULL, 0) == NULL){
        sqldebug(mysql);
    }

    /* run query and count results */
    count_sql(mysql);

    /*close connection and exit void*/
    mysql_close(mysql);
    exit(0);
}

void sqldebug(MYSQL *mysql)
{
  fprintf(stderr, "%s\n", mysql_error(mysql));
  mysql_close(mysql);
  exit(1);
}

void count_sql(MYSQL *mysql){
    /* run query */
    if(mysql_query(mysql, "SELECT COUNT(*) FROM `login_client` WHERE `ID` < DATE(NOW() + INTERVAL 1 DAY)")){
        sqldebug(mysql);
    }

    /* store the results */
    MYSQL_RES *result = mysql_store_result(mysql);

    if(result == NULL){
        finish_with_error(mysql);
    }

    /* check the result has records ** don't really need this part */
    int num_fields = mysql_num_fields(result);
    if(num_fields<1){
        printf("no fields returned");
        exit(1);
    }

    /* row record */
    MYSQL_ROW row;

    if(row=mysql_fetch_row(result)){
       printf("Counted users %s\n", row[0]);
    }
    return;
}


问:
How can I replace %20 with - from url using php?
code:

```<code> <?php
    $query = "select * from latest_news limit 0,10";
    $fet = mysqli_query($link,$query);
    while ($fetch = mysqli_fetch_array($fet))
    {
 ?>
 <p id="news-h3"><?php echo $fetch['news_title']; ?>...<a href="news-details.php?news_tags=<?php echo $fetch['news_tags']; ?>" style="color:red;">[Read More]</a></p>
 <?php
     }
 ?>
</code>```

When I click on link i.e.

```<code><a href="news-details.php?news_tags=<?php echo $fetch['news_tags']; ?>" style="color:red;">[Read More]</a>
</code>```

It show

```<code>best%20engineering%20college%20in%20India
</code>```

Here, I want to replace %20 with (-) from url and get result like

```<code>best-engineering-college-in-India
</code>```

how can I fix this problem please help.

Thank you

答:
You should use str_replace() here:</p>

```<code>echo str_replace('%20', '-', $input); // best-engineering-college-in-India
</code>```

Body:
code:

 <?php
    $query = "select * from latest_news limit 0,10";
    $fet = mysqli_query($link,$query);
    while ($fetch = mysqli_fetch_array($fet))
    {
 ?>

<?php echo $fetch['news_title']; ?>...<a href="news-details.php?news_tags=<?php echo $fetch['news_tags']; ?>" style="color:red;">[Read More]

 <?php
     }
 ?>

When I click on link i.e.

<a href="news-details.php?news_tags=<?php echo $fetch['news_tags']; ?>" style="color:red;">[Read More]

It show

best%20engineering%20college%20in%20India

Here, I want to replace %20 with (-) from url and get result like

best-engineering-college-in-India

how can I fix this problem please help.

Thank you

Body:
You should use str_replace() here:

echo str_replace('%20', '-', $input); // best-engineering-college-in-India


问:
How to change the text on the action bar
Currently it just displays the name of the application and I want it to display something custom and be different for each screen in my app.

For example: my home screen could say 'page1' in the action bar while another activity that the app switches to could have 'page2' in that screens action bar.

答:
The Easiest way to change the action bar name is to go to the AndroidManifest.xml and type this code.</p>

```<code><activity android:name=".MainActivity"
    android:label="Your Label> </activity>
</code>```

Body:
The Easiest way to change the action bar name is to go to the AndroidManifest.xml and type this code.

<activity android:name=".MainActivity"
    android:label="Your Label> </activity>


问:
how to save all data of listview in text format on button click
```<code><TextView
    android:id="@+id/tv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    android:textColor="#000000"
    android:textSize="20sp"/>
</code>```

<p>i am new in android programming please guys help me.That how to save all data of Listview in text format on button click in our mobile </p>

```<code> static String[] city = {"Indore","Bhopal","Mumbai","Pune","Delhi","Kolkata",
        "Hyderabad","Banglore","Chennai","Amritsar","jhalandhar"};

Button button;
ListView listView;

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

    button = (Button) findViewById(R.id.button);
    listView = (ListView) findViewById(R.id.lv);

    MyAdapter myadapter = new MyAdapter(getApplicationContext(),city);
    listView.setAdapter(myadapter);
</code>```

答:
hope this helps.</p>

```<code>SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
    for (int i = 0 ; i < items.size(); i++) {
        ListViewItem item = items.get(i);
        edit.putString(Integer.toString(i), item.elementOne + "," + item.elementTwo + "," + item.elementthree);
    }
    edit.commit();
</code>```

Body:
<TextView
    android:id="@+id/tv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    android:textColor="#000000"
    android:textSize="20sp"/>

i am new in android programming please guys help me.That how to save all data of Listview in text format on button click in our mobile

 static String[] city = {"Indore","Bhopal","Mumbai","Pune","Delhi","Kolkata",
        "Hyderabad","Banglore","Chennai","Amritsar","jhalandhar"};

Button button;
ListView listView;

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

    button = (Button) findViewById(R.id.button);
    listView = (ListView) findViewById(R.id.lv);

    MyAdapter myadapter = new MyAdapter(getApplicationContext(),city);
    listView.setAdapter(myadapter);

Body:
hope this helps.

SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
    for (int i = 0 ; i < items.size(); i++) {
        ListViewItem item = items.get(i);
        edit.putString(Integer.toString(i), item.elementOne + "," + item.elementTwo + "," + item.elementthree);
    }
    edit.commit();


答: There'a a spelling mistake in your ID attribute. Replace 'selectElemet' to 'selectElement'. Hope that helps.</p>

Title: jQuery trigger("click") not working

Body:
Can someone please explain what is wrong with the pasted code. It shows alert on hover but does not perform click event like I expect, and click does not work on either  tag or <select> tag. My purpose is to expand the select element on hover by triggering click event

<!DOCTYPE html>

    click

    <select name="cars" id="selectElemet">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>


问:
Running an executable binary made w/ JET Excelsior in Docker
I'm starting out with Docker, trying to add my application into it, to run. The application is Java-based compiled using Jet Excelsior.

I use the following simple docker file for building.

```<code>#Dockerfile

FROM alpine:latest
COPY ["/", "/sandbox"]
WORKDIR /sandbox
ENTRYPOINT ["myapp"]
CMD ["-XX:+PrintFlagsFinal","-XX:+PrintGCDetails"]
</code>```

I build with the standard docker build -t sandbox .

I confirm that the folder structure and all files are properly transferred. I do this by docker run sandbox ls *. But when I do docker run sandbox I get the error:

container_linux.go:247: starting container process caused "exec: \"myapp\": executable file not found in $PATH"

I've tried not using the exec form i.e ENTRYPOINT / CMD myapp; even ENTRYPOINT / CMD ./myapp, to which I get:

/bin/sh: myapp: not found

Can anyone help?

答: I apparently didn't look hard enough, before posting this question. It turns out there is a specific solution to this question in JET Excelsior's knowledge base.</p>

Body:
I'm starting out with Docker, trying to add my application into it, to run. The application is Java-based compiled using Jet Excelsior.

I use the following simple docker file for building.

#Dockerfile

FROM alpine:latest
COPY ["/", "/sandbox"]
WORKDIR /sandbox
ENTRYPOINT ["myapp"]
CMD ["-XX:+PrintFlagsFinal","-XX:+PrintGCDetails"]

I build with the standard docker build -t sandbox .

I confirm that the folder structure and all files are properly transferred. I do this by docker run sandbox ls *. But when I do docker run sandbox I get the error:

container_linux.go:247: starting container process caused "exec: \"myapp\": executable file not found in $PATH"

I've tried not using the exec form i.e ENTRYPOINT / CMD myapp; even ENTRYPOINT / CMD ./myapp, to which I get:

/bin/sh: myapp: not found

Can anyone help?


问:
Is there an easy way to add a border to the top and bottom of an Android View?
I have a TextView and I'd like to add a black border along its top and bottom borders.  I tried adding android:drawableTop and android:drawableBottom to the TextView, but that only caused the entire view to become black.

```<code><TextView
    android:background="@android:color/green"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawableTop="@android:color/black"
    android:drawableBottom="@android:color/black"
    android:text="la la la" />
</code>```

Is there a way to easily add a top and bottom border to a View (in particular, a TextView) in Android?

答:
In android 2.2 you could do the following.

Create an xml drawable such as /res/drawable/textlines.xml and assign this as a TextView's background property.

```<code><TextView
android:text="My text with lines above and below"
android:background="@drawable/textlines"
/>
</code>```

/res/drawable/textlines.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
      <shape
        android:shape="rectangle">
            <stroke android:width="1dp" android:color="#FF000000" />
            <solid android:color="#FFDDDDDD" />

        </shape>
   </item>

   <item android:top="1dp" android:bottom="1dp">
      <shape
        android:shape="rectangle">
            <stroke android:width="1dp" android:color="#FFDDDDDD" />
            <solid android:color="#00000000" />
        </shape>
   </item>

</layer-list>
</code>```

The down side to this is that you have to specify an opaque background colour, as transparencies won't work. (At least i thought they did but i was mistaken). In the above example you can see that the solid colour of the first shape #FFdddddd is copied in the 2nd shapes stroke colour.

Body:
I have a TextView and I'd like to add a black border along its top and bottom borders.  I tried adding android:drawableTop and android:drawableBottom to the TextView, but that only caused the entire view to become black.

<TextView
    android:background="@android:color/green"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawableTop="@android:color/black"
    android:drawableBottom="@android:color/black"
    android:text="la la la" />

Is there a way to easily add a top and bottom border to a View (in particular, a TextView) in Android?

Body:
In android 2.2 you could do the following.

Create an xml drawable such as /res/drawable/textlines.xml and assign this as a TextView's background property.

<TextView
android:text="My text with lines above and below"
android:background="@drawable/textlines"
/>

/res/drawable/textlines.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
      <shape
        android:shape="rectangle">
            <stroke android:width="1dp" android:color="#FF000000" />
            <solid android:color="#FFDDDDDD" />

        </shape>
   </item>

   <item android:top="1dp" android:bottom="1dp">
      <shape
        android:shape="rectangle">
            <stroke android:width="1dp" android:color="#FFDDDDDD" />
            <solid android:color="#00000000" />
        </shape>
   </item>

</layer-list>

The down side to this is that you have to specify an opaque background colour, as transparencies won't work. (At least i thought they did but i was mistaken). In the above example you can see that the solid colour of the first shape #FFdddddd is copied in the 2nd shapes stroke colour.


问:
iterating through files with carriage returns
Is there a way to iterate through a text file using the syntax,

```<code>with open(filename,'r') as f:
  for line in f:
    print f
</code>```

if the file only contains carriage returns and no newline characters?

So far all I can do is

```<code>with open(filename,'r') as f:
  for line in f.read().split('\r'):
    print f
</code>```

But the files are sometimes huge. I don't want to modify the file using dos2unix because another software program needs it in the original format.

答: You can use open(filename, 'rU').

Body:
Is there a way to iterate through a text file using the syntax,

with open(filename,'r') as f:
  for line in f:
    print f

if the file only contains carriage returns and no newline characters?

So far all I can do is

with open(filename,'r') as f:
  for line in f.read().split('\r'):
    print f

But the files are sometimes huge. I don't want to modify the file using dos2unix because another software program needs it in the original format.

Body: You can use open(filename, 'rU').


问:
why use of deleted rvalue reference constructor function?
This is a very simple example with class A and B.
I want allow only deep copy, so I disabled the rvalue reference constructor.

```<code>#include <iostream>

class B;

class A {
public:
    A();
    ~A();
    A(const A & other);
    A& operator=(const A & other);
    A(A && ) = delete;
    A& operator=(A && ) = delete;
    B toB() const;

private:
    int a_;
};

class B {
public:
    B();
    ~B();
    B(const B & other);
    B& operator=(const B & other);
    B(B && ) = delete;
    B& operator=(B && ) = delete;
    A toA() const;

private:
    int b_;
};

A::A()
{
}

A::~A()
{
}
A::A(const A & other)
        : a_(other.a_)
{
}
A& A::operator=(const A & other)
{
    a_ = other.a_;
    return *this;
}

B A::toB() const
{
    return B();
}

B::B()
{
}
B::~B()
{
}
B::B(const B & other)
        : b_(other.b_)
{
}
B& B::operator=(const B & other)
{
    b_ = other.b_;
    return *this;
}

A B::toA() const
{
    return A();
}

int main()
{
    A a();
    B b();

    return 0;
}
</code>```

the gcc compiler report bugs like this:

```<code>In member function 'B A::toB() const':
error: use of deleted function 'B::B(B&&)'
     return B();
              ^
note: declared here
     B(B && ) = delete;
</code>```

I'm wandering why it use B(B && ) function, not the B(const B &) function instead.

答:
Move Constructor would be called whenever a nameless object is created.

In B A::toB() const function there is a statement return B(); which creates a nameless object to be returned from the function. For creating a nameless object move constructor is required which is deleted.

Body:
This is a very simple example with class A and B.
I want allow only deep copy, so I disabled the rvalue reference constructor.

#include <iostream>

class B;

class A {
public:
    A();
    ~A();
    A(const A & other);
    A& operator=(const A & other);
    A(A && ) = delete;
    A& operator=(A && ) = delete;
    B toB() const;

private:
    int a_;
};

class B {
public:
    B();
    ~B();
    B(const B & other);
    B& operator=(const B & other);
    B(B && ) = delete;
    B& operator=(B && ) = delete;
    A toA() const;

private:
    int b_;
};

A::A()
{
}

A::~A()
{
}
A::A(const A & other)
        : a_(other.a_)
{
}
A& A::operator=(const A & other)
{
    a_ = other.a_;
    return *this;
}

B A::toB() const
{
    return B();
}

B::B()
{
}
B::~B()
{
}
B::B(const B & other)
        : b_(other.b_)
{
}
B& B::operator=(const B & other)
{
    b_ = other.b_;
    return *this;
}

A B::toA() const
{
    return A();
}

int main()
{
    A a();
    B b();

    return 0;
}

the gcc compiler report bugs like this:

In member function 'B A::toB() const':
error: use of deleted function 'B::B(B&&)'
     return B();
              ^
note: declared here
     B(B && ) = delete;

I'm wandering why it use B(B && ) function, not the B(const B &) function instead.


答:
Your appointments is JSONArray

JSON

{"appointments":[{"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"}]}

```<code> JSONObject reader = new JSONObject(all_data);
 JSONArray jsonArray = reader.getJSONArray("appointments");
  ......//Do your work//..........
</code>```

Title: Android JSON parsing error cannot be converted to JSONArray

Body:
I'm fairly new to Android dev, and am trying to write a programme to parse some JSON from a website and output it in a ListView. However, when I run my programme, I get the error: (There are more then 7 row same as this error)

03-31 05:25:14.296 3196-3196/nazilli.tenispark E/FAILED: Json parsing
error: Value
{"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"}
of type org.json.JSONObject cannot be converted to JSONArray

03-31 05:25:14.297 3196-3196/nazilli.tenispark E/FAILED: Json parsing error:
Value
{"0":"3","id":"3","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-08","date":"2017-04-08","4":"20","hour":"20"}
of type org.json.JSONObject cannot be converted to JSONArray

The JSON I'm trying to parse is:

{"appointments":[{"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"},{"0":"3","id":"3","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-08","date":"2017-04-08","4":"20","hour":"20"},{"0":"4","id":"4","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-15","date":"2017-04-15","4":"20","hour":"20"},{"0":"5","id":"5","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-22","date":"2017-04-22","4":"20","hour":"20"},{"0":"6","id":"6","1":"0","cid":"0","2":"1","uid":"1","3":"2017-03-24","date":"2017-03-24","4":"17","hour":"17"},{"0":"7","id":"7","1":"0","cid":"0","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"17","hour":"17"},{"0":"8","id":"8","1":"1","cid":"1","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"16","hour":"16"},{"0":"9","id":"9","1":"2","cid":"2","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"15","hour":"15"},{"0":"10","id":"10","1":"3","cid":"3","2":"1","uid":"1","3":"2017-03-26","date":"2017-03-26","4":"13","hour":"13"}]}

this my listview custom row java

public class adapter_appointment extends ArrayAdapter<String> {
    public adapter_appointment(Context context, String[] data){
        super(context, R.layout.row_layout, data);
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View customView = inflater.inflate(R.layout.row_layout, parent, false);
        String all_data = getItem(position);
        TextView title = (TextView) customView.findViewById(R.id.title);
        //title.setText(all_data.toString());
        try {
            JSONArray array = new JSONArray(all_data);
            JSONObject obj = array.getJSONObject(0);
            Log.d("SUCCESS", "JSON Object: " + obj.toString());
            if (obj.has("date") && !obj.isNull("date")) {
                title.setText(obj.getString("date").toString());
                Log.d("SUCCESS", "Date: " + obj.getString("date").toString());
            } else {
                // Do something
            }
        } catch (Exception e) {
            Log.e("FAILED", "Json parsing error: " + e.getMessage());
        }
        return customView;
    }
}

This is json.java

public class my_appointments extends AppCompatActivity {
    ListView lv;
    InputStream is = null;
    String line = null;
    String result = null;
    String[] data;

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

        lv=(ListView) findViewById(R.id.my_appointments);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
        //Run
        getData();
        ArrayAdapter adapter = new adapter_appointment(this, data);
        lv.setAdapter(adapter);
    }

    private void getData()
    {
        try {
            URL url = new URL("MY URL");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            is=new BufferedInputStream(con.getInputStream());
            //
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            while((line=br.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
            //
            JSONObject jo = new JSONObject(result);
            JSONArray ja = jo.getJSONArray("appointments");
            data = new String[ja.length()];
            for(int i=0;i<ja.length();i++)
            {
                jo=ja.getJSONObject(i);
                data[i]=jo.toString();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

If I don't parse:

Body:
Your appointments is JSONArray

JSON

{"appointments":[{"0":"2","id":"2","1":"0","cid":"0","2":"1","uid":"1","3":"2017-04-01","date":"2017-04-01","4":"20","hour":"20"}]}

 JSONObject reader = new JSONObject(all_data);
 JSONArray jsonArray = reader.getJSONArray("appointments");
  ......//Do your work//..........