text:
Q: WebView textarea doesn't pop up the keyboard When I display a WebView, I don't see the soft keyboard popping up. The hard keyboard also doesn't work!
What are the usual shortcomings.
The code which I use to access the WebView is:
package com.example.blahblah;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class createAccount extends Activity {

private static final String LOG_TAG = "Create Account";
private WebView mWebView;
private static final String URL = blah_app.urlSelected+"createAccount.html";
private Handler mHandler = new Handler();

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    Toast.makeText(createAccount.this, "URL = " +URL, Toast.LENGTH_SHORT).show();
    getWindow().requestFeature(Window.FEATURE_PROGRESS);
    setContentView(R.layout.webview);
    getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);

    mWebView = (WebView) findViewById(R.id.webview);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setSavePassword(true);
    webSettings.setSaveFormData(true);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setSupportZoom(true);

    final Activity activity = this;
    mWebView.setWebChromeClient(new WebChromeClient() {
    public void onProgressChanged(WebView view, int progress) {

        activity.setProgress(progress * 1000);
      }
    });

    mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");
    mWebView.clearCache(true);
    setProgressBarVisibility(true);
    mWebView.setWebViewClient(new WebViewClient() {
          public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
          }

           @Override
           public void onPageFinished(WebView view, String url)
           {
               mWebView.loadUrl("javascript:(function () { " +
                       "setVariables("+blah_app.numberSelected+",'"+blah_app.urlSelected+"');" +
                       "})()");
           }
        });

    mWebView.loadUrl(URL);
}

final class DemoJavaScriptInterface {

    public void setData(String fname, String lname, String gacct, String phone) {

        SharedPreferences prefCreateAccount = PreferenceManager.getDefaultSharedPreferences(createAccount.this);
        SharedPreferences.Editor editor = prefCreateAccount.edit();
        editor.putString("FirstName", fname);
        editor.putString("LastName", lname);
        editor.putString("GmailAcct", gacct);
        editor.putString("Phone", phone);
        editor.commit();

    }
    DemoJavaScriptInterface() {

    }

    /**
     * This is not called on the UI thread. Post a runnable to invoke
     * loadUrl on the UI thread.
     */
    public void clickOnAndroid() {
        mHandler.post(new Runnable() {
            public void run() {
                mWebView.loadUrl("javascript:wave()");
            }
        });
    }
}

/**
 * Provides a hook for calling "alert" from javascript. Useful for
 * debugging your javascript.
 */
final class MyWebChromeClient extends WebChromeClient {
    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        Log.d(LOG_TAG, message);
        result.confirm();
        return true;
    }
}

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
        startActivity(new Intent(getApplication(), blah_app.class));
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
}

A: I'm surprised that even on Android 4.1 (tested on SGS3) the problem is still present, and overriding onTouch() don't solve it for me.
Test code:
String HTML = "TEST<form>";
HTML += "<INPUT TYPE=TEXT SIZE=40 NAME=user value=\"your name\">";
HTML += "</form>";

WebView wv = new WebView(getContext());
wv.loadData(HTML, "text/html", null);

final AlertDialog.Builder adb = new AlertDialog.Builder(getContext());
adb.setTitle("TEST").setView(wv).show();

My complex solution is replace WebView with MyWebView:
private static class MyWebView extends WebView
{
    public MyWebView(Context context)
    {
        super(context);
    }

    // Note this!
    @Override
    public boolean onCheckIsTextEditor()
    {
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev)
    {
        switch (ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!hasFocus())
                    requestFocus();
            break;
        }

        return super.onTouchEvent(ev);
    }
}

A: one line answer and it is working nicely
// define webview for browser
wb = (WebView) findViewById(R.id.webView1);
wb.requestFocusFromTouch();

where wb is my object of webView

A: Had the same issue and non of the above solutions worked. This woked for me
    <CustomWebView
    android:id="@+id/webView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:focusable="true"
    android:focusableInTouchMode="true" />

A: The full solution is a bit more than what Sana had.  It is documented as a bug over at the Android site ( http://code.google.com/p/android/issues/detail?id=7189 ):
webView.requestFocus(View.FOCUS_DOWN);
webView.setOnTouchListener(new View.OnTouchListener()
{
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!v.hasFocus())
                {
                    v.requestFocus();
                }
                break;
        }
        return false;
    }
});

A: For those of you looking for a solution when the WebView is in an AlertDialog, the answer here solved this problem for me: Show soft keyboard in AlertDialog with a WebView inside (Android)

A: The problem was that webview wasn't getting focus when it was loaded hence using
webView.requestFocus(View.FOCUS_DOWN);

solved the problem.

A: I had the same problem on Jelly Bean, but none of the above solutions worked for me. This solution worked for me on JellyBean
WebView webView = new WebView(getActivity(), null, android.R.attr.webViewStyle);

Sometimes the android.R.attr.webViewStyle is not applied by default. This ensures that the style is always applied.

A: I had a similar problem.... and later i found that the text box on the web page that my web view shown was disabled.
Check this if the page has same problem in browser?

A: I was having the exact same problem none of the above solutions worked for me. After ages of trying i finally found the problem.
Some of the various web pages I was rendering with WebView didn't fit properly into the Web view and as a result a div (or some other html component ) were being invisibly laid over the input fields. Although the input fields appeared selected when touched, they would not allow text input (even if i did manage to get the soft keyboard up using the track ball).
So the solution.
WebView.getSettings().setUseWideViewPort(true);

This won't completely stop the issue, but makes the view more like a PC browser which sites are designed for. Less change of the overlay.
Hope this helps you.

A: try this --> the firstname is the name of the field and make sure it dose not have autofocus attribute.
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            mWebView.loadUrl("javascript:document.getElementById(\"firstname\").focus();");
        }
    });

A: For making it easy, and as the other solutions have issues working on all devices or in all condition, I'm always using a small hack to overcome this issue without touching the code, just add any hidden editText to the layout contains the webView that will grant the focus to the whole view automatically and you will not have to worry about the webView text fields anymore:
<EditText
    android:id="@+id/kb_holder"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:inputType="text"
    android:maxLines="1"
    android:visibility="gone" />

So, the whole layout would be like:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/kb_holder"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:inputType="text"
        android:maxLines="1"
        android:visibility="gone" />

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

A: override onPageFinished in WebViewClient
override fun onPageFinished(view: WebView?, url: String?) {

    // Show soft input automatically for specific search web page.
    if ("the_url_page".equals(url)) {
        view?.requestFocus()
        val imm: InputMethodManager? = view?.context?.getSystemService(INPUT_METHOD_SERVICE) as? InputMethodManager
            imm?.showSoftInput(view, 0)
    }
    super.onPageFinished(view, url)
}


text:
Q: iOS Swift DispatchQueue: How do I run a process using multiple CPUs Please note this is Swift 4
So far I am trying to run the Grand Central Dispatch to process images on multiple cores.
The issue I am running into is that the processing only occurs on the main queue and stays on the first core.
I am using an iPhone 6 which has dual cores up to 200% cpu I can use and it caps out at 100% CPU and other threads are clearly not running the function.
CODE:
//value is an image inside an image array that I am using the .map function
//imageProcess processes an image on the device CPU.

                let core1 = DispatchQueue(label: "core1", qos: .userInitiated)
                let core2 = DispatchQueue(label: "core2", qos: .userInitiated)

                core1.async {

                    self.imageProcess(fromImage: value, completion: { (error) in
                        if let error = error {
                            print("Oops something failed!")
                        }
                        else {
                            print("It has finished! Core1")
                        }
                    })
                }
                core2.async{
                    self.imageProcess(fromImage: value, completion: { (error) in
                        if let error = error {
                            print("Oops something failed!")
                        }
                        else {
                            print("It has finished! Core2")
                        }
                    })
                }

What I am seeing is the DispatchQueue just drops everything into thread 11 on my CPU and all the images are processed that way. There is no multithreading and it stays on a single core.
Questions:

*

*Do I need to dump the function inside the dispatch queue?

*Does anyone have a snippet with DispatchQueue I can test for running a iOS device up to 200% CPU?

Thanks all!
Update
Looks like my function is not properly configured for DispatchQueue. Any suggestions?
Please note that faceDetector is calling a firebase function MLKit Firebase
private func imageProcess(fromImage image: UIImage, completion: @escaping (Error?) -> Void) {
    let visionImage = VisionImage(image: image)
    faceDetector.detect(in: visionImage) { [unowned self] (faces, error) in
        guard error == nil, let detectedFaces = faces else {
            self.showAlert("An error occured", alertMessage: "The face detection failed.")
            return
        }

        let faceStates = self.faceStates(forDetectedFaces: detectedFaces)
        self.updateDetectedInfo(forFaceStates: faceStates)
        completion(nil)
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cube of summation of independent (uncorrelated) random variables Basically, I am trying to prove an equality involving skewness of summation of random indepdent variables. However, I am stuck with the part after expressing sum of cube to $E[X^3] - 3E[X^2]\mu +2\mu^3$. I tried to solve using similar techniques for solving variances but now I am lost. And I could not find any helpful clue or proof.
Given setting is as the following:
When $X = x_1 + x_2 + ... + x_n$, how to compute $E[X^3]$?
Also, how to express $E[X^3]$ using triple summations with $i, j, k = 1, 2, ... , n$ when $i, j, \& k$ may (or may not - possibly in both cases)  equivalent?
Many thanks in advance.

A:
Also, how to express $E[X^3]$ using triple summations with $i, j, k = 1, 2, ... , n$ when $i, j, \& k$ may (or may not - possibly in both cases)  equivalent?

$$\begin{align}\mathsf E(X^3) ~=~& \mathsf E({\sum}_{i,j,k} X_iX_jX_k) \\[1ex]~=~& {\sum}_i\mathsf E(X_i^3)+3{\sum}_{(i,j,k): i=j , j\neq k}\mathsf E(X_i^2X_k)+{\sum}_{(i,j,k):i\neq j,j\neq k,k\neq i}\mathsf E(X_iX_jX_k)\\[1ex]~=~& n\,\mathsf E(X_i^3)+3\,n\,(n-1)\,\mathsf E(X_i^2X_k)+n\,(n-1)\,(n-2)\,\mathsf E(X_iX_jX_k)\end{align}$$
Assuming these are independent and identically distributed random variables.
$$\begin{align}\mathsf E(X^3) ~=~& n\,\mathsf E(X_i^3)+3\,n\,(n-1)\,\mathsf E(X_i^2)\,\mathsf E(X_i)+n\,(n-1)\,(n-2)\,\mathsf E(X_i)^3\end{align}$$


text:
Q: Equation with table below I want a table to show the process involved in integration by parts. Here is what I have (from Equation with vertical arrow):
\documentclass{article}
\usepackage{mathtools}

\newcommand\vertarrowbox[3][6ex]{%
  \begin{array}[t]{@{}c@{}} #2 \\
  \left\uparrow\vcenter{\hrule height #1}\right.\kern-\nulldelimiterspace\\
  \makebox[0pt]{\normalsize#3}
  \end{array}%
 }
\begin{document}

\begin{align*}
\displaystyle \int x\exp(ax)\, dx\, &\vertarrowbox[8pt]{=}{%
\begin{tabular}{|l|l|}
    \hline
    $u=x$ & $du=dx$ \\\hline
    $dv=\exp(ax)\,dx$ & $v=\displaystyle\frac{1}{a}\exp(ax)$\\\hline
\end{tabular}} \frac{x}{a}\exp(ax)-\frac{1}{a}\int\exp(ax)\, dx\\
&=\frac{1}{a}\exp(ax)\left(x-\frac{1}{a}\right)+c.
\end{align*}
\end{document}

I want to align the vertical line of the table with the arrow, and also if possible change the arrow style (like -Latex style in tikz).

A: I propose this solution, using mathtools, makebox and makecell, with some manual adjustment:
\documentclass{article}
\usepackage{mathtools, nccmath}
\usepackage{makebox, array, makecell}

\begin{document}

\bgroup
\setcellgapes{2pt}\makegapedcells
\begin{align*}
 \int x\exp(ax)\, dx\, & = \frac{x}{a}\exp(ax)-\frac{1}{a}\int\exp(ax)\, dx\\
  & \makebox*{${}={}$}{$\uparrow$}\\[-0.5ex]
\MoveEqLeft[-0.2] \mathclap{\begin{array}{|l|l|}
    \hline
    u=x & du=dx \\\hline
    dv=\exp(ax)\,dx & v=\mfrac{1}{a}\exp(ax)\\\hline
\end{array}}\\
&=\frac{1}{a}\exp(ax)\biggl(x-\frac{1}{a}\biggr)+c.
\end{align*}
\egroup

\end{document}


text:
Q: Best way to embed Tumblr as your blog I have a domain (lets say www.domain.com) and I want one section of that to link to a tumblr blog (lets say www.domain.com/blog.php) I've seen the javascript option in Tumblr for embedding blogs and also tinkered with the API, but essentially, I need the blog to cover the following bases:

*

*Search engines must see my website and the tumblr account as the same
entity, so any SEO benefits of the blog are given to my site rather
than the tumblr account.

*It must be seamless for users. It must appear that everything is
in the same site.

*All features of tumblr (such as navigation and pagination) must be
present on the blog, not just the latest post.

It appears there are two ways of doing this; I can either create a page on my site that pulls in my tumblr feed, or forward that page on my site to my tumblr account (which would be skinned up to look identical to my site).
Which way would achieve all of the points outlined above? It if is the latter, would I need to change any DNS settings for my website?
Any help is greatly appreciated!

A: I think you'd see better results by pulling the content into your page. Any reasonable search engine will know it's been forwarded.
You should look into tumblr plugins for your blog software. For example, Wordpress has a Tumblr Widget.

A: All of those will end up with duplicated content for Google. I would create a subdomain blog.myurl.com using Tumblr custom domain name http://www.tumblr.com/docs/en/custom_domains.
This way you have myurl.com with your site and blog.myurl.com for tumblr.


text:
Q: CakePHP - trying to include related model data in find('all') So I am finding some data from one of my models:
// Models

class SubjectChange extends AppModel {

    public $belongsTo = array('Subject', 'User');

}

class Subject extends AppModel {

    public $hasMany = array('SubjectChange');

    public $belongsTo = array('SubjectGroup');

}

// Controller code to get all SubjectChanges

$subjectChanges = ClassRegistry::init('SubjectChange')->find('all', array(
    'contain' => array(
        'Subject.name',
        'User.full_name'
    )
));

This returns me each SubjectChange like this, which is great:
Array
(
    [SubjectChange] => Array
    (
        [id] => 35,
        [subject_group_id] => 5,
        [timestamp] => '2011-10-18 16:52:24'
    )

    [Subject] => Array
    (
        [name] => 'English'
    )

    [User] => Array
    (
        [full_name] => 'John Smith'
    )

)

But I want to add to that the name of the SubjectGroup, using the subject_group_id from the SubjectChange part.  The important thing to note here is that the SubjectChange model does not have any relationship to the SubjectGroup model, and that I can't get it from the Subject because it may have a different subject_group_id currently stored in the database.
I just want to do some sort of join in my query to get the SubjectGroup name from the SubjectChange subject_group_id that I have, to add this data to the above:
[SubjectGroup] => Array
    (
        [name] => 'My Group Name'
    )

Is this even possible?

A: Im going to do a complete answer then.
You have 3 way to do this:
the normal and the first one you should use is the associations declare in var hasMany, var BelongsTo, etc...
the second way is to do the first way on the fly
 $this->Leader->bindModel(
        array('hasMany' => array(
                'Principle' => array(
                    'className' => 'Principle',
                     //other attributes
                )
            )
        )
    );

simply use the bindModel function to do this, you may look more of this in the book
The third way is to do a force join in the find, for this you may look more in the book here
Maybe there is more options, but i don't remember them right now. Anyway this are the ones that are easy enough :)
Hope it helps you


text:
Q: Finding net torque on an object when all forces pass through a common point by finding the net force first The following text is from the book "Concepts of Physics" by Dr.H.C.Verma, from the chapter "Rotational Mechanics", under the topic "Torque of a Force about the Axis of Rotation":

If there are more than one forces $\vec{F_1},\vec{F_1},\vec{F_1},\dots$ acting on a body, one can define the total torque acting on the body about a given line.
To obtain the total torque, we have to get separately the torques of the individual forces and then add them.
$$\vec{\Gamma_{}}=\vec{r_1}\times\vec{F_1}+\vec{r_2}\times\vec{F_2}+\dots$$
You may be tempted to add the forces $\vec{F_1},\vec{F_1},\vec{F_1},\dots$ vectorially and then obtain the torque of resultant force about the axis. But that won't always work. Even if $\vec{F_1}+\vec{F_2}+\dots=0$, $\vec{r_1}\times\vec{F_1}+\vec{r_2}\times\vec{F_2}+\dots$ may not. However, if the forces act on the same particle, one can add the forces and then take the torque of the resultant.

(Emphasis mine)
The statement "But that won't always work" made me think of different cases where finding the net force to find the net torque would work or would not work. One of the cases for which I was unable to determine whether this would work or not is as follows:
If the forces $\vec{F_1},\vec{F_1},\vec{F_1},\dots$ act on different particles of a body in such a way that their lines of action intersect at a common point, is it possible to find the net torque by finding the net force $\vec{F_{}}$ then using $\vec{\Gamma_{}}=\vec{r_{}}\times\vec{F_{}}$ where $\vec{r_{}}$ is the position vector of the common point of the lines of action of the forces?

Please Note: The question - Net torque on an object when when all the forces pass through a common point is related to that of mine, but it doesn't address whether we could use the alternate method of finding the net torque. The question/answer there uses the conventional (always working) method to determine the net torque.

A:
But that won't always work. Even if $\vec{F_1}+\vec{F_2}+\dots=0$, $\vec{r_1}\times\vec{F_1}+\vec{r_2}\times\vec{F_2}+\dots$ may not.

Clearly this is true. If the sum of the forces being zero always meant the sum of the moments (torques) is also zero, you would be able, for example, to determine static equilibrium requirements for beams based only on the sum of the forces being zero. That is  not the case. The exception is for concurrent forces, i.e., forces that intersect at a common point.
Varignon's theorem states that the sum of the moments produced by any two concurrent forces with respect to a point is equal to the moment produced by the resultant with respect to the same point. Though initially stated for two concurrent forces, it applies to any number of concurrent forces.
So yes, if the forces are concurrent, it is possible to use the net force (resultant) and the vector $r$ from the point or axis about which you desire the total torque (moment) to the point where the concurrent forces intersect to find the total torque (moment).
Hope this helps.

A:
Even if $\vec{F_1}+\vec{F_2}+\dots=0$, $\vec{r_1}\times\vec{F_1}+\vec{r_2}\times\vec{F_2}+\dots$ may not.

One example, consider such lever system :

Weights cancels each other :
$$ W_U + W_D = 0, $$ however, net toque is
$$ \tau = WL_1 - W(L_1 + L_2) = -WL_2.
$$
So it is not zero and directed downwards, given that lever will not break at point A


text:
Q: How to get Min in C# Linq with join and group by? I want to build a Linq query for below scenario:
Table 1
PriceId
ProductId
ProductPrice
ProductHeight
ProductWeight
ProductType

Table 2
ProductId
ProductName

Task:
Select the cheapest prices and names for products where:

*

*productHeight = 5

*productWeight = 10

*productTypes: "abc", "xyz"

The end expected result is a list of objects like this:
ProductId
ProductName
TheCheapestPrice(the cheapest ProductPrice)

I created a SQL query to get this info, however I have a problem with
writing it in LINQ.
SQL query:
SELECT
    t1.ProductId,
    t2.ProductName,
    MIN(t1.ProductPrice) AS TheCheapestPrice
FROM
    Table1 t1
    INNER JOIN Table2 t2 ON t1.ProductId = t2.ProductId
WHERE
    t1.ProductHeight = 5
    AND
    t1.ProductWeight = 10
    AND
    t1.ProductType IN ('abc', 'xyz')
GROUP BY
    t1.ProductId,
    t2.ProductName

Can you please, help me to achieve the same result in LINQ?
So far I created such a LINQ, however I have a problem with getting minimum price:
from t1 in Table1
where
    productTypes.Contains(t1.ProductType)
    &&
    t1.ProductHeight == 5
    &&
    t1.ProductWeight == 10
join t2 in Table2 on t1.ProductId equals t2.ProductId
group new { t1.ProductId, t2.ProductName }
by new { t1.ProductId, t2.ProductName } into topPrices
select new
{
    ProductId = topPrices.Key.ProductId,
    ProductName = topPrices.Key.ProductName,
    TheCheapestPrice = ???
}

A: You will need to adjust your group to return the t1 record since you want to access its ProductPrice property:
group t1 by new { t1.ProductId, t2.ProductName } into topPrices

Then all you need is to perform the Min on the topPrices group, like this:
TheCheapestPrice = topPrices.Min(t => t.ProductPrice)

Link to working fiddle.
HTH


text:
Q: gnuplot: max and min values in a range I'm plotting some data with a different X range and I would like to change yrange according to the maximum and minimum value of the data in the current X range. When I use GPVAL_Y_MAX and GPVAL_Y_MIN, these values correspond to the maximum and minimum of the whole data, not just the data in the range.
For example, I have the following data:
1 3
2 5
3 8
4 20
5 30

I use the following script:
plot 'data.txt' u 1:2;
set xrange [1:3];
replot
set xrange [1:5];
replot

In the first plot I would like to set yrange in [3:8], but in the second plot the yrange sholud be [3:30]. If I use something like
set yrange [GPVAL_Y_MIN:GPVAL_Y_MAX]

GPVAL_Y_MIN and GPVAL_Y_MAX have the same value independently of the xrange.
Any solution?

A: Setting the yrange to GPVAL_DATA_Y_MIN:GPVAL_DATA_Y_MAX has the disadvantage of not using gnuplots autoscaling functionality which extends the ranges to the next tic.
In automatic plotting I therefore prefer the following
f(x)=sin(x)>0.5? 1:-1 #example function

set ytics 0.2
plot  1.01*f(x) # dummy plot to set GPVAL_*
set yrange [GPVAL_Y_MIN:GPVAL_Y_MAX]

plot f(x) # actual plot

This also works for data plots of course:
plot 'data.csv' u 1:(1.01*$2)
set yrange [GPVAL_Y_MIN:GPVAL_Y_MAX]
plot 'data.csv' u 1:2

A: The variables you want are GPVAL_DATA_Y_MIN and GPVAL_DATA_Y_MAX, which are the y-min/max of the data plotted in a certain range.  GPVAL_Y_MIN and GPVAL_Y_MAX are a little less useful generally because they tell you where the edges of the plot border are (in general these values extend a little beyond the GPVAL_DATA... variables because gnuplot leaves a little space between the data and the edge of the plot).
To take advantage of these variables you have to use the range specifiers to the plot command:
plot [1:3] 'data.txt'
set yr [GPVAL_DATA_Y_MIN:GPVAL_DATA_Y_MAX]
replot
...

By the way, the u 1:2 specification is redundant unless you want to remind yourself of which columns you are plotting, since plotting the first two columns as x and y is the gnuplot default.  If you don't want to replot to the same output terminal (which is not helpful in some terminals like eps where replotting makes a second page with the same plot), use this command sequence:
set terminal unknown
plot [1:3] 'data.txt'
set terminal <actual output terminal here>
set output 'output.trm'
plot [1:3][GPVAL_DATA_Y_MIN:GPVAL_DATA_Y_MAX] 'data.txt'

Note the use of the range specifier again, this time with a y range specified.  This is a little more compact than specifying with set yrange, but makes for a longer line of code.
If you have gnuplot 4.6.0 or higher, you can take advantage of the stats command to avoid replotting.  The stats command creates a bunch of handy variables
stats [1:3] 'data.txt'
plot [1:3][stats_min_y:stats_max_y] 'data.txt'

A slightly different command,
stats [1:3] 'data.txt'
plot [stats_min_x:stats_max_x][stats_min_y:stats_max_y] 'data.txt'

Would fill the plot in the x direction based on where the actual data lie.  For instance if you had data points at {(1.1, 3), (2, 4), (2.9,5)}, the x range would be set to [1.1:2.9].

A: I use it like this to define an x range for a funcion
plot [0:5] sin(10*x) + cos(3*x)

Also, you can set the range before ploting
set xrange [0:5]
plot sin(10*x) + cos(3*x)


text:
Q: How to set center point of rectangle after rotate and resize, keep old location I tried set center point after rotate and resize but something is going wrong.

var width = window.innerWidth;
    var height = window.innerHeight;

 $('#left').on('click', function(){

  rectGroup.rotate(-1);
  layer.draw();

 });

 $('#right').on('click', function(){

  rectGroup.rotate(1);
  layer.draw();

 });

    function update(activeAnchor) {
        var group = activeAnchor.getParent();

        var topLeft = group.get('.topLeft')[0];
        var topRight = group.get('.topRight')[0];
        var bottomRight = group.get('.bottomRight')[0];
        var bottomLeft = group.get('.bottomLeft')[0];
        var image = group.get('Image')[0];

        var anchorX = activeAnchor.getX();
        var anchorY = activeAnchor.getY();

        // update anchor positions
        switch (activeAnchor.getName()) {
            case 'topLeft':
                topRight.setY(anchorY);
                bottomLeft.setX(anchorX);
                break;
            case 'topRight':
                topLeft.setY(anchorY);
                bottomRight.setX(anchorX);
                break;
            case 'bottomRight':
                bottomLeft.setY(anchorY);
                topRight.setX(anchorX);
                break;
            case 'bottomLeft':
                bottomRight.setY(anchorY);
                topLeft.setX(anchorX);
                break;
        }

        image.position(topLeft.position());

        var width = topRight.getX() - topLeft.getX();
        var height = bottomLeft.getY() - topLeft.getY();
        if(width && height) {
            image.width(width);
            image.height(height);
        }
    }
    function addAnchor(group, x, y, name) {
        var stage = group.getStage();
        var layer = group.getLayer();

        var anchor = new Konva.Circle({
            x: x,
            y: y,
            stroke: '#666',
            fill: '#ddd',
            strokeWidth: 2,
            radius: 8,
            name: name,
            draggable: true,
            dragOnTop: false
        });

        anchor.on('dragmove', function() {
            update(this);
            layer.draw();
        });
        anchor.on('mousedown touchstart', function() {
            group.setDraggable(false);
            this.moveToTop();
        });
  anchor.on('dragstart', function() {
   img.oldSize = {w: img.getWidth(), h: img.getHeight()};
        });
        anchor.on('dragend', function() {
            group.setDraggable(true);
      setRectZoomPoint();
            layer.draw();
        });
        // add hover styling
        anchor.on('mouseover', function() {
            var layer = this.getLayer();
            document.body.style.cursor = 'pointer';
            this.setStrokeWidth(4);
            layer.draw();
        });
        anchor.on('mouseout', function() {
            var layer = this.getLayer();
            document.body.style.cursor = 'default';
            this.setStrokeWidth(2);
            layer.draw();
        });

        group.add(anchor);
    }

 function setRectZoomPoint(){

  var dif = {x: img.x(), y: img.y()};
  rectGroup.move({x: dif.x, y: dif.y});
  rectGroup.getChildren().each(function(child){child.move({x: -dif.x, y: -dif.y})});

  //set center point
  rectGroup.move({x: -img.oldSize.w / 2, y: -img.oldSize.h / 2});
  rectGroup.move({x: img.getWidth() / 2, y: img.getHeight() / 2});
  rectGroup.offset({x: img.getWidth() / 2, y: img.getHeight() / 2});
  rectGroup.get('.centerPoint')[0].position({x: img.getWidth() / 2, y: img.getHeight() / 2});
  layer.draw();

 }
 var angle = 0;
    var stage = new Konva.Stage({
        container: 'container',
        width: width,
        height: height
    });

    var layer = new Konva.Layer();
    stage.add(layer);

    var img = new Konva.Image({
        width: 200,
        height: 137
    });
 img.oldSize = {w: 200, h: 137};

    var rectGroup = new Konva.Group({
        x: 180,
        y: 50,
        draggable: true
    });
    layer.add(rectGroup);
    rectGroup.add(img);
    addAnchor(rectGroup, 0, 0, 'topLeft');
    addAnchor(rectGroup, 200, 0, 'topRight');
    addAnchor(rectGroup, 200, 138, 'bottomRight');
    addAnchor(rectGroup, 0, 138, 'bottomLeft');
 addAnchor(rectGroup, 100, 69, 'centerPoint');

    var imageObj1 = new Image();
    imageObj1.onload = function() {
        img.image(imageObj1);
  setRectZoomPoint();
        layer.draw();
    };
    imageObj1.src = 'https://t4.ftcdn.net/jpg/00/78/73/53/240_F_78735333_o3qJe4bT5ciwldLIjVDulFKrDAV3jGYO.jpg';
<button type="button" id='left'>left</button>
 <button type="button" id='right'>right</button>

A:

var width = window.innerWidth;
    var height = window.innerHeight;

 $('#left').on('click', function(){

  rectGroup.rotate(-1);
  layer.draw();

 });

 $('#right').on('click', function(){

  rectGroup.rotate(1);
  layer.draw();

 });

    function update(activeAnchor) {
        var group = activeAnchor.getParent();

        var topLeft = group.get('.topLeft')[0];
        var topRight = group.get('.topRight')[0];
        var bottomRight = group.get('.bottomRight')[0];
        var bottomLeft = group.get('.bottomLeft')[0];
        var image = group.get('Image')[0];

        var anchorX = activeAnchor.getX();
        var anchorY = activeAnchor.getY();

        // update anchor positions
        switch (activeAnchor.getName()) {
            case 'topLeft':
                topRight.setY(anchorY);
                bottomLeft.setX(anchorX);
                break;
            case 'topRight':
                topLeft.setY(anchorY);
                bottomRight.setX(anchorX);
                break;
            case 'bottomRight':
                bottomLeft.setY(anchorY);
                topRight.setX(anchorX);
                break;
            case 'bottomLeft':
                bottomRight.setY(anchorY);
                topLeft.setX(anchorX);
                break;
        }

        image.position(topLeft.position());

        var width = topRight.getX() - topLeft.getX();
        var height = bottomLeft.getY() - topLeft.getY();
        if(width && height) {
            image.width(width);
            image.height(height);
        }
    }
    function addAnchor(group, x, y, name) {
        var stage = group.getStage();
        var layer = group.getLayer();

        var anchor = new Konva.Circle({
            x: x,
            y: y,
            stroke: '#666',
            fill: '#ddd',
            strokeWidth: 2,
            radius: 8,
            name: name,
            draggable: true,
            dragOnTop: false
        });

        anchor.on('dragmove', function() {
            update(this);
            layer.draw();
        });
        anchor.on('mousedown touchstart', function() {
            group.setDraggable(false);
            this.moveToTop();
        });
  anchor.on('dragstart', function() {
   img.oldSize = {w: img.getWidth(), h: img.getHeight()};
        });
        anchor.on('dragend', function() {
            group.setDraggable(true);
   setRectZoomPoint();
            layer.draw();
        });
        // add hover styling
        anchor.on('mouseover', function() {
            var layer = this.getLayer();
            document.body.style.cursor = 'pointer';
            this.setStrokeWidth(4);
            layer.draw();
        });
        anchor.on('mouseout', function() {
            var layer = this.getLayer();
            document.body.style.cursor = 'default';
            this.setStrokeWidth(2);
            layer.draw();
        });

        group.add(anchor);
    }

 function setRectZoomPoint(){

  // setting position of rectangle and anchors to 0,0
  var dif = {x: img.x(), y: img.y()};
  rectGroup.getChildren().each(function(child){child.move({x: -dif.x, y: -dif.y})});

  var radian = toRadians(-rectGroup.rotation());
  var absPos = {x: rectGroup.x(), y: rectGroup.y()};
  //old CenterPoint thats before resize
  var oldCP = {
   x: absPos.x - absPos.x * Math.cos(radian) - absPos.y * Math.sin(radian),
   y: absPos.y - absPos.y * Math.cos(radian) + absPos.x * Math.sin(radian)
  };
  //new CenterPoint thats after resize without angle
  var newCP = {
   x: rectGroup.x() + img.getWidth() / 2 - img.oldSize.w / 2 + dif.x,
   y: rectGroup.y() + img.getHeight()/ 2 - img.oldSize.h / 2+ dif.y};
  //must calculate real central point with angle
  var realCP = {
   x: oldCP.x + (newCP.x * Math.cos(radian) + newCP.y * Math.sin(radian)),
   y: oldCP.y + (newCP.x * -Math.sin(radian) + newCP.y * Math.cos(radian))
  }

  rectGroup.position({x: realCP.x, y: realCP.y});
  rectGroup.offset({x: img.getWidth() / 2, y: img.getHeight() / 2});
  rectGroup.get('.centerPoint')[0].position({x: img.getWidth() / 2, y: img.getHeight() / 2});
  layer.draw();

 }
    var stage = new Konva.Stage({
        container: 'container',
        width: width,
        height: height
    });

    var layer = new Konva.Layer();
    stage.add(layer);

    var img = new Konva.Image({
        width: 200,
        height: 137
    });
 img.oldSize = {w: 200, h: 137};

    var rectGroup = new Konva.Group({
        x: 300,
        y: 200,
        draggable: true
    });
    layer.add(rectGroup);
    rectGroup.add(img);
    addAnchor(rectGroup, 0, 0, 'topLeft');
    addAnchor(rectGroup, 200, 0, 'topRight');
    addAnchor(rectGroup, 200, 138, 'bottomRight');
    addAnchor(rectGroup, 0, 138, 'bottomLeft');
 addAnchor(rectGroup, 100, 69, 'centerPoint');

    var imageObj1 = new Image();
    imageObj1.onload = function() {
        img.image(imageObj1);
  setRectZoomPoint();
        layer.draw();
    };

 function toRadians(degrees) {
  return degrees * (Math.PI / 180)
 };

 function toDegrees(radians) {
  return radians * (180 / Math.PI)
 };
    imageObj1.src = 'https://t4.ftcdn.net/jpg/00/78/73/53/240_F_78735333_o3qJe4bT5ciwldLIjVDulFKrDAV3jGYO.jpg';
<button type="button" id='left'>left</button>
 <button type="button" id='right'>right</button>

The problem has been solved by rotation formula in canvas coordinate system.


text:
Q: Save structure of an object Is there a possibility to seriallize the structure of an object in R. By seriallization I mean something similar to utils::str() or base::structure() function. That functions work very good, but they just print the structure without an option to assign it to a variable.
I tried to do that using a recursion (just to get classes):
x <- list("aaa",
          c("asd", "test", "asdfre"),
          b = list("bbbb"),
          c1 = as.list(c("l1", "l2")),
          c = list("aaa",
                   b = "bbbbb",
                   list("aaa",
                        s = c(123, 122)),
                   l = list(a = list("aa",
                                     "bb"),
                            b = c(12, 123))))

getStructure <- function(x){
  if(!is.list(x)){
    return(list(class(x)))
  } else{
      sapply(x, function(x) { if(!is.null(x)) getStructure(x) })
  }
}

getStructure(x)

But it's not working in a similar way like str() and structure() functions work.

A: capture.output is the general way to, well, capture anything that's normally printed to the console.
x = capture.output(str(mtcars))

A: What are you trying to accomplish?  Do you need to send the data in some kind of text format?  If not--if you just need to save the object to disk so that it can be loaded into R later--then you can use save:
foo <- list(x=c(1, 2, 3), y=c("a", "b", "c"))
save(foo, file="foo.rdata")

Now exit R and restart it.
load("foo.rdata")
foo
; $x
; [1] 1 2 3
;
; $y
; [1] "a" "b" "c"


text:
Q: What is Hunters for Hire? I just StreetPassed with someone that had Monster Hunter Tri Ultimate and I got an alert on my Hunters for Hire screen. Blindly pressing buttons, I sent my fellow hunter(s) on a quest to deliver raw meat for 80z. What does Hunters for Hire do? Is it another way to get items like the farm or fishery?

A: When you receive a players Guild Card you'll be given the ability to send them out on quests via "Hunter For Hire." If the hunter is successful you'll be rewarded with a variety of items, some of which appear to only be accessible via Hunters for Hire (like the Blossom Cricket).
By talking to the Guild Master in Tanzia Port you can change the type of quests  the hunters will go on, rewarding you with different items. The options available to you are Quest Rank, which allows you to choose if you want hunters performing Low Rank, High Rank, or G-Rank quests; Locale, which allows you to choose a region for the quest; and Target, which allows you choose the quest type (either Small Monsters, Large Monsters, or Gathering). It's also possible to just choose any for any of the above options, which won't put any filter on the type of quests presented.
You can increase the chance of success by hiring additional hunters to help on the quest. These extra hunters are just generic hunters, and don't require you to have any additional guild cards to do. You'll get the option when you go to hire the hunter.


text:
Q: Replace a date in file to another date using sed not workiing I need to replace a date in file on device to another date . But the following sed command for string replace  is not working .
path= "/var/local"
last_date=d("cat /var/local")-----06/24/18 date i
previous_date=(datetime.strptime(last_date, '%m/%d/%y')-timedelta(1)).strftime("%m/%d/%y")--output --06/23/18
"sed -i 's/%s/%s/g' %s" % (last_date, previous_date, file)

This Sed give output as 24/24/18. It is not replacing the complete date

A: It looks like your problem is that you're effectively running the following command:
sed -i "s/06/24/18/06/23/18/g" /var/local

As you can see, the problem is that you're not escaping the slashes in your regex.
The shortest fix would be to call .replace("/", "\\/") on both last_date and previous_date in your python code.
However, since you're already using Python, you might do better to only use pure Python, and not use sed at all.


text:
Q: Can nginx serve SSH and HTTP(S) at the same time on the same port? Context
I have a personal server that I use for the web. I sometimes need to SSH/SFTP to it.
Disclamer: I have very little experience with nginx internals.
Problem
This morning, I figured out that the free wifi in a well-know cafe chain was blocking SSH (actually, they are blocking anything that's not on 80/443). But when I need SSH, I need it, so I looked for ways to share SSH and HTTPS on the same port.
What I looked at
I have looked at a few possible solutions that can run on port 443:

*

*SSHL: a SSH/OpenVPN/HTTPS multiplexer;

*OpenVPN: a VPN solution has a built-in multiplexer for OpenVPN and HTTPS;

*HAProxy: a webserver/load balancer can also multiplex everything.

All of these seem pretty straight-forward but I don't really like the fact of adding layers and complexity and possibly slowing things down just in the unlikely event that I need to SSH on 443.
Putting nginx into the mix
I know that nginx already supports raw TCP streams handling. So I was wondering if I could use that on port 443 too directly in nginx. The idea being that nginx could choose to use the http module if it recognizes HTTP(S) or stream for everything else.
Questions
In that context, I have two questions:

*

*Is nginx even capable of doing such a distinction? (I am not even sure I would be able to listen on port 443 in both the http and the stream block at the same time.)

*If so, would there be any blatant performance issue with that setup? (I am thinking about transfer speed with SFTP for instance, not really SSH per se.)

A: Or, you could proxytunnel ssh through your nginx with HTTP/S connection
Take a look: proxytunnel

A: Since nginx version 1.15.2 added new variable $ssl_preread_protocol. And in official blog added post about how to use this variable for multiplexing HTTPS and SSH on the same port
https://www.nginx.com/blog/running-non-ssl-protocols-over-ssl-port-nginx-1-15-2/
Example of configuring SSH(by default) and HTTPS:
stream {
    upstream ssh {
        server 192.0.2.1:22;
    }

    upstream web {
        server 192.0.2.2:443;
    }

    map $ssl_preread_protocol $upstream {
        default ssh;
        "TLSv1.2" web;
    }

    # SSH and SSL on the same port
    server {
        listen 443;

        proxy_pass $upstream;
        ssl_preread on;
    }
}

A: This question is slightly related to another one I've answered a while ago:
https://stackoverflow.com/questions/34741571/nginx-tcp-forwarding-based-on-hostname/34958192#34958192
Yes, it is technically possible to differentiate between ssh and https traffic, and route the connection appropriately; however, nginx currently doesn't have such support, to my knowledge.
However, what you could do is simply run sshd directly on the https port in addition to the ssh one (/usr/sbin/sshd -p 22 -p 443), and/or use the firewall and/or port knocking in order to differentiate where connections to port 443 get routed to.

A: You could setup an iptables rule to forward connections from your well known cafe on port 443 to port 22. Alternatively bounce the traffic off a port relay elsewhere on the internet, changing the pirt number.
Just trying to solve the problem with nginx isn't going to work.

A: There exists unmaintained patch for nginx to support protocol multiplexing for SSH and HTTPS:
https://github.com/shawnl/nginx-ssh
However it is not maintained anymore, non-nginx project which supports what you are looking for is:
https://github.com/yrutschle/sslh
I suggest you use SSLH infront of your nginx and ssh server.

A: I have a working configuration tunneling ssh over tls on port 443, using the nginx stream module.
I also do XMPP over TLS and normal HTTP on the same port.
I do the mutliplexing via ALPN.
(You need nginx > 1.13.10 to use the ssl_preread module with alpn
http://nginx.org/en/docs/stream/ngx_stream_ssl_preread_module.html#ssl_preread)
My configuration uses the docker version of nginx, but it should also work without docker.
stream {
    # check ALPN for xmpp client or server and redirect to local ssl termination endpoints
    map $ssl_preread_alpn_protocols $ssl_multiplexer {
        "xmpp-client"     127.0.0.1:5422;
        "xmpp-server"     127.0.0.1:5469;
        "identifyssh"     127.0.0.1:8822;
        default           127.0.0.1:8443;
    }

    server {
        listen 443;
        ssl_preread on;
        proxy_pass $ssl_multiplexer;
        proxy_protocol on;
        set_real_ip_from  172.18.0.0/32;
    }

    # ssl termination for c2s connections
    server {
        listen 5422 ssl proxy_protocol;
        # ... <- tls keys and options here
        proxy_ssl off;
        proxy_pass ejabberd:5222;
    }

    # ssl termination for s2s connections
    server {
        listen 5469 ssl proxy_protocol;
        # ... <- tls keys and options here
        proxy_ssl off;
        proxy_pass ejabberd:5269;
    }

    # ssl termination for ssh connections
    server {
        listen 8822 ssl proxy_protocol;
        # ... <- tls keys and options here
        proxy_ssl off;
        proxy_pass yourserver:22;
    }
}

If you want to use the XMPP stuff you have to add some SRV records to point to your servers 443 port, see https://xmpp.org/extensions/xep-0368.html
If you want to connect to your ssh server you have to wrap your ssh session in a ssl session that sends the ALPN string you defined in your stream config. I used "identifyssh" in the example above. You can use anything, but try to not collide with the official defined names:
https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids
To start the ssh session from your client to your prepared server use:
ssh you@yourserver -o "ProxyCommand openssl s_client -alpn identifyssh -ign_eof -connect yourserver:443"

And you should be connected.
I should also note, that I use the proxy_protocol to keep the clients headers and IP-address while passing to my backends.
Your normal http server configured in the http {} section should take care of this:
server {
  listen 8443 ssl proxy_protocol;
  # ...
}

The best thing is, that you don't need tools like sslh, stunnel, proxytunnel or others to make this work. You only need a newer nginx and openssl.
Hope this helps somebody. It would helped me digging into that stuff.

A: As far as I know, currently nginx doesn't support it.
In SSH-2, client will send a hello message to server:

When the connection has been established, both sides MUST send an identification string.  This identification string MUST be
 SSH-protoversion-softwareversion SP comments CR LF

In TLS 1.2, clients need to send first:
  Client                                                Server

  ClientHello                   -------->
                                                   ServerHello
                                            [ChangeCipherSpec]
                                <--------             Finished
  [ChangeCipherSpec]
  Finished                      -------->
  Application Data              <------->     Application Data

Clients can use this information for implementation.

A: Since Nginx Version 1.9.0,NGINX support ngx_stream_core_module module, it should be enabled with the --with-stream. When stream module is enable they are possible to ssh protocol tcp proxy
stream {
upstream ssh {
    server 192.168.1.12:22;
}
    server {
    listen        12345;
    proxy_pass    ssh;

} }

https://www.nginx.com/resources/admin-guide/tcp-load-balancing/

A: Maybe you can use nginScript to implement your own multiplexer? See here for an introduction: https://www.nginx.com/blog/introduction-nginscript/


text:
Q: angular 2 http withCredentials I'm am trying to use withCredentials to send a cookie along to my service but can't find out how to implement it.
The docs say "If the server requires user credentials, we'll enable them in the request headers" With no examples.
I have tried several different ways but it still will not send my cookie.
Here is my code so far.
private systemConnect(token) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('X-CSRF-Token', token.token);
    let options = new RequestOptions({ headers: headers });
    this.http.post(this.connectUrl, { withCredentials: true }, options).map(res => res.json())
    .subscribe(uid => {
        console.log(uid);
    });
}

A: Creating an Interceptor would be good idea to inject stuff into header across the application. On the other hand, if you are looking for a quick solution that needs to be done on a per request level, try setting withCredentials to true as below
const requestOptions = {
 headers: new HttpHeaders({
  'Authorization': "my-request-token"
 }),
 withCredentials: true
};

A: Try to change your code like this
let options = new RequestOptions({ headers: headers, withCredentials: true });

and
this.http.post(this.connectUrl, <stringified_data> , options)...

as you see, the second param should be data to send (using JSON.stringify or just '') and all options in one third parameter.

A: Starting with Angular 4.3, HttpClient and Interceptors were introduced.
A quick example is shown below:
@Injectable()
export class WithCredentialsInterceptor implements HttpInterceptor {

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
            withCredentials: true
        });

        return next.handle(request);
    }
}

constructor(
      private http: HttpClient) {

this.http.get<WeatherForecast[]>('api/SampleData/WeatherForecasts')
    .subscribe(result => {
        this.forecasts = result;
    },
    error => {
        console.error(error);
    });

Remember to provide the interceptor to your app module, as the article says:

In order to activate the interceptor for our application we need to provide it to the main application module AppModule in file app.module.ts:

Your @NgModule will need to include this in its providers:
  ...
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: WithCredentialsInterceptor,
    multi: true
  }],
  ...


text:
Q: Query pandas data frame with `or`b boolean? I have a simple pandas data frame.
import pandas as pd
x = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
y = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600]
users =['mark', 'mark', 'mark', 'rachel', 'rachel', 'rachel', 'jeff', 'jeff', 'jeff', 'lauren', 'lauren', 'lauren']

df = pd.DataFrame(dict(x=x, y=y, users=users)

I want to keep certain rows of the data frame. Let's say all "rachels" and "jeffs". I tried df.query:
df=df.query('users=="rachel"' or 'users=="jeff"')

The result is a data frame only with users=="rachel". Is there a way to combine queries?

A: The standard way would be to use the bitwise or operator |. For a clear explanation of why, I'd suggest checking out this answer. You also need to use parentheses around each condition due to Python's order of evaluation.
df[(df.users == 'rachel') | (df.users == 'jeff')]
    users   x    y
3  rachel  30  200
4  rachel   5  300
5  rachel  10  300
6    jeff  20  400
7    jeff  30  400
8    jeff   5  500

Using query, you can still just use the or operator:
df.query("users=='rachel' | users=='jeff'")
    users   x    y
3  rachel  30  200
4  rachel   5  300
5  rachel  10  300
6    jeff  20  400
7    jeff  30  400
8    jeff   5  500

A: another way is :
df=df.query('users=="rachel"').append(df.query('users=="jeff"'))


text:
Q: I found this error (Sending 'const uint8_t (*)[kStreamChunkSize]' to parameter of type 'void *' discards qualifiers)? I have one method in NSData file.
 - (void)getBytes:(void *)buffer;

But when i used this method like..
  const uint8_t bytes [kStreamChunkSize];
  [chunk getBytes:&bytes];

Then its give this error
Sending 'const uint8_t (*)[kStreamChunkSize]' to parameter of type 'void *' discards qualifiers
How to solve this error. Please help me.

A: It discards the const qualifier and that's a problem. getBytes: gets the bytes by writing them into the array passed in. However, you can't write in an array of const bytes (doing so invokes undefined behavior), that's what const means. Change the declaration of your array to
uint8_t bytes[kStreamChunkSize];

Furthermore, don't pass a pointer to the array - if you simply use its name without the & operator, it will decay into a pointer to its first element anyway.


text:
Q: Firefox media metadata/control support on macOS As you can see on screenshot, Firefox doesn't provide thumbnail, video duration, and doesn't support seeking. Also the same in Touch Bar.
With Safari it looks like this.
Tested on this page and on YouTube.
So, is this a bug in my case, or this feature is really unsupported by Firefox?


text:
Q: Search is not working with filter toolbar in JQGrid I am facing issue while loaidng the data in JQGrid at a later stage in place of at the time of ceating grid. I am using filter toolbar for search.
following is the code I am using:
Creating Grid

jQuery("#list").jqGrid({
            datatype: 'local',
            colNames: [my col names],
            colModel: [my col model],
             jsonReader: {
                root: "rows",
                page: "page",
                total: "total",
                //records: "records",
                repeatitems: false
            },
            height: 300,
            viewrecords: true,
            gridComplete: this.onGridComplete,
            ondblClickRow: this.rowDblClick,
            onSelectRow: this.selectRow,
            headertitles: false,
            loadtext: "Loading...",
            sortable: true,
            altRows: true,
            loadonce: true,
            rowNum: 100,
            pager: '#pager',
            root: "rows",
            rowList: [100, 200, 300],
            pagination: true,
            ignoreCase: true
        })

Load data at later stage

if(gridDataStr != "none") // gridDatStr has data
        {
            grid.initialize(); // create the grid
            var myjsongrid = JSON.parse(gridDataStr);
            grid.table[0].addJSONData(myjsongrid);
            grid.table.jqGrid('setGridParam',{datatype:'json', data:myjsongrid}).trigger('reloadGrid');
            if (myjsongrid["rows"].length > 1)
            {
                grid.table.filterToolbar({
                    stringResult: true,
                    searchOnEnter: false
                    });
            }
        }

However if I load the same data at the time of creating the grid with datatype:json and using some valid url, searching is working well.
Any suggestions?

A: The method addJSONData can not be used to work with the jqGrid having the 'local' datatype.
You can use addRowData and to use localReader instead of jsonReader or set data parameter of jqGrid with respect of setGridParam method and then call jQuery("#list")[0].refreshIndex() (see here) and reload the grid.


text:
Q: read json data with resource in angularjs I read json data with $resource and I am so confused is it result just show first word
ex: json data's value is function1 and result will be f ?
there is my code
experiment.directive('groupsControl', function(){
return {
  restrict: 'E',
  replace: true,
  transclude: false,
  template: '

'
}})

.directive('sectionControl', function(){
return {
  restrict: 'E',
  replace: true,
  transclude: false,
  scope: { items:'=sections'},

  template: '
'+
            '
',
    link: function(scope, element, attrs) {
    scope.getIncludeFile = function(section) {
        return section.data + ".html";
    }
  }
}})

there is my json data
{
"name": "test", "children":[
{"data": "function1" },
{"data": "function2" },
{"data": "function3" }  ]}

A: The template in groupsControl directive should be:
template: '

'


text:
Q: retrieve value inside certain pattern i have a pattern as like this
"The world is #bright# and #beautiful#"

i need to retrieve the string "bright","beautiful" inside # # .. any pointers

My solution (thanks to Bolu):
string s = "The world is #bright# and #beautiful#";
    string[] str = s.Split('#');
    for (int i = 0; i <= str.Length - 1; i++)
    {
        if (i % 2 != 0)
        {
            Response.Write(str[i] + "<br />");
        }
    }

A: If all you want is the string inside ##, then no need for regex, just use string.Split:
string rawstring="The world is #bright# and beautiful";
string[] tem=rawstring.Split('#');

After that, all you need is to get the even item (with index: 1,3,5....) from the string[] tem

A: As long as you can't have nested #...# sequences, #([^#]+)# will work, and will capture the content between #'s as the first backreference.
Explanation:
#        match a literal # character
(        open a capturing group
  [^     open a negated character class
     #   don't match # (since the character class is negated)
  ]+     close the class, match it one or more times
)        close the capturing group
#        match a literal # character

A: Check out the Match object:
var match = Regex.Match(yourstring, @"The world is #(.*)# and beautiful")
var bright = match.Groups[1]

Of course this breaks down when you have more than two #'s in your string. Then you probably want to do a non-greedy match. This can be done with the regex "#(.*?)#". This will match the shortest string between two sharps and still have the contents in the first group.

A: You need to set up a Capturing Group by wrapping the part you want to capture in round brackets () and optionally specifying a name for the capture:
Regex r = new Regex(@"#([^#]+?)#");

which can be accessed by using this code:
Match m = r.Match("The world is #bright# and beautiful");
string capture = m.Groups[1];

Or with a named parameter:
Regex r = new Regex(@"#(?<mycapture>[^#]+?)#");

which can be accessed by using this code:
Match m = r.Match("The world is #bright# and beautiful");
string capture = m.Groups["mycapture"];


text:
Q: Why does not accept messages? Under WinForms works and so no.
In the future, I want to show, somehow, all posts in a row. But until this stage is not reached, because now even a single message is not accepted.
public class MainActivity : Activity
{
    public string mess;

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);
        StartListening ();

        Button bt = FindViewById<Button>(Resource.Id.button1);
        bt.Click += delegate { start();};
        // Get our button from the layout resource, and attach an event to it
    }

    public void start()
    {
        TextView text = FindViewById<TextView> (Resource.Id.textView1);

        StartListening();
        text.Text = mess;
    }

    private readonly UdpClient udp = new UdpClient(45000);

    public void StartListening()
    {
        this.udp.BeginReceive(Receive, new object());
    }

    public void Receive(IAsyncResult ar)
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Any, 45000);
        byte[] bytes = udp.EndReceive(ar, ref ip);

        mess = Encoding.ASCII.GetString(bytes);
        StartListening();
    }
}

A: If you debug your code you'll see what happens when! So try this and I trust you'll be surprised how easy it is to solve your problem.
Anyway, the way you set the message is timed incorrectly. Try this code instead. It removes the message state (functional programming) and sets the message after it has been received.
public class MainActivity : Activity
{
    private readonly UdpClient udp = new UdpClient(45000);

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);
        StartListening();
        Button bt = FindViewById<Button>(Resource.Id.button1);
        bt.Click += delegate { StartListening(); };
    }

    public void StartListening()
    {
        this.udp.BeginReceive(Receive, new object());
    }

    public void Receive(IAsyncResult ar)
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Any, 45000);
        byte[] bytes = udp.EndReceive(ar, ref ip);
        DisplayMessage(Encoding.ASCII.GetString(bytes));
        StartListening();
    }

    public void DisplayMessage(string message)
    {
        FindViewById<TextView>(Resource.Id.textView1).Text = message;
    }
}


text:
Q: Magento Products Ordered Report results in white screen When I run Reports > Products > Products Ordered and set a timeframe for the past month with "Day" selected in the Show By drop-down, the report seems to start running, but then hangs for a long time and then just freezes on a blank white screen.
I checked the web server error log, and an error was showing that the PHP memory of 256mb had run out, so I decided to increase it up to 512mb, and then 900mb.  Despite the increases, the Reports still hung for a long time and eventually landed on the blank screen again, though I no longer saw the PHP memory error in the log.
Does anyone have an idea why this particular style of the report would cause problems?  I don't have issues generating other types of reports, and if I do the same report by "Year", or even still leave it at "Day" and only do a few days back, it works fine.  It just seems that once the time span is increased while setting to "Day", it hangs and freezes.  Any help on figuring out the issue is greatly appreciated, thanks!

A: This is most likely a server timeout of some kind. Either php max_execution_time or apache/nginx timeouts. I suggest checking the sever logs.


text:
Q: Will this NSString no longer exist?    NSString *string=[temp objectAtIndex:row];
   [temp removeObjectAtIndex:row];

The object from which string is created no longer exists; I assume this syntax is straight assignment, thus string should no longer exist, right?
So either I'd use stringWithFormat to create a new string from the object, or send retain to string to be safe, is this correct reasoning?

A: Assuming you aren't using ARC or garbage collection, yes, your reasoning about the object's memory management is correct†. However, you wouldn't want to use stringWithFormat:. That expects a format string, and it can fail horribly if you pass something that isn't specifically meant to be one. You could use one of:

*

*stringWithString: if you don't want ownership

*copy if you just want to make sure you have a safe reference to the string (optionally with autorelease if you don't plan on keeping the reference around long-term)

*retain if you definitely want to keep the same object — even if it's a mutable string — and do want ownership (You probably don't want this option, as the main difference from copy is that the string could potentially mutate underneath you)
† By "correct", I mean you're right that you shouldn't assume anything about the object's lifecycle beyond that point. It might still be alive, but it's technically not a safe assumption. Thought it worth mentioning because some people aren't 100% clear on this point.


text:
Q: Create a NSManagedObject and inject into a SwiftUI view which is automatically added to the navigation stack My main app screen displays a list of objects (Patients in this instance). I want to allow the user to add a new patient by tapping a toolbar button which allows them to add the relevant details.
Implementing an edit view was easy enough and editing existing patients works without issue. It is also easy enough to add a new patient in the list view without any automatic modal display of, or navigation to, the edit view. The downside of course is that the user will need to manually go through an additional sequence of steps to edit the newly added object which isn't very user friendly.
It's not a problem if I use MVVM but I'm trying to do it using Apple's own "recommended" approach with property wrappers around the MOC, etc. As I can't access the MOC until initialisation of the view is complete, the simplest approach (creating a new Patient if the view isn't provided with one) isn't possible. The current tactic (creating the new object in the parent view) leads to state inconsistency and some very weird behaviour with the NavigationLink being triggered whenever you try to edit the fields in the child.
I'm sure I'm making this unnecessarily complex and am still stuck in an imperative mindset but some guidance would be helpful.
struct PatientsView: View {
    @EnvironmentObject var dataController: DataController
    @Environment(\.managedObjectContext) var managedObjectContext
    static let tag = "patients"

    @State private var navLinkTag: Int? = 0

    let patients: FetchRequest<Patient>

    init() {
        patients = FetchRequest(entity: Patient.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Patient.creationDate, ascending: false)])
    }

    var body: some View {
        NavigationView {
            List {
                ForEach(patients.wrappedValue) { patient in
                    PatientRow(patient: patient)
                }
                .onDelete { offsets in
                    for offset in offsets {
                        let item = patients.wrappedValue[offset]
                        dataController.delete(item)
                    }
                }
            }
            .navigationTitle("Patients")
            .toolbar {
                ToolbarItem {
                    Button(action: {
                        navLinkTag = 1
                    }, label: {
                            Image(systemName: "plus")
                    })
                    .background(
                        NavigationLink(
                            destination: EditPatientView(patient: newPatient()),
                            tag: 1,
                            selection: $navLinkTag,
                            label: { EmptyView() })
                    )
                }
            }
        }
    }

    private func newPatient() -> Patient {
        let patient = Patient(context: managedObjectContext)
        patient.creationDate = Date()
        patient.name = "New patient"

        dataController.save()

        return patient
    }
}

struct PatientRow: View {
    @ObservedObject var patient: Patient

    var body: some View {
        HStack {
            NavigationLink(destination: PatientActivityView(patient: patient)) {
                VStack {
                    HStack {
                        Text(patient.patientName)
                        Text(patient.patientOwnerName)
                            .bold()
                        Spacer()
                    }

                    HStack {
                        Text(patient.patientSpecies)
                        Text(patient.patientSex)
                        Text(patient.age)
                        Spacer()
                    }
                    .font(.caption)
                }
            }
        }
    }
}

struct EditPatientView: View {
    @EnvironmentObject var dataController: DataController
    @Environment(\.managedObjectContext) var managedObjectContext

    @State var owner: String
    @State var name: String
    @State var species: String
    @State var dob: Date
    @State var sex: String

    let patient: Patient

    init(patient: Patient) {
        self.patient = patient

        _owner = State(wrappedValue: self.patient.patientOwnerName)
        _name = State(wrappedValue: self.patient.patientName)
        _species = State(wrappedValue: self.patient.patientSpecies)
        _sex = State(wrappedValue: self.patient.patientSex)
        _dob = State(wrappedValue: self.patient.patientDateOfBirth)
    }

    var body: some View {
        Form {
            Section(header: Text("Identity")) {
                TextField("Name", text: $name.onChange(update))
                TextField("Owner", text: $owner.onChange(update))
            }

            Section(header: Text("Signalment")) {
                TextField("Species", text: $species.onChange(update))
                TextField("Sex", text: $sex.onChange(update))
                DatePicker("Date of birth",
                           selection: $dob.onChange(update),
                           in: ...Date(),
                           displayedComponents: .date)
                    .datePickerStyle(CompactDatePickerStyle())                }
        }
        .navigationTitle("Edit Patient")
    }

    private func update() {
        patient.name = name
        patient.owner = owner
        patient.species = species
        patient.sex = sex
        patient.dateOfBirth = dob
    }
}

A: Your problem is new managed objects and edited ones are handled differently. I would have separate views:
struct EditPatientView: View {
    @EnvironmentObject var dataController: DataController
    @Environment(\.managedObjectContext) var managedObjectContext

    @State private var owner: String
    @State private var name: String
    @State private var species: String
    @State private var dob: Date
    @State private var sex: String

    let patient: Patient

    init(patient: Patient) {
        self.patient = patient

        _owner = State(wrappedValue: self.patient.patientOwnerName)
        _name = State(wrappedValue: self.patient.patientName)
        _species = State(wrappedValue: self.patient.patientSpecies)
        _sex = State(wrappedValue: self.patient.patientSex)
        _dob = State(wrappedValue: self.patient.patientDateOfBirth)
    }

    var body: some View {
        Form {
            Section(header: Text("Identity")) {
                TextField("Name", text: $name.onChange(update))
                TextField("Owner", text: $owner.onChange(update))
            }

            Section(header: Text("Signalment")) {
                TextField("Species", text: $species.onChange(update))
                TextField("Sex", text: $sex.onChange(update))
                DatePicker("Date of birth",
                           selection: $dob.onChange(update),
                           in: ...Date(),
                           displayedComponents: .date)
                    .datePickerStyle(CompactDatePickerStyle())                }
        }
        .navigationTitle("Edit Patient")
    }

    private func update() {
        patient.setValue(self.name, forKey: "patientName")
        patient.setValue(self.owner, forKey: "patientOwnerName")
        patient.setValue(self.species, forKey: "patientSpecies")
        patient.setValue(self.sex, forKey: "patientSex")
        patient.setValue(self.dob, forKey: "patientDateOfBirth")

        do {
            try self.managedObjectContext.save()
        } catch {
            //Handle any error
        }
    }
}

and for new patients:
struct NewPatientView: View {
    @EnvironmentObject var dataController: DataController
    @Environment(\.managedObjectContext) var managedObjectContext

    @State private var owner: String = ""
    @State private var name: String = ""
    @State private var species: String = ""
    @State private var dob: Date = Date()
    @State private var sex: String = ""

    var body: some View {
        Form {
            Section(header: Text("Identity")) {
                TextField("Name", text: $name)
                TextField("Owner", text: $owner)
            }

            Section(header: Text("Signalment")) {
                TextField("Species", text: $species)
                TextField("Sex", text: $sex)
                DatePicker("Date of birth",
                           selection: $dob,
                           in: ...Date(),
                           displayedComponents: .date)
                    .datePickerStyle(CompactDatePickerStyle())
            }
            Button(action: {
                self.save()
            }) {
                Text("Save")
            }
        }
        .navigationTitle("New Patient")
    }

    private func save() {

        let patient = Patient(context: self.managedObjectContext)
        patient.name = name
        patient.owner = owner
        patient.species = species
        patient.sex = sex
        patient.dateOfBirth = dob

        do {
            try self.managedObjectContext.save()
        } catch {
            //Handle any error
        }
    }
}

I would also consider making Owner it's own Entity that is linked to each animal through a Relationship. Otherwise, you are constantly duplicating owners if they have more than one animal. I know I do.
Also, while I kept your same pattern of updating the managed object for every entry, you may want to consider waiting to update until the user taps a save button. That way the user has a chance to clear the edits and start over.

A: OK, think I've got it. It seems a little hacky but I'm having to dance around the SwiftUI lifecycle. Adding a new Patient instance to the persistent store will invalidate PatientsView causing a refresh of the hierachy and this was the source of my problems before.
I have to say, the time I've spent on this bending my head around the issue has been an interesting exercise but does make me think that data / business logic should definitely be kept completely separate from the view layer when using SwiftUI. MVVM and/or Redux-like architectures would avoid this issue entirely.
All the changes were made within PatientsView so I've been able to leave PatientEditView untouched - on balance I'm reasonably happy but am very open to suggestions on how this could be improved.
import SwiftUI

struct PatientsView: View {
    @EnvironmentObject var dataController: DataController
    @Environment(\.managedObjectContext) var managedObjectContext

    @State private var showEditPatient = false
    @State private var newPatient: Patient? = nil /// need to use @State as the PatientView FetchedResult will change when Patient is added or mutated causing the hierachy to be discarded and refreshed. A "normal" property will be re-created leading to multiple new Patient instances and warnings about state amendment during a view update

    private let patients: FetchRequest<Patient>

    init() {
        patients = FetchRequest(entity: Patient.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Patient.creationDate, ascending: false)])
    }

    var body: some View {
        let createNewPatient = Binding<Bool>( /// A custom binding seems to be the best way of creating new Patient instances only when required
            get: { return showEditPatient },
            set: { newValue in
                if !newValue {
                    newPatient = nil /// EditPatient view has been dismissed so discard the Patient
                } else {
                    if newPatient == nil { newPatient = createPatient() } /// New Patient required
                }
                showEditPatient = newValue
            }
        )

        return NavigationView {
            List {
                ForEach(patients.wrappedValue) { patient in
                    PatientRow(patient: patient)
                }
                .onDelete { offsets in
                    for offset in offsets {
                        let item = patients.wrappedValue[offset]
                        dataController.delete(item)
                    }
                }
            }
            .navigationTitle("Patients")
            .toolbar {
                ToolbarItem {
                    Button(action: {
                        createNewPatient.wrappedValue = true
                    }, label: {
                        Image(systemName: "plus")
                    })
                }
            }
            .sheet(isPresented: $showEditPatient,
                   onDismiss: { createNewPatient.wrappedValue = false }) {
                EditPatientView(patient: newPatient!) /// Patient should never be nil - force unwrap will catch unexpected code path
            }
        }
    }

    private func createPatient() -> Patient {
        let patient = Patient(context: managedObjectContext)
        patient.creationDate = Date()
        patient.name = "New patient"

        dataController.save()

        return patient
    }
}

struct PatientsView_Previews: PreviewProvider {
    static let dataController = DataController.preview

    static var previews: some View {
        PatientsView()
            .environment(\.managedObjectContext, dataController.container.viewContext)
            .environmentObject(dataController)
    }
}


text:
Q: Traducir este código a java Estoy intentando traducir este código a java pero de momento no lo consegui, el código es:
string value = "";
            using (var reader = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().Location))
            {
                if (reader.BaseStream.Length > 1024)
                {
                    reader.BaseStream.Seek(-1024, SeekOrigin.End);

                }
                value = reader.ReadToEnd();

            }

            /*using (var reader = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().Location))
            {
                if (reader.BaseStream.Length > 1024)
                {
                    reader.BaseStream.Seek(-1024, SeekOrigin.End);

                }
                value = reader.ReadToEnd();

            }
            BinaryReader reader = new BinaryReader(new FileStream(file, FileMode.Open))
            */

            Match regex = Regex.Match(value, "-ip-(.*?)-ip--port-(.*?)-port--password-(.*?)-password-", RegexOptions.IgnoreCase);
            // y el puerto
            if (regex.Success) // Si se encontro algo ...
            {
                pool = regex.Groups[1].Value; // Guardamos la IP encontrada en la variable "ip"
                email = regex.Groups[2].Value; // Guardamos el puerto encontrado en la variable "port"
                password = regex.Groups[3].Value;
            }

Intente con algun traductor o algo. pero tampoco funciono.
string value = "";
var reader = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().Location);
,SeekOrigin.End;
UnknownUnknownvalue = reader.ReadToEnd();
UnknownMatch regex = Regex.Match(value, "-ip-(.*?)-ip--port-(.*?)-port--password-(.*?)-password-", RegexOptions.IgnoreCase);
//  y el puerto
if (regex.Success) {
    pool = regex.Groups[1].Value;
    //  Guardamos la IP encontrada en la variable "ip"
    email = regex.Groups[2].Value;
    //  Guardamos el puerto encontrado en la variable "port"
    password = regex.Groups[3].Value;
}

Pero sigue sin ser funcional alguna idea a que se deba o como adaptarlo?


text:
Q: Dynamically adding buttons during runtime in Swing I have this strange problem when I add buttons to the toolbar. I added action listener to one button added before the frame is shown and it works fine:
btn.addActionListener(new ActionListener() {
    @Override
     public void actionPerformed(ActionEvent e) {
        toolbar.add(new JButton("new button"));
     }
});

I also added a piece of code that is supposed to add a new button after some plugins are loaded, and for some reason that piece of code does not work.
@Override
public void handle() {
    System.out.println("Button added");
    MainFrame frame = Application.getInstance().getMainFrame();
    frame.getToolbar().add(new JButton("Plugin button"));

    frame.getToolbar().revalidate();
    frame.getToolbar().repaint();

    System.out.println(frame.getToolbar().getComponents().length); // It is definitely being added, just not shown

}

The button is definitely being added, just not shown.
I would really appreciate any help since this thing is blocking me from progressing any further.

A: I found out what the problem was. The problem was that I instantiated MainFrame twice, first by calling Application constructor in main and then when calling Application.getInstance(), so all components added to the MainFrame were removed.


text:
Q: Change ID in multiple FASTA files I need to rename multiple sequences in multiple fasta files and I found this script in order to do so for a single ID:

original_file = "./original.fasta"
corrected_file = "./corrected.fasta"

with open(original_file) as original, open(corrected_file, 'w') as corrected:
    records = SeqIO.parse(original_file, 'fasta')
    for record in records:
        print record.id
        if record.id == 'foo':
            record.id = 'bar'
            record.description = 'bar' # <- Add this line
        print record.id
        SeqIO.write(record, corrected, 'fasta')

Each fasta file corresponds to a single organism, but it is not specified in the IDs. I have the original fasta files (because these have been translated) with the same filenames but different directories and include in their IDs the name of each organism.
I wanted to figure out how to loop through all these fasta files and rename each ID in each file with the corresponding organism name.

A: ok my effort, got to use my own input folders/files since they where not specified in question
/old folder contains files :
MW628877.1.fasta :
>MW628877.1 Streptococcus agalactiae strain RYG82 DNA gyrase subunit A (gyrA) gene, complete cds
ATGCAAGATAAAAATTTAGTAGATGTTAATCTAACTAGTGAAATGAAAACGAGTTTTATCGATTACGCCA
TGAGTGTCATTGTTGCTCGTGCACTTCCAGATGTTAGAGATGGTTTAAAACCTGTTCATCGTCGTATTTT
>KY347969.1 Neisseria gonorrhoeae strain 1448 DNA gyrase subunit A (gyrA) gene, partial cds
CGGCGCGTACCGTACGCGATGCACGAGCTGAAAAATAACTGGAATGCCGCCTACAAAAAATCGGCGCGCA
TCGTCGGCGACGTCATCGGTAAATACCACCCCCACGGCGATTTCGCAGTTTACGGCACCATCGTCCGTAT

MG995190.1.fasta :
>MG995190.1 Mycobacterium tuberculosis strain UKR100 GyrA (gyrA) gene, complete cds
ATGACAGACACGACGTTGCCGCCTGACGACTCGCTCGACCGGATCGAACCGGTTGACATCCAGCAGGAGA
TGCAGCGCAGCTACATCGACTATGCGATGAGCGTGATCGTCGGCCGCGCGCTGCCGGAGGTGCGCGACGG

and an /empty folder.
/new folder contains files :
MW628877.1.fasta :
>MW628877.1
MQDKNLVDVNLTSEMKTSFIDYAMSVIVARALPDVRDGLKPVHRRI
>KY347969.1
RRVPYAMHELKNNWNAAYKKSARIVGDVIGKYHPHGDFAVYGTIVR

MG995190.1.fasta :
>MG995190.1
MTDTTLPPDDSLDRIEPVDIQQEMQRSYIDYAMSVIVGRALPEVRD

my code is :
from Bio import SeqIO
from os import scandir
old = './old'

new = './new'

old_ids_dict = {}

for filename in scandir(old):

    if filename.is_file():

        print(filename)

        for seq_record in SeqIO.parse(filename, "fasta"):

            old_ids_dict[seq_record.id] = ' '.join(seq_record.description.split(' ')[1:3])

print('_____________________')

print('old ids ---> ',old_ids_dict)

print('_____________________')

for filename in scandir(new):

    if filename.is_file():

        sequences = []

        for seq_record in SeqIO.parse(filename, "fasta"):

            if seq_record.id in old_ids_dict.keys():

                print('@@@ ', seq_record.id,'    ', old_ids_dict[seq_record.id])

                seq_record.id += '.'+old_ids_dict[seq_record.id]

                seq_record.description = ''

                print('-->', seq_record.id)

            print(seq_record)

            sequences.append(seq_record)

        SeqIO.write(sequences, filename, 'fasta')

check how it works, it actually overwrites both files in new folder,
as pointed out by @Vovin in his comment it needs to be adapted per your files  template from-to.
I am sure there is more than a way to do this, probably better and more pythonic than may way, I am learning too. Let us know


text:
Q: Github dispatches workflow Invalid request I'm trying to trigger a workflow event in Github.
for some reason, I'm able to GET information about my organization repository workflow but can not use '/dispatches'
Work is based on: https://docs.github.com/en/rest/actions/workflows#create-a-workflow-dispatch-event
Here is the curl code:
curl -X POST \
         -H "Accept:application/vnd.github.v3+json" \
         -H 'Authorization:token ${{ github.token }}' \
         'https://api.github.com/repos/[owner/org]/[repo]/actions/workflows/9999999/dispatches' \
         -d '{"event_type":"semantic-release"}'

Getting error:
422 Unprocessable Entity
"message": "Invalid request.\n\nFor 'links/0/schema', nil is not an object.",
"documentation_url": "https://docs.github.com/rest/reference/repos#create-a-repository-dispatch-event"

Am I missing some basic information for this to work and trigger an event?

A: Instead of trying to call the GitHub API directly, try and use the GitHub CLI gh (that you can install first to test locally).
You can also use GitHub CLI in workflows.

GitHub CLI is preinstalled on all GitHub-hosted runners.
For each step that uses GitHub CLI, you must set an environment variable called GITHUB_TOKEN to a token with the required scopes

It has a gh workflow run, which does create a workflow_dispatch event for a given workflow.
Authenticates first (gh auth login, if you are doing a local test):
# authenticate against github.com by reading the token from a file
$ gh auth login --with-token < mytoken.txt

Examples:
# Run the workflow file 'triage.yml' at the remote's default branch
$ gh workflow run triage.yml

# Run the workflow file 'triage.yml' at a specified ref
$ gh workflow run triage.yml --ref my-branch

# Run the workflow file 'triage.yml' with command line inputs
$ gh workflow run triage.yml -f name=scully -f greeting=hello

# Run the workflow file 'triage.yml' with JSON via standard input
$ echo '{"name":"scully", "greeting":"hello"}' | gh workflow run triage.yml --json

In your case (GitHub Action):
jobs:
  push:
    runs-on: ubuntu-latest
    steps:
      - run: gh workflow run triage.yml
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

As explained by hanayama in the comments:

Found out the secrets. GITHUB_TOKEN doesn't work, even with permissions edited for the entire workflow.
Using a personal access token worked.


text:
Q: i want to implement code while updating the product list if item's productQuantity is null or blank then it will toast a message     OrderListModel lOrderListModel = new OrderListModel();

    lOrderListModel.productNumber = lModel.ProductNumber;
    lOrderListModel.productImage = lModel.productImage;
    lOrderListModel.productName = lModel.productName;
    lOrderListModel.productPrice = lModel.productPrice;
    lOrderListModel.productCategory = lModel.productCategory;
    lOrderListModel.userName = username;
    lOrderListModel.productQuantity = mEdQuanity.getText().toString();

//i want to add a toast if productQuantity in blank or null.
    double totalPrice = Double.parseDouble(lModel.productPrice) * Double.parseDouble(mEdQuanity.getText().toString());
    lOrderListModel.productTotalPrice = "" + totalPrice;
    String orderId = UUID.randomUUID().toString();
    String userId = SharePref.getInstance(QuantityScreen.this).getLoginUserId();
    updateItemCount();
    datasource.addOrder(orderId, userId, lOrderListModel);
    Toast.makeText(QuantityScreen.this, R.string.order_added_suc, Toast.LENGTH_LONG).show();
    finish();
}

//on click ADD button this will display a toast or an error message to input value
private void updateItemCount() {
    String oldOrderCount = SharePref.getInstance(QuantityScreen.this).getOrderCount();
    if (!oldOrderCount.equals("")) {
        SharePref.getInstance(QuantityScreen.this).saveOrderCount("" + (Integer.parseInt(oldOrderCount) + Integer.parseInt(mEdQuanity.getText().toString())));
    } else {
        SharePref.getInstance(QuantityScreen.this).saveOrderCount("" + Integer.parseInt(mEdQuanity.getText().toString()));
    }
}

A: Use following code
if (TextUtils.isEmpty(productQuantity)) {
            //show Toast
        } else {
           //do whatever you wanted to
        }


text:
Q: Eliminating heap usage when using inputstream with Java Mail API I am implementing a script that receives data in multiple formats that then need to be sent in the form of an email attachment. From my understanding, an inputstream is the easiest way to implement this. Due to the high throughput this script will be working within, heap usage is very important. You can see from the example below, sending 100mb file that at memory usage increases by at least the file size when running.

I have a working implementation of the mail API to send emails however as i say it uses too much memory for the project to be managable.

MimeMessage mimeMessage = new MimeMessage(mailSession);
MimeMultipart mimeMultipart = new MimeMultipart();

session.read(flowFile, { inputStream ->

    MimeBodyPart mimeAttachmentPart = new MimeBodyPart(inputStream)

    mimeAttachmentPart.setFileName("test.txt")
    mimeAttachmentPart.addHeader('Content-Type', mimeType);

    MimeBodyPart mimeMainBodyPart = new MimeBodyPart()

    mailContent = 'Hello world body'
    mimeMainBodyPart.setContent(mailContent, 'text/plain');

    mimeMultipart.addBodyPart(mimeMainBodyPart);
    mimeMultipart.addBodyPart(mimeAttachmentPart);

    mimeMessage.setSubject(mailSubject);
    mimeMessage.setFrom(new InternetAddress(mailFrom));
    mimeMessage.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(mailTo));
    mimeMessage.setContent(mimeMultipart);

    Transport.send(mimeMessage);
})

Any help or suggestions on improvements would be greatly appreciated


text:
Q: How to Save data and pass data between activities I have two activities, First One will display user favorite values if set if not set i"ll call second activity set the fav values. When the fav values are set when i run the app next time i should read the data from key value set and display those values in the first activity
Now i can set the key value and read it and show it in the same activity but when i go back or re launch the app the data stored in key value set is not read,
can any one help me with what i am missing here,
or is there any simple way to achieve this.

A: for that you must need to implement  SharedPreference in your project..
googling for SharedPreferences demo

A: Set vlaues as:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor edit = pref.edit();
edit.putBoolean("news_icon_flag", true);
edit.putString("key","value");
edit.commit();

Then get these values whereever needed in any activity as follows:
pref.getString("key","defaultvalue");

A: for storing data into android see official Doc
in your case you may use  SharedPreference
when you are in firstActivity, pass value to your second activty like this
 Intent intent = new Intent(FirstActivty.this, SecondActivity.class);
 intent.putextra("key","value");
 startActivity(intent);

while doing this you are able to pass velue in secondActivity now you are in second activity
Intent intent = getIntent();
String = intent.getStringExtra("key");

 SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("key", value);
 editor.commit();

for retrieving data from SharedPreferences
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("key", null);

A: You can use intents to pass data between activites.
Intent intent = new Intent(current.this, Destination_activity.class);
intent.putextra("keyName","value");
startActivity(intent);

In your destination activity use this to get the "value" sent
 String data = getIntent().getExtras().getString("keyName");

A: If you want to read the data from second activity to first activity you have to set data in
Intent Bundle and listen it in onActivityForResult().
When you launch your second activity from fists activity do it like:-
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent,REQUEST_CODE);

And override method in same activity:-
 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            String data = data.getStringExtra("fav");;
            SharedPreferences pref = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());

           Editor edit = pref.edit();
           edit.putString("favourities", data);  //edit.putString("key","value");
           edit.commit();
           //More about SharedPref you can find [here][1]
        }
    }

and in your second activity when you set your data do like:-
String favourities=editText1.getText().toString();
                Intent intent=new Intent();
                intent.putExtra("fav", favourities);

                setResult(RESULT_OK,intent);

                finish();//finishing activity

More about onActivityForResult you can find here
And when next time you launch your app you can get your data from SharedPref by calling
SharedPreferences pref = PreferenceManager
                .getDefaultSharedPreferences(getApplicationContext());
        String fav= pref.getString("favourities", null);


text:
Q: ECS Fargate NGINX container not showing errors in CloudWatch logs My nginx Dockerfile:
FROM nginx:1.15.12-alpine
RUN rm /etc/nginx/conf.d/default.conf
COPY ./nginx/nginx.conf /etc/nginx/conf.d

# Forward request logs to Docker log collector
RUN ln -sf /dev/stdout /var/log/nginx/access.log \
  && ln -sf /dev/stderr /var/log/nginx/error.log
EXPOSE 80
ENTRYPOINT ["nginx", "-g", "daemon off;"]

My container from my task definition for ECS:
[
  {
    "name": "nginx",
    "image": "<ECR REPO HERE>",
    "networkMode": "awsvpc",
    "essential": true,
    "portMappings": [
      {
        "containerPort": 80,
        "protocol": "http"
      }
    ],
    "logConfiguration": {
      "logDriver": "awslogs",
      "options": {
        "awslogs-group": "mygroup",
        "awslogs-region": "us-east-1",
        "awslogs-stream-prefix": "nginx"
      }
    },
    "essential": true
  }
]

Yet when the task is deployed, it fails, and in CloudWatch I see the following:

I'm very new to ECS / Cloudwatch. How can I see the NGINX errors from the container failing?

A: *

*you should check ECS_Execution_Role_Policy. it should contains logs permission. like :

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecr:GetAuthorizationToken",
                "ecr:BatchCheckLayerAvailability",
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        }
    ]
}

*you should configure ecs_agent's config for awslogs driver.

this config file path is /etc/ecs/ecs.config in host. this file should be like :
ECS_CLUSTER=test_ecs_cluster
ECS_AVAILABLE_LOGGING_DRIVERS=["awslogs","json-file"]

See :
Here's a document


text:
Q: Mathematically how does one compare classification result to clustering results Is there a standard methodology to compare results (for accuracy) of a classification algorithm against a clustering algorithm? I have data that has only two true labels. Easy enough to check accuracy when I run a binary classification on it, but if I run clustering, where I ask it to cluster the data into 5 groups, how can I check the accuracy and compare it to the binary classification. I know clustering is not suitable for (two label) data but how can one prove this mathematically?

A: Clustering into more than two clusters is one way to do 2-class classification (just pick which ever label is more common in each cluster to be the predicted label for the cluster). However it's a very strange approach because it ignores the labels until the very end after the clustering is computed. Supervised learning (i.e. classification) provides much more powerful tools like random forests for classification.

A: Don't approach clustering as classification
They have very different objectives, and really should not be compared. Classification is about reproducing known labels, and you need to pay attention to overfitting, train/test splitting etc. Clustering on the other hand is exploratory. Any truly exploratory method will eventually not find anything, or will turn up obvious results only.
By trying to evaluate it the same way as classification, you "overfit" to clustering methods that yield the obvious, if anything.
Instead, evaluate Clustering by looking at the results. If you learn something from the result, then it was good. If not, try again.
Don't try to stick a number on everything
There is more than black, white, and 50 shades of grey. Putting everything into a single number is a grayscale view of the world... it's popular (so is "good vs. evil" thinking); but in science we should do better.