问:
Start new Activity with onClick() in RecyclerView
I want to go into a new Activity with the onClick() method but my code is not working. Can you please offer some advice. I have some issues with the recyclerView, since it's fairly new for me. Thank you

public class FragmentOne extends Fragment {

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            RecyclerView recyclerView = (RecyclerView) inflater.inflate(
                    R.layout.recycleview, container, false);
            ContentAdapter adapter = new ContentAdapter();
            recyclerView.setAdapter(adapter);

            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            return recyclerView;
        }

        public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {
            private static final int LENGTH = 50;

            public ContentAdapter() {
            }

            public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

                public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
                    super(inflater.inflate(R.layout.fragment_channel, parent, false));
                }

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ChannelDetailActivity.class);
                    startActivity(intent);
                }
            }

            @Override
            public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

                ViewHolder viewHolder = new ViewHolder (LayoutInflater.from(parent.getContext()), parent);
                return viewHolder;

            }

            @Override
            public void onBindViewHolder(ViewHolder holder, int position) {
            }

            @Override
            public int getItemCount() {
                return LENGTH;
            }
        }

    }```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:paddingBottom="16dp"
    android:paddingTop="16dp"
    android:scrollbars="vertical"
    android:elevation="5dp"
    android:fadingEdgeLength="@dimen/cardview_compat_inset_shadow"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" /></code>```

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="360dp"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:layout_marginBottom="1dp"
    android:elevation="2dp"
    android:layout_gravity="center_horizontal"
    android:background="#FFFF">

    <ImageView
        android:id="@+id/user_image"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:scaleType="centerCrop"
        android:src="@drawable/userone" />

    <TextView
        android:id="@+id/user_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_toRightOf="@+id/user_image"
        android:text="Chuck Reich"
        android:paddingBottom="3dp"
        android:textAppearance="?attr/textAppearanceListItem"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/user_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/user_name"
        android:layout_marginLeft="16dp"
        android:layout_toRightOf="@+id/user_image"
        android:textColor="#a9a9a9"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="Horizon Media Studios"
        android:textAppearance="?attr/textAppearanceListItem"
        android:paddingBottom="2dp"
        android:textSize="14sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="3928"
        android:paddingRight="18dp"
        android:id="@+id/textView2"
        android:textColor="#a9a9a9"
        android:textSize="12sp"
        android:layout_below="@+id/user_desc"
        android:layout_alignStart="@+id/user_desc" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="3402"
        android:id="@+id/textView3"
        android:textColor="#a9a9a9"
        android:textSize="12sp"
        android:layout_below="@+id/user_desc"
        android:layout_toEndOf="@+id/textView2" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="2354"
        android:paddingLeft="20dp"
        android:id="@+id/textView4"
        android:textColor="#a9a9a9"
        android:textSize="12sp"
        android:layout_below="@+id/user_desc"
        android:layout_centerHorizontal="true" />

</RelativeLayout>```

答:
This can be very useful for you to get to other Activities

first the recycler view adapter:

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

final private ListItemClickListener mOnClickListener;
String[] mStrings;

public MainMenuRVAdapter(String[] tvStrings, ListItemClickListener listener) {
    mStrings = tvStrings;
    mOnClickListener = listener;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.customRow, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.bind(position);
}

@Override
public int getItemCount() {
    return mStrings.length;
}

public interface ListItemClickListener {
    void onListItemClick(int clickedItemIndex);
}

class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView RowTV;

    public ViewHolder (View itemView) {
        super(itemView);
        RowTV = (TextView) itemView.findViewById(R.id.RowTextView);
        itemView.setOnClickListener(this);
    }

    void bind(int listIndex) {
        RowTV.setText(mListStrings[listIndex]);
    }

    @Override
    public void onClick(View v) {
        int clickedPosition = getAdapterPosition();
        mOnClickListener.onListItemClick(clickedPosition);
    }
}
}
</code>```

Then the MainActivity:

```<code>public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, MainMenuRVAdapter.ListItemClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String[] stringsArray = getResources().getStringArray(R.array.mainStrings);

    RecyclerView rv = (RecyclerView) findViewById(R.id.RV);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    rv.setLayoutManager(layoutManager);
      rv.setAdapter(new MainMenuRVAdapter(stringsArray, this));
}
  @Override
public void onListItemClick(int clickedItemIndex) {
Intent mIntent;
switch (clickedItemIndex) {
 case 0: //first item in Recycler view
            mIntent = new Intent (MainActivity.this, x.class);
            startActivity(mIntent);
            break;
case 1: //second item in Recycler view
            mIntent = new Intent (MainActivity.this, y.class);
            startActivity(mIntent);
            break;
case 2: //third item in Recycler view
            mIntent = new Intent (MainActivity.this, z.class);
            startActivity(mIntent);
            break;
}
</code>```

you can use this method and add as many cases to the switch().

Hope I Helped.

Body:
I want to go into a new Activity with the onClick() method but my code is not working. Can you please offer some advice. I have some issues with the recyclerView, since it's fairly new for me. Thank you

public class FragmentOne extends Fragment {

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            RecyclerView recyclerView = (RecyclerView) inflater.inflate(
                    R.layout.recycleview, container, false);
            ContentAdapter adapter = new ContentAdapter();
            recyclerView.setAdapter(adapter);

            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            return recyclerView;
        }

        public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {
            private static final int LENGTH = 50;

            public ContentAdapter() {
            }

            public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

                public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
                    super(inflater.inflate(R.layout.fragment_channel, parent, false));
                }

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), ChannelDetailActivity.class);
                    startActivity(intent);
                }
            }

            @Override
            public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

                ViewHolder viewHolder = new ViewHolder (LayoutInflater.from(parent.getContext()), parent);
                return viewHolder;

            }

            @Override
            public void onBindViewHolder(ViewHolder holder, int position) {
            }

            @Override
            public int getItemCount() {
                return LENGTH;
            }
        }

    }

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/my_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:paddingBottom="16dp"
    android:paddingTop="16dp"
    android:scrollbars="vertical"
    android:elevation="5dp"
    android:fadingEdgeLength="@dimen/cardview_compat_inset_shadow"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="360dp"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:layout_marginBottom="1dp"
    android:elevation="2dp"
    android:layout_gravity="center_horizontal"
    android:background="#FFFF">

    <ImageView
        android:id="@+id/user_image"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:scaleType="centerCrop"
        android:src="@drawable/userone" />

    <TextView
        android:id="@+id/user_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_toRightOf="@+id/user_image"
        android:text="Chuck Reich"
        android:paddingBottom="3dp"
        android:textAppearance="?attr/textAppearanceListItem"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/user_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/user_name"
        android:layout_marginLeft="16dp"
        android:layout_toRightOf="@+id/user_image"
        android:textColor="#a9a9a9"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="Horizon Media Studios"
        android:textAppearance="?attr/textAppearanceListItem"
        android:paddingBottom="2dp"
        android:textSize="14sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="3928"
        android:paddingRight="18dp"
        android:id="@+id/textView2"
        android:textColor="#a9a9a9"
        android:textSize="12sp"
        android:layout_below="@+id/user_desc"
        android:layout_alignStart="@+id/user_desc" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="3402"
        android:id="@+id/textView3"
        android:textColor="#a9a9a9"
        android:textSize="12sp"
        android:layout_below="@+id/user_desc"
        android:layout_toEndOf="@+id/textView2" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="2354"
        android:paddingLeft="20dp"
        android:id="@+id/textView4"
        android:textColor="#a9a9a9"
        android:textSize="12sp"
        android:layout_below="@+id/user_desc"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Body:
This can be very useful for you to get to other Activities

first the recycler view adapter:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

final private ListItemClickListener mOnClickListener;
String[] mStrings;

public MainMenuRVAdapter(String[] tvStrings, ListItemClickListener listener) {
    mStrings = tvStrings;
    mOnClickListener = listener;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.customRow, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    holder.bind(position);
}

@Override
public int getItemCount() {
    return mStrings.length;
}

public interface ListItemClickListener {
    void onListItemClick(int clickedItemIndex);
}

class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView RowTV;

    public ViewHolder (View itemView) {
        super(itemView);
        RowTV = (TextView) itemView.findViewById(R.id.RowTextView);
        itemView.setOnClickListener(this);
    }

    void bind(int listIndex) {
        RowTV.setText(mListStrings[listIndex]);
    }

    @Override
    public void onClick(View v) {
        int clickedPosition = getAdapterPosition();
        mOnClickListener.onListItemClick(clickedPosition);
    }
}
}

Then the MainActivity:

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, MainMenuRVAdapter.ListItemClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String[] stringsArray = getResources().getStringArray(R.array.mainStrings);

    RecyclerView rv = (RecyclerView) findViewById(R.id.RV);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    rv.setLayoutManager(layoutManager);
      rv.setAdapter(new MainMenuRVAdapter(stringsArray, this));
}
  @Override
public void onListItemClick(int clickedItemIndex) {
Intent mIntent;
switch (clickedItemIndex) {
 case 0: //first item in Recycler view
            mIntent = new Intent (MainActivity.this, x.class);
            startActivity(mIntent);
            break;
case 1: //second item in Recycler view
            mIntent = new Intent (MainActivity.this, y.class);
            startActivity(mIntent);
            break;
case 2: //third item in Recycler view
            mIntent = new Intent (MainActivity.this, z.class);
            startActivity(mIntent);
            break;
}

you can use this method and add as many cases to the switch().

Hope I Helped.


来源: stackexchange

问:
Cannot implicitly convert type 'double' to 'long'
In this code i got the above error in lines i commented.

```<code>public double bigzarb(long u, long v)
{
    double n;
    long x;
    long y;
    long w;
    long z;
    string[] i = textBox7.Text.Split(',');
    long[] nums = new long[i.Length];
    for (int counter = 0; counter < i.Length; counter++)
    {
        nums[counter] = Convert.ToInt32(i[counter]);
    }

    u = nums[0];
    int firstdigits = Convert.ToInt32(Math.Floor(Math.Log10(u) + 1));
    v = nums[1];
    int seconddigits = Convert.ToInt32(Math.Floor(Math.Log10(v) + 1));
    if (firstdigits >= seconddigits)
    {
        n = firstdigits;

    }
    else
    {
        n = seconddigits;
    }
    if (u == 0 || v == 0)
    {
        MessageBox.Show("the Multiply is 0");
    }

    int intn = Convert.ToInt32(n);
    if (intn <= 3)
    {
        long uv = u * v;
        string struv = uv.ToString();
        MessageBox.Show(struv);
        return uv;
    }
    else
    {
        int m =Convert.ToInt32(Math.Floor(n / 2));

        x = u % Math.Pow(10, m); // here
        y = u / Math.Pow(10, m); // here
        w = v % Math.Pow(10, m); // here
        z = v / Math.Pow(10, m); // here

        long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
        textBox1.Text = result.ToString();
        return result;
    }
}
</code>```

Whats is the problem? Thanks!

答:
The Math.Pow method returns a double, not a long so you will need to change your code to account for this:

```<code>x = (long)(u % Math.Pow(10, m));
</code>```

This code will cast the double result from Math.Pow and assign that value to x.  Keep in mind that you will lose all the precision providided by decimal (which is a floating-point type and can represent decimal values).  Casting to long will truncate everything after the decimal point.

ContentLicense: CC BY-SA 2.5

Body:
In this code i got the above error in lines i commented.

public double bigzarb(long u, long v)
{
    double n;
    long x;
    long y;
    long w;
    long z;
    string[] i = textBox7.Text.Split(',');
    long[] nums = new long[i.Length];
    for (int counter = 0; counter = seconddigits)
    {
        n = firstdigits;

    }
    else
    {
        n = seconddigits;
    }
    if (u == 0 || v == 0)
    {
        MessageBox.Show("the Multiply is 0");
    }

    int intn = Convert.ToInt32(n);
    if (intn <= 3)
    {
        long uv = u * v;
        string struv = uv.ToString();
        MessageBox.Show(struv);
        return uv;
    }
    else
    {
        int m =Convert.ToInt32(Math.Floor(n / 2));

        x = u % Math.Pow(10, m); // here
        y = u / Math.Pow(10, m); // here
        w = v % Math.Pow(10, m); // here
        z = v / Math.Pow(10, m); // here

        long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
        textBox1.Text = result.ToString();
        return result;
    }
}

Whats is the problem? Thanks!

Body:
The Math.Pow method returns a double, not a long so you will need to change your code to account for this:

x = (long)(u % Math.Pow(10, m));

This code will cast the double result from Math.Pow and assign that value to x.  Keep in mind that you will lose all the precision providided by decimal (which is a floating-point type and can represent decimal values).  Casting to long will truncate everything after the decimal point.


问:
Send 2 ajax POST request on single click

logout(){
  var destroySession='{"token":"'+this.token+'"}'
  console.log("Session Destroy"+destroySession)
  axios.post(eventBus.apiURL+'logout',{
    headers: {
      'Content-type': 'application/json',
    },
    body: destroySession,
  }).then(response=>{
    console.log("RESadas :: "+JSON.stringify(response.data))
    alert("Logout successfully..!")
    this.$router.push('/')
  },error=>{
    console.log(error);
    alert("Some Issue for LogOut at Server Side..!")

  });

  window.localStorage.removeItem('token')
  window.localStorage.removeItem('name')
  this.$router.push('/')
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button @click="logout">Logout</button></code>```

I have written a code for logout in vuejs, but at the time of click it sends two POST request and during session destroy problem occurs at server side.

答:
As per Mozilla Developer Network,

Preflight Requests

Unlike “simple requests” (discussed above), "preflighted" requests
first send an HTTP request by the OPTIONS method to the resource on
the other domain, in order to determine whether the actual request is
safe to send. Cross-site requests are preflighted like this since they
may have implications to user data.

In particular, a request is preflighted if any of the following
conditions is true:

If the request uses any of the following methods:

Put

DELETE

CONNECT

OPTIONS

TRACE

PATCH

Or if, apart from the headers set automatically by
the user agent (for example, Connection, User-Agent, or any of the
other header with a name defined in the Fetch spec as a “forbidden
header name”), the request includes any headers other than those which
the Fetch spec defines as being a “CORS-safelisted request-header”,
which are the following:

Accept

Accept-Language

Content-Language

Content-Type (but note the additional requirements below)

DPR

Downlink

Save-Data

Viewport-Width

Width

Or if the Content-Type header has a
value other than the following:

application/x-www-form-urlencoded

multipart/form-data

text/plain

Updated

Please read this answer on how to disable preflight requests: Link

ContentLicense: CC BY-SA 3.0

Body:
logout(){
  var destroySession='{"token":"'+this.token+'"}'
  console.log("Session Destroy"+destroySession)
  axios.post(eventBus.apiURL+'logout',{
    headers: {
      'Content-type': 'application/json',
    },
    body: destroySession,
  }).then(response=>{
    console.log("RESadas :: "+JSON.stringify(response.data))
    alert("Logout successfully..!")
    this.$router.push('/')
  },error=>{
    console.log(error);
    alert("Some Issue for LogOut at Server Side..!")

  });

  window.localStorage.removeItem('token')
  window.localStorage.removeItem('name')
  this.$router.push('/')
}

<button @click="logout">Logout</button>

I have written a code for logout in vuejs, but at the time of click it sends two POST request and during session destroy problem occurs at server side.


问:
java.lang.StringIndexOutOfBoundsException: String index out of range: -4
I have this simple Java code which gives the following error:
java.lang.StringIndexOutOfBoundsException: String index out of range: -4

the code is:

```<code>String date = "14000101";
String repayDate = date.substring(0, 4)+"-"+date.substring(5, 2)+"-"+date.substring(6, 2);
</code>```

the length of the string is 8 and yet it gives an error starting form the second part.

Any ideas?

Thanks!

答:
You are givin negative values:

[Api][1]
    [1]: http://www.w3api.com/wiki/Java:String.substring()

```<code>public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
</code>```

If you put beginIndex lower that endIndex, crash.

You should do something like this:

```<code>String repayDate = date.substring(0, 4)+"-"+date.substring(5, 7)+"-"+date.substring(6, 8);
</code>```

Try it!
Good luck.

Body:
I have this simple Java code which gives the following error:
java.lang.StringIndexOutOfBoundsException: String index out of range: -4

the code is:

String date = "14000101";
String repayDate = date.substring(0, 4)+"-"+date.substring(5, 2)+"-"+date.substring(6, 2);

the length of the string is 8 and yet it gives an error starting form the second part.

Any ideas?

Thanks!

Body:
You are givin negative values:

[Api][1]
    [1]: http://www.w3api.com/wiki/Java:String.substring()

public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)

If you put beginIndex lower that endIndex, crash.

You should do something like this:

String repayDate = date.substring(0, 4)+"-"+date.substring(5, 7)+"-"+date.substring(6, 8);

Try it!
Good luck.


问:
How do you get to the original message text in a Microsoft Bot Framework LuisIntent method
I'm trying to access the complete original text from within a method marked as a LuisIntent within a LuisDialog.

The documentation shows these methods as taking two arguments:

```<code>IDialogContext context, LuisResult result
</code>```

Neither of which publicly exposes the original text of the message. The context object does contain the message but in a private property (context.data.message.text) which is not accessible.

Is there a way to access this in the context, or can it be passed into the dialog constructor?

答:
You could do it like this by using the Query property of the LuisResult, </p>

```<code>[LuisIntent(intentName: "someIntentName")]
private async Task Eligibility(IDialogContext context, LuisResult result)
 {
   await context.PostAsync($"The original text is: {result.Query}");
   context.Wait(MessageReceivedAsync);
}
</code>```

Body:
I'm trying to access the complete original text from within a method marked as a LuisIntent within a LuisDialog.

The documentation shows these methods as taking two arguments:

IDialogContext context, LuisResult result

Neither of which publicly exposes the original text of the message. The context object does contain the message but in a private property (context.data.message.text) which is not accessible.

Is there a way to access this in the context, or can it be passed into the dialog constructor?

Body:
You could do it like this by using the Query property of the LuisResult,

[LuisIntent(intentName: "someIntentName")]
private async Task Eligibility(IDialogContext context, LuisResult result)
 {
   await context.PostAsync($"The original text is: {result.Query}");
   context.Wait(MessageReceivedAsync);
}


问:
How to eliminate inefficiency of django query in a loop?
How can the following code be made more efficient (e.g., how to replace the loop with a query)?

def get_question(datetime_now, questions_queryset, user):
    best_schedule = None
    best_question = None
    # HOW TO ELIMINATE THE FOLLOWING LOOP AND REPLACE WITH A QUERY?
    for question in questions_queryset:
        try:
            schedule = (Schedule.objects
                        .filter(question=question, user=user)
                        .latest(field_name='datetime_added')
        except ObjectDoesNotExist:
            schedule = None
        if (schedule and (schedule.date_show_next >= datetime_now) and
                ((not best_schedule) or
                 (schedule.datetime_added >= best_schedule.datetime_added))):
            best_schedule = schedule
            best_question = question

    return best_question
```

<p><br/>
<br/>
models.py</p>

<pre class="lang-python prettyprint-override"><code>from django.contrib.auth.models import User
from django.db.models import DateTimeField, ForeignKey, Model, TextField

class Question(Model):
    question = TextField()

class Schedule(Model):
    datetime_added = DateTimeField(auto_now_add=True)
    datetime_show_next = DateTimeField(null=True, default=None)
    question = ForeignKey(Question)
    user = ForeignKey(User, null=True)
</code>```

答:
```<code>    # Get the question ids
    question_ids = questions_queryset.values_list('id', flat=True)

    # get the beloved shedule
    schedule = Schedule.objects.filter(question__in=question_ids, user=user).latest(field_name='datetime_added')

    # You may opt for Schedule.objects.get() so as not to run into
    # the problem of multiple objects returned if all you need is strictly one schedule
</code>```

Body:
How can the following code be made more efficient (e.g., how to replace the loop with a query)?

def get_question(datetime_now, questions_queryset, user):
    best_schedule = None
    best_question = None
    # HOW TO ELIMINATE THE FOLLOWING LOOP AND REPLACE WITH A QUERY?
    for question in questions_queryset:
        try:
            schedule = (Schedule.objects
                        .filter(question=question, user=user)
                        .latest(field_name='datetime_added')
        except ObjectDoesNotExist:
            schedule = None
        if (schedule and (schedule.date_show_next >= datetime_now) and
                ((not best_schedule) or
                 (schedule.datetime_added >= best_schedule.datetime_added))):
            best_schedule = schedule
            best_question = question

    return best_question

models.py

from django.contrib.auth.models import User
from django.db.models import DateTimeField, ForeignKey, Model, TextField

class Question(Model):
    question = TextField()

class Schedule(Model):
    datetime_added = DateTimeField(auto_now_add=True)
    datetime_show_next = DateTimeField(null=True, default=None)
    question = ForeignKey(Question)
    user = ForeignKey(User, null=True)


问:
How to make an image not scroll?
I would like to know how to make an image not scroll with the rest of the page. However, I want the image to be a certain percentage of width, and the browser automatically figure out the heightto display the image, and the image height automatically configured also determines the parent div's height.

The following code allows me to position the image area nicely and size the actual image nicely:

.popPictureParent {
  position: relative;
  display: block;
  width: 100%;
  height: auto;
  overflow: hidden;
}

.popPicture {
  position: relative;
  display: block;
  width: 100%;
  height: auto;
}

.popPicture img {
  display: block;
  width: 100%;
  height: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="popPictureParent" id="picture1">
  <div class="popPicture">
    <img src="./files/painting_scene_smaller.png" alt="painting scene" />
  </div>
</div></code>```

How would I make the image not sccroll similar to this website: https://www.thediyjoint.com/ but have the image size and position the divs how I have it right now? I have other things on the website that it has to not intrude, this isn't the only thing, so.

I've tried the background image thing, using fixed, absolute, but neither work. I need the browser to do some math to make the image look nice based on a width percentage given.

When I try the background, there isn't an option to set the parent's div width to what the background needs. This is really convoluted to me. If more information is needed, please comment.

EDIT: the thing is, I need the image to serve as a width and height placeholder, so the parent div sizes to it. The background image doesn't give a placeholder. Also, I need the image to not show up outside of its parent div.

答:
Here is a solution:</p>

```<code>.popPicture{
     background-image: url('./files/painting_scene_smaller.png');
     background-repeat: no-repeat;
     background-attachment: fixed;
  }
</code>```

Title: How to make an image not scroll?

Body:
I would like to know how to make an image not scroll with the rest of the page. However, I want the image to be a certain percentage of width, and the browser automatically figure out the heightto display the image, and the image height automatically configured also determines the parent div's height.

The following code allows me to position the image area nicely and size the actual image nicely:

.popPictureParent {
  position: relative;
  display: block;
  width: 100%;
  height: auto;
  overflow: hidden;
}

.popPicture {
  position: relative;
  display: block;
  width: 100%;
  height: auto;
}

.popPicture img {
  display: block;
  width: 100%;
  height: auto;
}

How would I make the image not sccroll similar to this website: https://www.thediyjoint.com/ but have the image size and position the divs how I have it right now? I have other things on the website that it has to not intrude, this isn't the only thing, so.

I've tried the background image thing, using fixed, absolute, but neither work. I need the browser to do some math to make the image look nice based on a width percentage given.

When I try the background, there isn't an option to set the parent's div width to what the background needs. This is really convoluted to me. If more information is needed, please comment.

EDIT: the thing is, I need the image to serve as a width and height placeholder, so the parent div sizes to it. The background image doesn't give a placeholder. Also, I need the image to not show up outside of its parent div.

Body:
Here is a solution:

.popPicture{
     background-image: url('./files/painting_scene_smaller.png');
     background-repeat: no-repeat;
     background-attachment: fixed;
  }


问:
how to return as array in php function
im using laravel 5.4 and intervention plugin to upload images as ajax

i will upload images in php controller and it will return a response (file name).

and the returned variables from php is an array but in javascript it going to string and i cant iterate that

```<code> public function upload(Request $request)
{
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    return $answer;
}
</code>```

答:
Try this one,</p>

```<code>return response()->json($answer);
</code>```

Title: how to return as array in php function

Body:
im using laravel 5.4 and intervention plugin to upload images as ajax

i will upload images in php controller and it will return a response (file name).

and the returned variables from php is an array but in javascript it going to string and i cant iterate that

 public function upload(Request $request)
{
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    return $answer;
}

Body:
Try this one,

return response()->json($answer);


问:
list of entity, max date, max row_id
I have table in SQLServer.

I have list in c#, of entity id. (ex: 50, 70, 120 etc).

I need, for each entity, to take only the line with max date, and within that, the max of row_id.

for exmaple:

```<code>entity        date_value       row_id
50            30/06/2017       3000<br>
75            30/04/2017       2900<br>
50            30/06/2017       2890<br>
50            30/05/2017       2500<br>
50            30/06/2017       2100<br>
75            30/03/2017       2000<br>
</code>```

here I need to take only 2 rows:

```<code> 50            30/06/2017       3000<br>
 75            30/04/2017       2900<br>
</code>```

Not for all entities have rows in this table.

Can u help me with this?

Thank u.

答:
i think its help you

for ascending use   OrderBy(x => x.Col1).ThenBy(x => x.Col2)

Or For Descending use this

```<code> OrderByDescending (x => x.Col1).ThenByDescending (x => x.Col2)
</code>```

Title: list of entity, max date, max row_id

Body:
I have table in SQLServer.

I have list in c#, of entity id. (ex: 50, 70, 120 etc).

I need, for each entity, to take only the line with max date, and within that, the max of row_id.

for exmaple:

entity        date_value       row_id
50            30/06/2017       3000

75            30/04/2017       2900

50            30/06/2017       2890

50            30/05/2017       2500

50            30/06/2017       2100

75            30/03/2017       2000

here I need to take only 2 rows:

 50            30/06/2017       3000

 75            30/04/2017       2900

Not for all entities have rows in this table.

Can u help me with this?

Thank u.

Body:
i think its help you

for ascending use   OrderBy(x => x.Col1).ThenBy(x => x.Col2)

Or For Descending use this

 OrderByDescending (x => x.Col1).ThenByDescending (x => x.Col2)


问:
passing access and secret key aws cli
I am trying to embed access and secret key along with aws cli. e.g.

```<code>aws ec2 describe-instances --aws-access-key <access_key> --aws-secret-key <secret_key>
</code>```

Also tried with -o and -w options for access and secret key respectively. It says : Unknown option aws-access-key and aws-secret-key

答:
You can also use aws configure:</p>

```<code>$ aws configure
AWS Access Key ID [None]: xxxxxxxxxxxxxxxxxxxxxxxxx
AWS Secret Access Key [None]: xxxxxxxxxxxxxxxxxxxxxxxxx
</code>```

Title: passing access and secret key aws cli

Body:
I am trying to embed access and secret key along with aws cli. e.g.

aws ec2 describe-instances --aws-access-key <access_key> --aws-secret-key <secret_key>

Also tried with -o and -w options for access and secret key respectively. It says : Unknown option aws-access-key and aws-secret-key

Body:
You can also use aws configure:

$ aws configure
AWS Access Key ID [None]: xxxxxxxxxxxxxxxxxxxxxxxxx
AWS Secret Access Key [None]: xxxxxxxxxxxxxxxxxxxxxxxxx


答:
Try using json_encode().

This will solve your issue.

```<code>public function upload(Request $request)
{
    $answer=array();
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    echo json_encode($answer);
    die;
}
</code>```

Title: how to return as array in php function

Body:
Try using json_encode().

This will solve your issue.

public function upload(Request $request)
{
    $answer=array();
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    echo json_encode($answer);
    die;
}


问:
ReactJS: webpack Bundle.js not found(404)
I have set up a simple react project. I am using a webpack, I am geting an error GET http://localhost:3001/bundle.js 404 (Not Found) however bundle.js is generated in public folder

here is my package.json file

```<code>`{
  "name": "hello-react",
  "version": "1.0.0",
  "description": "simple react app",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "express": "^4.13.4",
    "react": "^0.14.7",
    "react-dom": "^0.14.7"
  },
  "devDependencies": {
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "webpack": "^1.12.13"
  }
}`
</code>```

here is server.js

```<code>var express = require('express');
// Create our app
var app = express();

app.use(express.static('public'));

app.listen(3001,function(){
  console.log('server is up on 3001');
});
</code>```

index.html

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

<head>
  <meta charset="UTF-8"/>
</head>

<body>
  <div id="app"></div>

  <script src="bundle.js"></script>
</body>

</html>
</code>```

my folder structure

答:
Thanks All of you guys.
I resolved issue, the problem was with runing a webpack command and then runing a server.</p>

Body:
I have set up a simple react project. I am using a webpack, I am geting an error GET http://localhost:3001/bundle.js 404 (Not Found) however bundle.js is generated in public folder

here is my package.json file

`{
  "name": "hello-react",
  "version": "1.0.0",
  "description": "simple react app",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "express": "^4.13.4",
    "react": "^0.14.7",
    "react-dom": "^0.14.7"
  },
  "devDependencies": {
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "webpack": "^1.12.13"
  }
}`

here is server.js

var express = require('express');
// Create our app
var app = express();

app.use(express.static('public'));

app.listen(3001,function(){
  console.log('server is up on 3001');
});

index.html

<!DOCTYPE html>

  <meta charset="UTF-8"/>

my folder structure


问:
KoaJS how to get files from multipart form data?
When I post a multipart form,

```<code><form name="acount_manage"  action="/update" enctype="multipart/form-data" method="post">
    <input type="file" name="file">
</form>
</code>```

It throws:

```<code>Error: Unsupported content-type: multipart/form-data
at Object.<anonymous> (e:\...\node_modules\co-body\lib\any.js:51:15)
</code>```

any.js:

/**
 * Module dependencies.
 */

var json = require('./json');
var form = require('./form');
var text = require('./text');

var JSON_CONTENT_TYPES = [
  'application/json',
  'application/json-patch+json',
  'application/vnd.api+json',
  'application/csp-report',
  'application/ld+json'

];

/**
 * Return a a thunk which parses form and json requests
 * depending on the Content-Type.
 *
 * Pass a node request or an object with `.req`,
 * such as a koa Context.
 *
 * @param {Request} req
 * @param {Options} [opts]
 * @return {Function}
 * @api public
 */

module.exports = function(req, opts){
  req = req.req || req;

  // parse Content-Type
  var type = req.headers['content-type'] || '';
  type = type.split(';')[0];

  // json
  if (~JSON_CONTENT_TYPES.indexOf(type)) return json(req, opts);

  // form
  if ('application/x-www-form-urlencoded' == type) return form(req, opts);

  // text
  if ('text/plain' == type) return text(req, opts);

  // invalid
  return function(done){
    var message = type ? 'Unsupported content-type: ' + type : 'Missing content-type';
    var err = new Error(message);
    err.status = 415;
    done(err);
  };
};```
</div>
</div>
</p>

<p>then,I changed the code </p>

```if ('application/x-www-form-urlencoded' == type) return form(req, opts);
```

<p>to </p>

```if ('application/x-www-form-urlencoded' == type || 'multipart/form-data'==type) return form(req, opts);
```

<p>no error ,but I can't get the request'data :</p>

```debug(this.request.files.file);
```

Result is undefined.

I am using KoaJs.

答:
Try koa-body library.

Example:

Put this middleware BEFORE the route middleware:

```<code>app.use(require('koa-body')({
    formidable:{
        uploadDir: __dirname + '/public/uploads', // directory where files will be uploaded
        keepExtensions: true // keep file extension on upload
    },
    multipart: true,
    urlencoded: true,
}));
</code>```

Then use in route middleware

```<code>async function(ctx, next) {
    ctx.request.body.files.file  // file is the input name
}
</code>```

This code is for KoaJs 2, but this library works with KoaJs 1 too.

Body:
When I post a multipart form,

<form name="acount_manage"  action="/update" enctype="multipart/form-data" method="post">
    <input type="file" name="file">
</form>

It throws:

Error: Unsupported content-type: multipart/form-data
at Object.<anonymous> (e:\...\node_modules\co-body\lib\any.js:51:15)

any.js:

/**
 * Module dependencies.
 */

var json = require('./json');
var form = require('./form');
var text = require('./text');

var JSON_CONTENT_TYPES = [
  'application/json',
  'application/json-patch+json',
  'application/vnd.api+json',
  'application/csp-report',
  'application/ld+json'

];

/**
 * Return a a thunk which parses form and json requests
 * depending on the Content-Type.
 *
 * Pass a node request or an object with `.req`,
 * such as a koa Context.
 *
 * @param {Request} req
 * @param {Options} [opts]
 * @return {Function}
 * @api public
 */

module.exports = function(req, opts){
  req = req.req || req;

  // parse Content-Type
  var type = req.headers['content-type'] || '';
  type = type.split(';')[0];

  // json
  if (~JSON_CONTENT_TYPES.indexOf(type)) return json(req, opts);

  // form
  if ('application/x-www-form-urlencoded' == type) return form(req, opts);

  // text
  if ('text/plain' == type) return text(req, opts);

  // invalid
  return function(done){
    var message = type ? 'Unsupported content-type: ' + type : 'Missing content-type';
    var err = new Error(message);
    err.status = 415;
    done(err);
  };
};

then,I changed the code

if ('application/x-www-form-urlencoded' == type) return form(req, opts);

to

if ('application/x-www-form-urlencoded' == type || 'multipart/form-data'==type) return form(req, opts);

no error ,but I can't get the request'data :

debug(this.request.files.file);

Result is undefined.

I am using KoaJs.

Body:
Try koa-body library.

Example:

Put this middleware BEFORE the route middleware:

app.use(require('koa-body')({
    formidable:{
        uploadDir: __dirname + '/public/uploads', // directory where files will be uploaded
        keepExtensions: true // keep file extension on upload
    },
    multipart: true,
    urlencoded: true,
}));

Then use in route middleware

async function(ctx, next) {
    ctx.request.body.files.file  // file is the input name
}

This code is for KoaJs 2, but this library works with KoaJs 1 too.


问:
Backbone, multi-language and root
I'm using backbone to manage my routing. I need to implement multi-language on my website as following :

in french : www.example.com

in english : www.example.com/en

Moreover I have an additional root on my url on production, so it gives www.example.com/dev or www.example.com/dev/en

The root is provided through my web server (node). It's retrieved through the <%- prefix %> variable in the example below.

It works well on localhost, but as soon as I pass on my server with a url with the additional root, the pages are not found. I'm looking for a generic solution to manage both situations (with or without root).

```<code><!DOCTYPE html>
<html>
<head>
...
</head>
<body>

<script type="text/javascript">

window.onload = function()
{
    let prefix = '<%- prefix %>'.substr(1);

    var BaseRouter = Backbone.Router.extend({
        routes: {

            [prefix + 'imgfocus/:imgid'] : 'imgfocus',
            [prefix + 'skymap/:obsids'] : 'skymap',
            // ...
            },

        imgfocus : function(imgid)
        {
            navservice.loadScreen({page : 'imgfocus', imgid : imgid});
        },
        skymap : function(obsids, stateid, tourid)
        {
            navservice.loadScreen({page : 'skymap', obsids : parseInt(obsids) === 0 ? undefined : obsids, stateid : stateid, tourid : tourid});
        },
        /// ...
    });

    let br = new BaseRouter();

    for (let i = 0; i < navservice.languages.length; i++)
        {
            if (navservice.languages[i] !== '')
            {
                for (let key in br.routes)
                {
                    br.routes[navservice.formatUrl(key, navservice.languages[i]).substr(1)] = br.routes[key];
                }
            }
        }
        // language retrieval
        var language = navservice.getUserLanguage();

        Backbone.history.start({pushState : true, root: '/' + (language ? language : '')});
    }

    $(document).on("click", "a:not([data-bypass])", function (evt) {
        var href = { prop: $(this).prop("href"), attr: $(this).attr("href") };
        var root = location.protocol + "//" + location.host + Backbone.history.options.root;
        if (href.prop && href.prop.slice(0, root.length) === root) {
            evt.preventDefault();
            var route = href.attr;

            // language retrieval
            var lang = navservice.getUserLanguage(route);

            if(lang && route.slice(0,lang.length+1) === "/" + lang) {
                route = route.slice(lang.length+1);
            }

            Backbone.history.navigate(route, {trigger : true});
        }
    });
}

</script>
</code>```

答:
Create differents templates, then use history root option:

```<code>Backbone.history.start({pushState: true, root: "/en/"})
</code>```

More info backbone history start.

Title: Backbone, multi-language and root

Body:
I'm using backbone to manage my routing. I need to implement multi-language on my website as following :

in french : www.example.com

in english : www.example.com/en

Moreover I have an additional root on my url on production, so it gives www.example.com/dev or www.example.com/dev/en

The root is provided through my web server (node). It's retrieved through the <%- prefix %> variable in the example below.

It works well on localhost, but as soon as I pass on my server with a url with the additional root, the pages are not found. I'm looking for a generic solution to manage both situations (with or without root).

<!DOCTYPE html>

...

Body:
Create differents templates, then use history root option:

Backbone.history.start({pushState: true, root: "/en/"})

More info backbone history start.


问:
Generate .i file from .c file
I know that gcc does that. But I would want a C program that can do so. The program should accept a .c file and does the preprocessing operations and generate .i file
FYI : this is a project that was assigned to my kin in his college.</p>

答:
use the command cc -E file.c -o file.i this will give you preprocessed file. For more info refer man page.

Just read your question again. You want to write program, which created that file.
well you have to do lot of work for that.First of all you need to read #include ,  #define and Conditional inclusions (#if, #elif #endif) and then you need to detect < > and " ", read the file which is inside these symbols. then you have to fopen() those files and paste them into .i file.

TO sum it up it will be a lot of work but that's the way to do it.

Edit it is not just copy past. Reading the header file means that inside #include now say your header is abc.h, then you have to search for all predefined location where a .h file can be present. If it is found you need to fopen() that file read its content and write it into your .c file. Plus you have to take care of macros and condtional inclusion. Trust me i have tried it, its lot of work. but you can try it will boost up your basic

Title: Generate .i file from .c file


问:
Javascript package or library for UI component
I am looking for a implementation for the following image of a component. It runs through each header and text and scrolls up the associated image periodically. The user may also select a text block and the image on the right will scroll to the associated image, much like a carousel. Is there a library or package that may help me create this?

(I'm not sure what the best term for such an interface is)

答: Try to check components from this collection of JavaScript UI frameworks. </p>


问:
How get cart content ? (prestashop)
I'd like get cart content on prestashop os-commerce. How can do it ?</p>

答:
Simply use

```<code>Context::getContext()->cart
</code>```

refer this link
https://www.prestashop.com/forums/topic/440516-how-to-get-all-product-ids-in-current-cart/

Title: How get cart content ? (prestashop)

Body:
Simply use

Context::getContext()->cart

refer this link
https://www.prestashop.com/forums/topic/440516-how-to-get-all-product-ids-in-current-cart/


问:
What is the difference between valueforKey:, objectForKey:, and valueForKeyPath:?
I have 2 questions:

What is the difference between valueForKey: and objectForKey:? Is it that one is for NSDictionarys (objectForKey:) and for others it is valueforKey:, or is it the reverse?

Also what is the difference between valueForKey: and valueForKeyPath:? Has it got something to do with Core Data?

Please help.

答:
valueForKey: is part of the NSKeyValueCoding protocol and is therefore part of the key-value coding framework, which allows you to access class properties by name at runtime. That's how NIBs are loaded, for example — the names of properties associated with connections are loaded and then the values are set directly by name. This contrasts with the way that visual interface design tools often work in other languages, generating lots of hidden statically compiled code.

objectForKey: is defined on dictionaries only, and looks up an object by its key. An NSDictionary is a class that stores connections between values and keys.

So, valueForKey: could be used on an NSDictionary to return meta information about the dictionary, such as the count of objects inside it, the list of all keys, etc. objectForKey: would be used actually to look into the dictionary.

At runtime, the difference is that objectForKey: is a method with a completely opaque implementation. valueForKey: explicitly relies on subsequently calling named getters and setters. The reason for the latter is that you can extend key-value coding to key-value observing, where you ask to be informed every time a particular property on a particular object changes. At runtime that's achieved with a method swizzle, where the original setter is replaced by a new one that calls the previous setter and then sends out the required messages. Because all messages are dispatched dynamically, that's just achieved by modifying tables within the object instance.

So any object that is key-value coding compliant (which just means declaring and implementing your properties in the proper way, which the new-ish @property/@synthesize syntax does automatically) can be observed without the object itself having to implement any code.

There's further Apple stuff that uses key-value coding to achieve various things, including CoreData, but it's not specifically to enable any one other technology.

valueForKeyPath: is like valueForKey: except that it can traverse several objects. So you can have a root object with a bunch of properties, each of those properties is another object with another bunch of properties, etc, and using a key path you can retrieve a value way out at the leaf of that data structure rather than having to iterate through object after object for yourself.

In summary, valueForKey: and valueForKeyPath: provide information about object instances and interact with the dynamic nature of the Objective-C runtime. objectForKey: is a dictionary specific method that does dictionary tasks.

Additions:

An example, coded as I type and assuming that NSDictionary is key-value coding compliant:

```<code>NSDictionary *someDictionary;
// create someDictionary, populate it, for example (note: we assume photoOfKeys.jpg
// definitely exists, not a good idea for production code — if it doesn't we'll get
// a nil there and anything after it won't be added to the dictionary as it'll appear
// that we terminated the list):
someDictionary = @{ @"favouriteGarment": @"hat",
                    @"@allKeys"        : [NSImage imageNamed:NSImageNameDotMac],
                    @(2)               : NSArray.new };

NSObject *allKeys;
// we make no assumptions about which type @allKeys will be,  but are going to assume
// we can NSLog it, so it needs to be a descendant of NSObject rather than 'id' so as
// to definitely respond to the 'description' message — actually this is just compile
// time semantics, but if someone else reads this code it'll make it obvious to them
// what we were thinking...

// some code to get all of the keys stored in the dictionary and print them out;
// should print an array containing the strings 'favouriteGarment', '@allKeys' and
// the number 2
allKeys = [someDictionary valueForKey:@"@allKeys"];
NSLog(@"%@", allKeys);

// some code to get the object named '@allKeys' from the dictionary; will print
// a description of the image created by loading photoOfKeys.jpg, above
allKeys = [someDictionary objectForKey:@"@allKeys"];
NSLog(@"%@", allKeys);
// `objectForKey is analogous to `objectForKeyedSubscript:`, aka
allKeys = someDictionary[@"@allKeys"];
</code>```

allKeys is a property of NSDictionary as described here. I've also added a mapping from the NSString allKeys to a photograph of some keys. Whether I use the key-value coding valueForKey: methods or the NSDictionary objectForKey: lookup method dictates whether I read the property of the object instance or whether I send the object instance a message asking it to do its unique job.

Body:
valueForKey: is part of the NSKeyValueCoding protocol and is therefore part of the key-value coding framework, which allows you to access class properties by name at runtime. That's how NIBs are loaded, for example — the names of properties associated with connections are loaded and then the values are set directly by name. This contrasts with the way that visual interface design tools often work in other languages, generating lots of hidden statically compiled code.

objectForKey: is defined on dictionaries only, and looks up an object by its key. An NSDictionary is a class that stores connections between values and keys.

So, valueForKey: could be used on an NSDictionary to return meta information about the dictionary, such as the count of objects inside it, the list of all keys, etc. objectForKey: would be used actually to look into the dictionary.

At runtime, the difference is that objectForKey: is a method with a completely opaque implementation. valueForKey: explicitly relies on subsequently calling named getters and setters. The reason for the latter is that you can extend key-value coding to key-value observing, where you ask to be informed every time a particular property on a particular object changes. At runtime that's achieved with a method swizzle, where the original setter is replaced by a new one that calls the previous setter and then sends out the required messages. Because all messages are dispatched dynamically, that's just achieved by modifying tables within the object instance.

So any object that is key-value coding compliant (which just means declaring and implementing your properties in the proper way, which the new-ish @property/@synthesize syntax does automatically) can be observed without the object itself having to implement any code.

There's further Apple stuff that uses key-value coding to achieve various things, including CoreData, but it's not specifically to enable any one other technology.

valueForKeyPath: is like valueForKey: except that it can traverse several objects. So you can have a root object with a bunch of properties, each of those properties is another object with another bunch of properties, etc, and using a key path you can retrieve a value way out at the leaf of that data structure rather than having to iterate through object after object for yourself.

In summary, valueForKey: and valueForKeyPath: provide information about object instances and interact with the dynamic nature of the Objective-C runtime. objectForKey: is a dictionary specific method that does dictionary tasks.

Additions:

An example, coded as I type and assuming that NSDictionary is key-value coding compliant:

NSDictionary *someDictionary;
// create someDictionary, populate it, for example (note: we assume photoOfKeys.jpg
// definitely exists, not a good idea for production code — if it doesn't we'll get
// a nil there and anything after it won't be added to the dictionary as it'll appear
// that we terminated the list):
someDictionary = @{ @"favouriteGarment": @"hat",
                    @"@allKeys"        : [NSImage imageNamed:NSImageNameDotMac],
                    @(2)               : NSArray.new };

NSObject *allKeys;
// we make no assumptions about which type @allKeys will be,  but are going to assume
// we can NSLog it, so it needs to be a descendant of NSObject rather than 'id' so as
// to definitely respond to the 'description' message — actually this is just compile
// time semantics, but if someone else reads this code it'll make it obvious to them
// what we were thinking...

// some code to get all of the keys stored in the dictionary and print them out;
// should print an array containing the strings 'favouriteGarment', '@allKeys' and
// the number 2
allKeys = [someDictionary valueForKey:@"@allKeys"];
NSLog(@"%@", allKeys);

// some code to get the object named '@allKeys' from the dictionary; will print
// a description of the image created by loading photoOfKeys.jpg, above
allKeys = [someDictionary objectForKey:@"@allKeys"];
NSLog(@"%@", allKeys);
// `objectForKey is analogous to `objectForKeyedSubscript:`, aka
allKeys = someDictionary[@"@allKeys"];

allKeys is a property of NSDictionary as described here. I've also added a mapping from the NSString allKeys to a photograph of some keys. Whether I use the key-value coding valueForKey: methods or the NSDictionary objectForKey: lookup method dictates whether I read the property of the object instance or whether I send the object instance a message asking it to do its unique job.


问:
Typecast compojure route's id to integer automatically
I have something like this (GET "/photo/:id/tags/:tag-id/...")

and thus for every route inside that context I have to typecast these ids to Integer explicitly. Is there any way to achieve this automatically or have a common place to typecast ids instead of each controller's action?

答:
As of Compojure 1.4.0, you can also supply coercion functions for parameters using the :<< keyword:

```<code>[x :<< as-int]
</code>```

In the above case, the parameter x will be passed through the as-int function before being assigned. If any coercion function returns nil, then the coercion is considered to have failed, and the route will not match.

Example:

```<code>(defroutes app
  (GET "/customers" [] customers)
  (GET "/suppliers" [] suppliers)
  (GET "/accounts" [] accounts)
  (context "/statements" []
           (GET "/" [] statements)
           (GET "/:id" [id :<< as-int] (single-statement id))))
</code>```

Body:
As of Compojure 1.4.0, you can also supply coercion functions for parameters using the :<< keyword:

[x :<< as-int]

In the above case, the parameter x will be passed through the as-int function before being assigned. If any coercion function returns nil, then the coercion is considered to have failed, and the route will not match.

Example:

(defroutes app
  (GET "/customers" [] customers)
  (GET "/suppliers" [] suppliers)
  (GET "/accounts" [] accounts)
  (context "/statements" []
           (GET "/" [] statements)
           (GET "/:id" [id :<< as-int] (single-statement id))))


问:
how to retrieve the type of value which is there more number of times in a column in a table and count of it?
```<code>s.no    Name       type of vehicle allotted

1      ram             bus
2      krish           car

3      raj             bus

4      albert          car

5      johnson         bike

6      raghu           car
</code>```

consider this is a table now i want to retrieve the type of vehicle which is there more number of times in the table and count of it. is there any particular method(query).

答:
I think you have to count and select the top 1 row.

Query

```<code>SELECT t.* FROM(
    SELECT `type`, COUNT(`type`) `count`
    FROM `your_table_name`
    GROUP BY `type`
)t
ORDER BY `count` DESC LIMIT 1;
</code>```

Body:
s.no    Name       type of vehicle allotted

1      ram             bus
2      krish           car

3      raj             bus

4      albert          car

5      johnson         bike

6      raghu           car

consider this is a table now i want to retrieve the type of vehicle which is there more number of times in the table and count of it. is there any particular method(query).

Body:
I think you have to count and select the top 1 row.

Query

SELECT t.* FROM(
    SELECT `type`, COUNT(`type`) `count`
    FROM `your_table_name`
    GROUP BY `type`
)t
ORDER BY `count` DESC LIMIT 1;


问:
Remove tiny scroll bar - Ionic 3
You can see that there is a tiny scroll bar as shown below.Can you tell me how to remove that? This is Ionic 3 app. I have tried many ways.But no luck yet.

Please see how bad it is on the device :(

This on the browser:

.sass

```<code> .height-70 {
        height: 70px;
        overflow: hidden;
    }
</code>```

.html

```<code><ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col class="height-70" col-12>
        <ion-content>
          <button ion-button icon-left full (click)="loginWithLinkedin()" class="background-color-linkedin"><ion-icon name="logo-linkedin" class="margin-top-minus-4"></ion-icon><span>Continue with Linkedin</span></button>
        </ion-content>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>
</code>```

Chrome css(run time): below padding:16px is the problem.But how can I remove it? Because I need padding too.Any workaround?

答: If you use ion-content inside ion-col it will add some properties from scroll-content. Replace ion-content with div and manually add all the css properties you want to your div.

Title: Remove tiny scroll bar - Ionic 3

Body:
You can see that there is a tiny scroll bar as shown below.Can you tell me how to remove that? This is Ionic 3 app. I have tried many ways.But no luck yet.

Please see how bad it is on the device :(

This on the browser:

.sass

 .height-70 {
        height: 70px;
        overflow: hidden;
    }

.html

<ion-content padding>
  <ion-grid>
    <ion-row>
      <ion-col class="height-70" col-12>
        <ion-content>
          <button ion-button icon-left full (click)="loginWithLinkedin()" class="background-color-linkedin"><ion-icon name="logo-linkedin" class="margin-top-minus-4"></ion-icon>Continue with Linkedin</button>
        </ion-content>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

Chrome css(run time): below padding:16px is the problem.But how can I remove it? Because I need padding too.Any workaround?


问:
Mirror a Git repository directly to AWS CodeCommit
I want to create a backup of one of my Git repositories and save it to AWS CodeCommit. I don't want to include the use of my local machine. Can anyone tell me how can I do it directly or through AWS Lambda?</p>

答:
It seems migrating directly from Github to AWS Code-commit is not available in the AWS documentation. The following links have some scripts that can do the migration using a local machine.

Please check:

http://www.paul-kearney.com/2015/09/migrating-from-github-to-aws-codecommit.html

https://gist.github.com/paulkearney/6042561c56654a15af3c

ContentLicense: CC BY-SA 4.0


问:
Multiple Activity or Single Activity and multiple fragments
I have one very general question, I did not find a concrete answer for my question hence putting it again.

I want to decide between two approaches

Dedicated activities for various various screens and tasks to avoid complexity and issues

Single Activities and multiple fragments for different tasks and user can navigate like Activity holding Fragment A user will navigate to Fragment B, Fragment C , this can be back and forth transaction.

What I want to know?

Is Activity transition is that costly for processor or to achieve simplicity memory overhead is negligible ?

Fragment has overhead of managing life cycle with transition, so what all problem can come with this life cycler management?

How easy is to deal with fragment transaction with saving state of the fragment?

We don't know right now what amount data will be there for fragment to hold.

答:
Apart from answers above, few points which I would add which can help in deciding when to use a Fragment and when to use an Activity.

If you're supporting larger screen sizes, fragments are definitely preferred over activities.

When you've some code which you think can be reusable in multiple screens, you can use a fragment which can be reused across different places


问:
Choosing a simple web application framework
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages. </p>

<p>I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail. </p>

答: Squatting is a small perl based web framework thingy inspired by Ruby's Camping.  They're both small.</p>

OwnerDisplayName: nagul

Body:
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages.

I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail.

LastEditorDisplayName: Marko Dumic


问:
CSS: overflow-y and padding adjustment
Hi I am trying to pad some text with over-flow and padding but the bottom padding does not work like the rest of the top, left and right borders.

I try adding text-overflow but this didn't work. :(

I want to see the word "TEST" to be partially hidden, and not touching the black border.

body, html {
 margin: 0;
 padding: 0;
 display: flex;
 justify-content: center;
 align-items: center;
 height:100%;
 width: 100%;
}
.css {
 width: 220px;
 height: 220px;
 border: solid 6px black;
 font-size: 45pt;
 padding: 10px 17px;
 font-family: arial, sans-serif;
 font-weight: 600;
 line-height: 90%;
 box-sizing: border-box;
 background-color:red;
 overflow:hidden;
 text-overflow:'';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="css">CSS IS AWESOME TEST</div></code>```

https://codepen.io/StoptThisRetard/pen/eRrrJg

答:
The problem is that overflow:hidden hides the content that goes outside the box, whereas padding is inside the box.

So what result you are getting, is correct.

To solve your issue, you can add another div and give that div padding and background. See snippet below

body,
html {
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
}

.css {
  width: 220px;
  height: 220px;
  font-size: 45pt;
  padding: 10px 17px;
  font-family: arial, sans-serif;
  font-weight: 600;
  line-height: 90%;

   overflow: hidden;
}

.css_wrapper {
  padding: 10px 17px;
  border: solid 6px black;
  background-color: red;
 box-sizing: border-box;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="css_wrapper">
  <div class="css">CSS IS AWESOME TEST</div>
</div></code>```

Title: CSS: overflow-y and padding adjustment

Body:
Hi I am trying to pad some text with over-flow and padding but the bottom padding does not work like the rest of the top, left and right borders.

I try adding text-overflow but this didn't work. :(

I want to see the word "TEST" to be partially hidden, and not touching the black border.

body, html {
 margin: 0;
 padding: 0;
 display: flex;
 justify-content: center;
 align-items: center;
 height:100%;
 width: 100%;
}
.css {
 width: 220px;
 height: 220px;
 border: solid 6px black;
 font-size: 45pt;
 padding: 10px 17px;
 font-family: arial, sans-serif;
 font-weight: 600;
 line-height: 90%;
 box-sizing: border-box;
 background-color:red;
 overflow:hidden;
 text-overflow:'';
}

CSS IS AWESOME TEST

https://codepen.io/StoptThisRetard/pen/eRrrJg

Body:
The problem is that overflow:hidden hides the content that goes outside the box, whereas padding is inside the box.

So what result you are getting, is correct.

To solve your issue, you can add another div and give that div padding and background. See snippet below

body,
html {
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
}

.css {
  width: 220px;
  height: 220px;
  font-size: 45pt;
  padding: 10px 17px;
  font-family: arial, sans-serif;
  font-weight: 600;
  line-height: 90%;

   overflow: hidden;
}

.css_wrapper {
  padding: 10px 17px;
  border: solid 6px black;
  background-color: red;
 box-sizing: border-box;

}

<div class="css_wrapper">
  <div class="css">CSS IS AWESOME TEST</div>
</div>


问:
How to get the latest labeled code and label name in TFS2013 using powershell
I am trying to get the latest labeled code for specific solution/project in TFS 2013 using PowerShell. If anyone knows how to get the latest label, please post it here.</p>

答:
You can use below script to get the latest label for specific project:</p>

```<code>#Add Reference Assemblies to be loaded accordingly based on your VS client.

add-type -Path 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Microsoft.TeamFoundation.VersionControl.Client.dll'
add-type -Path 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Microsoft.TeamFoundation.Client.dll'

$CollectionUrl = 'http://servername:8080/tfs/DefaultCollection'
$tfs = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($CollectionUrl)
$vcs = $tfs.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$labels = $vcs.QueryLabels('*','$/ProjectName',$null,$true)
$latestlabel = $labels | Select-Object -first 1

write-host "The Latest Lable Name:" $latestlabel.Name
write-host "The Latest Lable ID  :" $latestlabel.LabelID
</code>```

Body:
You can use below script to get the latest label for specific project:

#Add Reference Assemblies to be loaded accordingly based on your VS client.

add-type -Path 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Microsoft.TeamFoundation.VersionControl.Client.dll'
add-type -Path 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Microsoft.TeamFoundation.Client.dll'

$CollectionUrl = 'http://servername:8080/tfs/DefaultCollection'
$tfs = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($CollectionUrl)
$vcs = $tfs.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$labels = $vcs.QueryLabels('*','$/ProjectName',$null,$true)
$latestlabel = $labels | Select-Object -first 1

write-host "The Latest Lable Name:" $latestlabel.Name
write-host "The Latest Lable ID  :" $latestlabel.LabelID


问:
Error:(33, 0) Could not find property 'compile' on org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@3da55115
there is a problem to sync of my project. when i was add some dependencies in build.gradle file, it through some errors, please help me

there is my code :

```<code>buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    maven {
        url 'http://clojars.org/repo'
    } }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'

        compile 'com.pusher:pusher-java-client:1.0.0'
        // for our HTTP requests later
        compile 'com.google.code.gson:gson:2.2.4', // for parsing JSON
                compile 'com.loopj.android:android-async-http:1.4.9'
         compile 'com.squareup.picasso:picasso:2.1.1' // for image rendering
    }
</code>```

答:
compile as a property. You should use proper FORMAT .

Don't

```<code>compile 'com.google.code.gson:gson:2.2.4', // Remove ,
</code>```

Do

```<code>compile 'com.google.code.gson:gson:2.2.4'
</code>```

Body:
there is a problem to sync of my project. when i was add some dependencies in build.gradle file, it through some errors, please help me

there is my code :

buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

repositories {
    maven {
        url 'http://clojars.org/repo'
    } }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'

        compile 'com.pusher:pusher-java-client:1.0.0'
        // for our HTTP requests later
        compile 'com.google.code.gson:gson:2.2.4', // for parsing JSON
                compile 'com.loopj.android:android-async-http:1.4.9'
         compile 'com.squareup.picasso:picasso:2.1.1' // for image rendering
    }

Body:
compile as a property. You should use proper FORMAT .

Don't

compile 'com.google.code.gson:gson:2.2.4', // Remove ,

Do

compile 'com.google.code.gson:gson:2.2.4'


问:
Fire event on binding values to dropdown
I need to manipulate the values during the bind of those to the select. Which of the event can pass the binding value as parameter and return the same with a added property or fetch the option direct and return with adding a property?

Something like this,

```<code>@Html.DropDownListFor(m => m.UserId, Model.UserList, "Select Name", new { @class = "target", @id = "ddlNames" })

$( ".target" ).xxx(function() {
  //Fetch the options here and add a property (selected="selected")
});
</code>```

Any ideas?

答:
You have to use $.ready() with :contains() without using any loop like,

```<code>$(function() { // just use code in document ready
    $(".target option:contains(Option-Value)").attr('selected','selected');
});
</code>```

Snippet,

$(function() { // just use code in document ready
  $(".target option:contains(Option 4)").attr('selected', 'selected');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="target">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
  <option value="option4">Option 4</option>
  <option value="option5">Option 5</option>
</select></code>```

Body:
I need to manipulate the values during the bind of those to the select. Which of the event can pass the binding value as parameter and return the same with a added property or fetch the option direct and return with adding a property?

Something like this,

@Html.DropDownListFor(m => m.UserId, Model.UserList, "Select Name", new { @class = "target", @id = "ddlNames" })

$( ".target" ).xxx(function() {
  //Fetch the options here and add a property (selected="selected")
});

Any ideas?

Body:
You have to use $.ready() with :contains() without using any loop like,

$(function() { // just use code in document ready
    $(".target option:contains(Option-Value)").attr('selected','selected');
});

Snippet,

$(function() { // just use code in document ready
  $(".target option:contains(Option 4)").attr('selected', 'selected');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="target">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
  <option value="option4">Option 4</option>
  <option value="option5">Option 5</option>
</select>


问:
Corrupt UDP Packet java
Sender

```<code>package core;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import message.JOutMessages;

/**
 *
 * @author padaboo I.B Aleksandrov jetananas@yandex.ru
 */
public class JUDPSender extends Thread{
    /**
     * run stop flag
     */
    public static boolean isRunning = true;
    /**
     * pool size
     */
    public int poolSize;
    /**
     * out passage
     */
    public JOutMessages message;
    /**
     * client port
     */
    public int clientPort;

    public JUDPSender(int poolSize,int clientPort){
        this.poolSize    = poolSize;
        this.clientPort  = clientPort;
    }

    @Override
    public void run() {
        try{
            ExecutorService executor   =  Executors.newFixedThreadPool(poolSize);
            DatagramSocket socket      =  new DatagramSocket();

            DatagramPacket packet;
            byte[] buffer;
            InetAddress inetAddress;
            JUDPSenderHandler handler;

            while(JUDPSender.isRunning){

                for (String key : JOutMessages.getKeySet()) {

                    message     =  (JOutMessages) JOutMessages.get(key);

                    buffer      = message.json.toJSONString().getBytes();

                    //System.out.println(message.json.toJSONString());

                    inetAddress = InetAddress.getByName(message.ip);

                    packet = new DatagramPacket(buffer, buffer.length, inetAddress, this.clientPort);

                    handler = new JUDPSenderHandler(socket,packet);
                    executor.execute(handler);

                }
            }
        } catch ( SocketException ex) {
            Logger.getLogger(JUDPSender.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnknownHostException ex){

        }
    }

    class JUDPSenderHandler implements Runnable{

        /**
         * datagram socket
         */
        DatagramSocket socket;
        /**
         * datagram packet
         */
        DatagramPacket packet;

        public JUDPSenderHandler(DatagramSocket socket,DatagramPacket packet) {
            this.socket = socket;
            this.packet = packet;
        }

        @Override
        public void run() {
            try {

                socket.send(packet);

            } catch (IOException ex) {
                Logger.getLogger(JUDPSender.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
</code>```

Recivier

```<code>/*
 * jsock framework https://github.com/nnpa/jsock open source
 * Each line should be prefixed with  *
 */

package jsock.core;

import conf.JConfig;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import jsock.message.JInMessages;

/**
 *
 * @author padaboo I.B Aleksandrov jetananas@yandex.ru
 */
public class JUDPRecivier extends Thread{

    /**
     * server port
     */
    private final int port;
    /**
     * pool size
     */
    private final int poolSize;
    /**
     * run stop flag
     */
    public static boolean isRunning = true;

    public JUDPRecivier(int poolSize,int port){
        this.port     = port;
        this.poolSize = poolSize;
    }

    /**
     * Create thread poll
     */
    @Override
    public void run() {
        try (DatagramSocket serverSocket = new DatagramSocket(port)) {

            ExecutorService executor     = Executors.newFixedThreadPool(poolSize);

            byte[] receiveData           = new byte[JConfig.socket_buffer_size];

            while(JUDPRecivier.isRunning){
                DatagramPacket receivePacket = new DatagramPacket ( receiveData, receiveData.length );
                serverSocket.receive ( receivePacket );

                executor.execute(
                    new JUDPRecivierHandler(serverSocket,receivePacket)
                );
            }
            serverSocket.close();
        } catch (IOException ex) {
            Logger.getLogger(JTCPReciver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Listen user sockets
     * send messages to message list
     * send connection to connection list
     */
    class JUDPRecivierHandler implements Runnable{
        //socket
        DatagramSocket socket;

        DatagramPacket receivePacket;

        public JUDPRecivierHandler(DatagramSocket serverSocket,DatagramPacket receivePacket) {
            this.socket        = serverSocket;
            this.receivePacket = receivePacket;
        }

        @Override
        public void run() {
            InetAddress inetAdress    = receivePacket.getAddress();
            String ip = inetAdress.getHostAddress();

            byte[] data = new byte[receivePacket.getLength()];

            data  = receivePacket.getData();

            String stringData = new String(data,0, receivePacket.getLength());

            JInMessages inputSocketMessage = new JInMessages(ip,stringData);
            inputSocketMessage.insert();
        }
    }
}
</code>```

Send packet

{"task":"JGameTask","data":{"isDirectRight":false,"Left":false,"blockMove":false,"fallSpeed":100,"LeftRelease":false,"LClickRelease":false,"DownRelease":false,"Right":false,"SitRelease":false,"camLeftZ":0.08650045,"camLeftY":-4.0163286E-9,"camLeftX":-0.18032658,"speed":1.0,"LClick":false,"camRotationW":-0.22177358,"camRotationX":-2.1658896E-4,"JumpRelease":false,"startLocation":{"x":-67.11953,"y":8.058952,"z":-55.18904},"camRotationY":0.9750977,"camRotationZ":-9.522566E-4,"levelId":"Gilkph036QbP","isRightDirect":false,"isSitRight":false,"Down":false,"camDirectionZ":-0.2704894,"RightRelease":false,"isDirectLeft":false,"camDirectionX":-0.12975043,"camDirectionY":-5.859462E-4,"CtrlRelease":false,"isSit":false,"isSitLeft":false,"Ctrl":false,"Jump":false,"isAnimRun":false,"isLeftDirect":false,"command":1,"rotateAnimation":"direct","isSitRun":false,"runAnimation":"run","gravity":60,"UpRelease":false,"Up":false,"Sit":false,"isStand":false},"user_id":"18","scenario":"send_keys","auth_token":"c0facde0aa585dc4b7e0a6d820bb3df41499141302"}

Receive with error:  at end 2"}

{"task":"JGameTask","data":{"isDirectRight":false,"Left":false,"blockMove":false,"fallSpeed":100,"LeftRelease":false,"LClickRelease":false,"DownRelease":false,"Right":false,"SitRelease":false,"camLeftZ":0.08650045,"camLeftY":-4.0163286E-9,"camLeftX":-0.18032658,"speed":1.0,"LClick":false,"camRotationW":-0.22177358,"camRotationX":-2.1658896E-4,"JumpRelease":false,"startLocation":{"x":-67.11953,"y":8.058952,"z":-55.18904},"camRotationY":0.9750977,"camRotationZ":-9.522566E-4**,**"levelId":"Gilkph036QbP","isRightDirect":false,"isSitRight":false,"Down":false,"camDirectionZ":-0.2704894,"RightRelease":false,"isDirectLeft":false,"camDirectionX":-0.12975043,"camDirectionY":-5.859462E-4,"CtrlRelease":false,"isSit":false,"isSitLeft":false,"Ctrl":false,"Jump":false,"isAnimRun":false,"isLeftDirect":false,"command":1,"rotateAnimation":"direct","isSitRun":false,"runAnimation":"run","gravity":60,"UpRelease":false,"Up":false,"Sit":false,"isStand":false},"user_id":"18","scenario":"send_keys","auth_token":"c0facde0aa585dc4b7e0a6d820bb3df41499141302"}2"}

Where is the mistake?

答:
fixed
while(JUDPRecivier.isRunning){
                receiveData           = new byte[JConfig.socket_buffer_size];</p>

```<code>            DatagramPacket receivePacket = new DatagramPacket ( receiveData, receiveData.length );
            serverSocket.receive ( receivePacket );

            executor.execute(
                new JUDPRecivierHandler(serverSocket,receivePacket)
            );

            receiveData = null;
        }
</code>```

Title: Corrupt UDP Packet java

Body:
Sender

package core;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import message.JOutMessages;

/**
 *
 * @author padaboo I.B Aleksandrov jetananas@yandex.ru
 */
public class JUDPSender extends Thread{
    /**
     * run stop flag
     */
    public static boolean isRunning = true;
    /**
     * pool size
     */
    public int poolSize;
    /**
     * out passage
     */
    public JOutMessages message;
    /**
     * client port
     */
    public int clientPort;

    public JUDPSender(int poolSize,int clientPort){
        this.poolSize    = poolSize;
        this.clientPort  = clientPort;
    }

    @Override
    public void run() {
        try{
            ExecutorService executor   =  Executors.newFixedThreadPool(poolSize);
            DatagramSocket socket      =  new DatagramSocket();

            DatagramPacket packet;
            byte[] buffer;
            InetAddress inetAddress;
            JUDPSenderHandler handler;

            while(JUDPSender.isRunning){

                for (String key : JOutMessages.getKeySet()) {

                    message     =  (JOutMessages) JOutMessages.get(key);

                    buffer      = message.json.toJSONString().getBytes();

                    //System.out.println(message.json.toJSONString());

                    inetAddress = InetAddress.getByName(message.ip);

                    packet = new DatagramPacket(buffer, buffer.length, inetAddress, this.clientPort);

                    handler = new JUDPSenderHandler(socket,packet);
                    executor.execute(handler);

                }
            }
        } catch ( SocketException ex) {
            Logger.getLogger(JUDPSender.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnknownHostException ex){

        }
    }

    class JUDPSenderHandler implements Runnable{

        /**
         * datagram socket
         */
        DatagramSocket socket;
        /**
         * datagram packet
         */
        DatagramPacket packet;

        public JUDPSenderHandler(DatagramSocket socket,DatagramPacket packet) {
            this.socket = socket;
            this.packet = packet;
        }

        @Override
        public void run() {
            try {

                socket.send(packet);

            } catch (IOException ex) {
                Logger.getLogger(JUDPSender.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

Recivier

/*
 * jsock framework https://github.com/nnpa/jsock open source
 * Each line should be prefixed with  *
 */

package jsock.core;

import conf.JConfig;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import jsock.message.JInMessages;

/**
 *
 * @author padaboo I.B Aleksandrov jetananas@yandex.ru
 */
public class JUDPRecivier extends Thread{

    /**
     * server port
     */
    private final int port;
    /**
     * pool size
     */
    private final int poolSize;
    /**
     * run stop flag
     */
    public static boolean isRunning = true;

    public JUDPRecivier(int poolSize,int port){
        this.port     = port;
        this.poolSize = poolSize;
    }

    /**
     * Create thread poll
     */
    @Override
    public void run() {
        try (DatagramSocket serverSocket = new DatagramSocket(port)) {

            ExecutorService executor     = Executors.newFixedThreadPool(poolSize);

            byte[] receiveData           = new byte[JConfig.socket_buffer_size];

            while(JUDPRecivier.isRunning){
                DatagramPacket receivePacket = new DatagramPacket ( receiveData, receiveData.length );
                serverSocket.receive ( receivePacket );

                executor.execute(
                    new JUDPRecivierHandler(serverSocket,receivePacket)
                );
            }
            serverSocket.close();
        } catch (IOException ex) {
            Logger.getLogger(JTCPReciver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Listen user sockets
     * send messages to message list
     * send connection to connection list
     */
    class JUDPRecivierHandler implements Runnable{
        //socket
        DatagramSocket socket;

        DatagramPacket receivePacket;

        public JUDPRecivierHandler(DatagramSocket serverSocket,DatagramPacket receivePacket) {
            this.socket        = serverSocket;
            this.receivePacket = receivePacket;
        }

        @Override
        public void run() {
            InetAddress inetAdress    = receivePacket.getAddress();
            String ip = inetAdress.getHostAddress();

            byte[] data = new byte[receivePacket.getLength()];

            data  = receivePacket.getData();

            String stringData = new String(data,0, receivePacket.getLength());

            JInMessages inputSocketMessage = new JInMessages(ip,stringData);
            inputSocketMessage.insert();
        }
    }
}

Send packet

{"task":"JGameTask","data":{"isDirectRight":false,"Left":false,"blockMove":false,"fallSpeed":100,"LeftRelease":false,"LClickRelease":false,"DownRelease":false,"Right":false,"SitRelease":false,"camLeftZ":0.08650045,"camLeftY":-4.0163286E-9,"camLeftX":-0.18032658,"speed":1.0,"LClick":false,"camRotationW":-0.22177358,"camRotationX":-2.1658896E-4,"JumpRelease":false,"startLocation":{"x":-67.11953,"y":8.058952,"z":-55.18904},"camRotationY":0.9750977,"camRotationZ":-9.522566E-4,"levelId":"Gilkph036QbP","isRightDirect":false,"isSitRight":false,"Down":false,"camDirectionZ":-0.2704894,"RightRelease":false,"isDirectLeft":false,"camDirectionX":-0.12975043,"camDirectionY":-5.859462E-4,"CtrlRelease":false,"isSit":false,"isSitLeft":false,"Ctrl":false,"Jump":false,"isAnimRun":false,"isLeftDirect":false,"command":1,"rotateAnimation":"direct","isSitRun":false,"runAnimation":"run","gravity":60,"UpRelease":false,"Up":false,"Sit":false,"isStand":false},"user_id":"18","scenario":"send_keys","auth_token":"c0facde0aa585dc4b7e0a6d820bb3df41499141302"}

Receive with error:  at end 2"}

{"task":"JGameTask","data":{"isDirectRight":false,"Left":false,"blockMove":false,"fallSpeed":100,"LeftRelease":false,"LClickRelease":false,"DownRelease":false,"Right":false,"SitRelease":false,"camLeftZ":0.08650045,"camLeftY":-4.0163286E-9,"camLeftX":-0.18032658,"speed":1.0,"LClick":false,"camRotationW":-0.22177358,"camRotationX":-2.1658896E-4,"JumpRelease":false,"startLocation":{"x":-67.11953,"y":8.058952,"z":-55.18904},"camRotationY":0.9750977,"camRotationZ":-9.522566E-4**,**"levelId":"Gilkph036QbP","isRightDirect":false,"isSitRight":false,"Down":false,"camDirectionZ":-0.2704894,"RightRelease":false,"isDirectLeft":false,"camDirectionX":-0.12975043,"camDirectionY":-5.859462E-4,"CtrlRelease":false,"isSit":false,"isSitLeft":false,"Ctrl":false,"Jump":false,"isAnimRun":false,"isLeftDirect":false,"command":1,"rotateAnimation":"direct","isSitRun":false,"runAnimation":"run","gravity":60,"UpRelease":false,"Up":false,"Sit":false,"isStand":false},"user_id":"18","scenario":"send_keys","auth_token":"c0facde0aa585dc4b7e0a6d820bb3df41499141302"}2"}

Where is the mistake?

Body:
fixed
while(JUDPRecivier.isRunning){
                receiveData           = new byte[JConfig.socket_buffer_size];

            DatagramPacket receivePacket = new DatagramPacket ( receiveData, receiveData.length );
            serverSocket.receive ( receivePacket );

            executor.execute(
                new JUDPRecivierHandler(serverSocket,receivePacket)
            );

            receiveData = null;
        }


问:
modify drupal views output to diplay a facebook like button
How can I edit views output rows to include a facebook like button and that like statement should take one of the field as parameter and output on facebook as ::

abc user likes "content of field" on mywebsite.com

答: Use fb_social module to implement this functionality. It is extremely easy and straight forward way to add like-box, like-buttons and all other facebook's social plugins to Drupal without too much hassle. </p>