text:
Q: How/where to provide sudo password for Vagrant shell provisioners? I am trying to build a Vagrant box (CentOS) that will be provisioned by an install.sh shell script. This script will do several things, the first of which, involves creating the correct directory structure under /opt so that my service can be installed there and do other things, like writing logs there, as well.
So my Vagrant project (so far) consists of:
my-app-vagrant/
    Vagrantfile
    install.sh

Where install.sh looks like:
mkdir /opt/myapp
mkdir /opt/myapp/bin        # Where we will install binary to (later in this script)
mkdir /opt/myapp/logs       # Where the binary will write logs to

Now the binary does not need elevated privileges in order to run (it is configured via command-line arguments where to write logs to). However I simply want it to live under /opt with the above directory structure, at least for this particular machine.
The problem is that /opt is owned by root. Which means I need to run these mkdirs with sudo, provide the script the password for sudo, and then tweak directory permissions so that when the app runs, it has permission to both run and to write logs to my intended destination (which again, is /opt/myapp/logs). So I tweaked install.sh to look like this:
mkdir /opt/myapp
mkdir /opt/myapp/bin
mkdir /opt/myapp/logs

chmod -R 777 /opt/myapp     # Now when the app runs as a normal non-privileged user, we can run + write logs

And I know that I can provide a password to the script via echo <rootPswd> | sudo -S sh install.sh (where <rootPswd> is the correct root password).
Now I'm trying to figure out how to get this running/working correctly when Vagrant is provisioning the VM.
My Vagrant file looks like:
Vagrant.configure(2) do |config|
    config.vm.provision "shell", path: "install.sh"

    config.vm.box = "centos7"
    config.vm.box_url = "https://github.com/tommy-muehle/puppet-vagrant-boxes/releases/download/1.1.0/centos-7.0-x86_64.box"

    config.vm.network "private_network", ip: "10.0.1.2"

    config.vm.provider "virtualbox" do |vb|
        vb.memory = "2048"
    end
end

But what I'm stuck on is: how do I extend the whole "echo <rootPswd> | sudo -S sh install.sh"-concept to Vagrant? According to their docs there is a privileged option that I might be able to use, but it is set to true by default anyways.
But nowhere in their docs do they explain how/where to provide the sudo password that should be used (at least from what I have been able to find so far).
So I ask:

*

*How do I provide the sudo password for a Vagrant VM's shell provisioner's installation script?; and

*Where can I find out what the sudo password even if, given the base Vagrant box that I'm trying to use?

A: Turns out that (for almost all Vagrant boxes) the vagrant user is listed in /etc/sudoers with ALL=(ALL) NOPASSWD:ALL permissions, which instructs Linux to not ask that user for a "sudo password", ever.
Hence, you don't need to supply your privileged user with a sudo password.

A: While smeeb's answer is the case even to this day, it doesn't quite answer the question. Really there are different ways to do this depending on the provisioner you are using. For example, in Ansible you can use ask_become_pass to be asked for the password prior.
With the shell provisioner you won't have any helpers outside of those Ansible provide. If privileged doesn't do it for you then you'd probably need to just sudo manually.
To do this you can use the following:
echo "mypassword" | sudo -S command

Take heed though, doing this on something throwaway will mean you will have traces in your history of that password.


text:
Q: Closing Shopify online store sales channel after moving to storefront API I recently changed a Shopify store to use a separate SPA using the storefront API. However the old 'online store' is still running as a separate website with some theme plugins etc. I'd like to remove this sales channel now that I'm using a custom app and the storefront API so that customers aren't confused as to why there are two websites running concurrently. However, when going to remove my online store, Shopify prompts me with an 'are you sure' modal that contains a warning that I won't be able to publish products and that they will send a request to a developer to delete personal customer information.
Obviously this is not what I want as the store is still running through storefront API and I still need everything on the Shopify admin side to remain intact and running. I tried getting support from Shopify about it but they just pointed me in the direction of the developer documentation. It's not really clear what impact deleting this sales channel would have? Any advice from someone who's done something similar would be greatly appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Abelian Galois group and prime ideals Let $K/k$ be abelian extension with Galois group $G$. Let $p$ be prime of $k$, let $P$ be a prime of $K$ lying above $p$ and let $G_P$ be its decomposition group.
Let $E$ be the fixed field of $G_P$. Let
$$ G=\cup_{i-1}^r\sigma_i G_P$$
be a coset decomposition. Let $q=P\cap E$.

How can I know that the primes $\sigma_i q$ are primes of $E$?

Here are what I thought.
Since $q$ is a prime in $E$, it follows that $\sigma_i q$ is a prime of $\sigma(E)$. Since $K/k$ is normal, $\sigma_i(E)=E$. So $\sigma_i$ is a prime in $E$. Is this correct? But, where did I need $G$ is abelian?


text:
Q: Could not load org.jgroups.protocols.pbcast.GmsImpl$Request I have no idea about this wrong when I use J2Cache:
INFO: Illegal access: this web application instance has been stopped already.  Could not load org.jgroups.protocols.pbcast.GmsImpl$Request.  The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact.
java.lang.IllegalStateException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1612)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at org.jgroups.protocols.pbcast.GMS.up(GMS.java:855)
at org.jgroups.protocols.pbcast.STABLE.up(STABLE.java:234)
at org.jgroups.protocols.pbcast.NAKACK.up(NAKACK.java:636)
at org.jgroups.protocols.BARRIER.up(BARRIER.java:103)
at org.jgroups.protocols.VERIFY_SUSPECT.up(VERIFY_SUSPECT.java:147)
at org.jgroups.protocols.FD_ALL.up(FD_ALL.java:185)
at org.jgroups.protocols.FD_SOCK.up(FD_SOCK.java:301)
at org.jgroups.protocols.MERGE2.up(MERGE2.java:209)
at org.jgroups.protocols.Discovery.up(Discovery.java:379)
at org.jgroups.protocols.TP.passMessageUp(TP.java:1412)
at org.jgroups.protocols.TP$MyHandler.run(TP.java:1598)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

Jun 11, 2015 2:47:30 PM org.apache.catalina.connector.CoyoteAdapter log
WARNING: Exception while attempting to add an entry to the access log
java.lang.NullPointerException
at org.apache.catalina.connector.CoyoteAdapter.log(CoyoteAdapter.java:557)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:182)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

The above of this wrong happened with tomcat's starting.
I have googled about it.
Someone said:

If you use a QUIT signal on the Java process it should output a thread
  dump that should identify which threads is still running and
  preventing a proper shutdown. I have seen this on occasion with some
  versions of HSQLDB that had a driver that didn't shutdown properly but
  it could be anything else deployed in your install.
To send the QUIT signal : kill -QUIT JAVA_PID
where JAVA_PID is the process ID of your Java process you can retrieve
  using : ps aux

But unfortunately, I can't understand it.
Can anybody help me?

A: This sounds familiar to this issue - https://issues.jboss.org/browse/JGRP-826. My guess is that tomcat already shuts down while there are still JGroups threads running. How do you shutdown Tomcat? Do you explicitly shutdown the cache as well? I would try implementing a ServletContextListener to receive a callback when the application gets shutdown. At this point I would try to explicitly close the cache as well. This all depends of course how and where you use the cache.


text:
Q: How do you efficiently (in a DB independent manner) select random records from a table? This seems like an incredibly simple problem however it isn't working out as trivially as I'd expected.
I have a club which has club members and I'd like to pull out two members at random from a club.
Using RANDOM()
One way is to use random ordering:
club.members.find(:all, :order => 'RANDOM()').limit(2)

However that is different for SqLite (the dev database) and Postgres (production) since in MySql the command is RAND().
While I could start writing some wrappers around this I feel that the fact that it hasn't been done already and doesn't seem to be part of ActiveRecord tells me something and that RANDOM may not be the right way to go.
Pulling items out directly using their index
Another way of doing this is to pull the set in order but then select random records from it:
First off we need to generate a sequence of two unique indices corresponding to the members:
all_indices = 1..club.members.count
two_rand_indices = all_indices.to_a.shuffle.slice(0,2)

This gives an array with two indices guaranteed to be unique and random. We can use these indices to pull out our records
@user1, @user2 = Club.members.values_at(*two_rand_indices)

What's the best method?
While the second method is seems pretty nice, I also feel like I might be missing something and might have over complicated a simple problem. I'm clearly not the first person to have tackled this so what is the best, most SQL efficient route through it?

A: The problem with your first method is that it sorts the whole table by an unindexable expression, just to take two rows.  This does not scale well.
The problem with your second method is similar, if you have 109 rows in your table, then you will generate a large array from to_a.  That will take a lot of memory and time to shuffle it.
Also by using values_at aren't you assuming that there's a row for every primary key value from 1 to count, with no gaps?  You shouldn't assume that.
What I'd recommend instead is:

*

*Count the rows in the table.
c = Club.members.count

*Pick two random numbers between 1 and the count.
r_a = 2.times.map{ 1+Random.rand(c) }

*Query your table with limit and offset.
Don't use ORDER BY, just rely on the RDBMS's arbitrary ordering.
for r in r_a
    row = Club.members.limit(1).offset(r)
end

See also:

*

*How can i optimize MySQL's ORDER BY RAND() function?

*Quick selection of a random row from a large table in MySQL

A: The Order By RAND() function in MySQL:
ORDER BY RAND() LIMIT 4

This will select a random 4 rows when the above is the final clause in the query.

A: try to use the randumb gem, it implement the second method you mentioned


text:
Q: Have 3 sections(divs) float left, center, and right I'm trying to get 3 separate elements float left center and right. The main container wrapping the 3 is using the following:
.container {
    display: inline-block;
    margin: 0 auto;
}

The 3 elements are using the following:
.left {
    float: left
}

.center {
    display: inline-block;
    margin: 0 auto;
}

.right {
     float: right;
}

I was able to successfully distribute these left, center, and right but the height of each are different and now they aren't vertically aligned. I've tried using the "vertical-align" property but it doesn't seem to work. What should I do?

A: Use CSS Flexbox.

.flexContainer { display:flex; height:250px; }
.flexContainer div { border:1px solid black; flex:1; }

Box 1

       Box 2 Box 2Box 2Box 2Box 2Box 2Box 2Box

       2Box 2Box 2Box 2Box 2Box 2Box 2Box 2Box 2
       Box 2 Box 2Box 2Box 2Box 2Box 2Box 2Box

       2Box 2Box 2Box 2Box 2Box 2Box 2Box 2Box 2
       Box 2 Box 2Box 2Box 2Box 2Box 2Box 2Box

       2Box 2Box 2Box 2Box 2Box 2Box 2Box 2Box 2

Box 3


text:
Q: Placing images next to boxes HTML/CSS I have been toying with this for about three weeks now and I have looked all over for what I am trying to portray and not getting results. I know it's so simple but I am just not having any luck!
I have a large box which spans the screen, I then have a white box inside this which has some text within it (which I am wondering if it is possible to have that expand as text is added rather than fixed width?) aligned to the left, I then have an image which I would like to float to the right and have the text box overlapping it at the center of the original outer box.
My issue is that the image is in the outer box, but I cannot get it to align with the text box and overlap underneath. Rather it just floats under the text box either at the right or center.

table {
    height: 100%;
    width: 100%;
    background-color: #fff;
    font-family: 'Courier New', Courier, monospace;
}

td {
  height: 100%;
  width: 100%;
  vertical-align: middle;
  text-align: right;
  background-color: #f4d442;
  font-family: 'Courier New', Courier, monospace;
}

.boxed{
  width: 50vw;
  height: 70vh;
  box-align: left;
  text-align: justify;
  padding: 5%;
  background-color:  #fff;
  margin: 5%;
  margin-left: 5%;
}

  .container-wrapper{
    text-align:center;
  }

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sed feugiat lectus. Phasellus maximus, ex nec bibendum volutpat, justo erat pellentesque massa, vel malesuada sem lectus tincidunt orci. Aenean eleifend est sit amet dapibus ullamcorper. Nam ornare finibus ex vitae interdum. Sed quis purus eros. Sed ut porttitor dolor, eget ultrices justo. Sed eu leo porta, mattis libero eu, sagittis metus. Vivamus nec lobortis nisi. Suspendisse posuere enim arcu, at interdum dui congue vitae. Aliquam vestibulum accumsan magna. Vivamus a arcu nunc. Cras euismod lacinia augue sed elementum. Phasellus dignissim semper mi at sollicitudin. Vivamus maximus semper nulla. Donec luctus, dolor non viverra aliquam, enim arcu imperdiet sem, et pretium dui ante ac lectus.

I have tried for weeks to get my head around this and having no luck, thanks for any light you can shine! This is the first website I have fully made so constructive critisism is welcomed.

A: One solution might be to try using flex box:

.container-wrapper {
  background-color: #f4d442;
  font-family: 'Courier New', Courier, monospace;
  display: flex;
  align-items: center;
}

.image {
  margin: 20px;
}

.boxed {
  text-align: justify;
  padding: 20px;
  margin: 20px;
  background-color: #fff;
}

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sed feugiat lectus. Phasellus maximus, ex nec bibendum volutpat, justo erat pellentesque massa, vel malesuada sem lectus tincidunt orci. Aenean eleifend est sit amet dapibus ullamcorper.
    Nam ornare finibus ex vitae interdum. Sed quis purus eros. Sed ut porttitor dolor, eget ultrices justo. Sed eu leo porta, mattis libero eu, sagittis metus. Vivamus nec lobortis nisi. Suspendisse posuere enim arcu, at interdum dui congue vitae. Aliquam
    vestibulum accumsan magna. Vivamus a arcu nunc. Cras euismod lacinia augue sed elementum. Phasellus dignissim semper mi at sollicitudin. Vivamus maximus semper nulla. Donec luctus, dolor non viverra aliquam, enim arcu imperdiet sem, et pretium dui
    ante ac lectus.

A:

table {
    height: 100%;
    width: 100%;
    background-color: #fff;
    font-family: 'Courier New', Courier, monospace;
}

td {
  height: 100%;
  width: 100%;
  vertical-align: middle;
  text-align: right;
  background-color: #f4d442;
  font-family: 'Courier New', Courier, monospace;
}

.boxed{
  width: 50vw;
  height: auto;
  box-align: left;
  text-align: justify;
  padding: 5%;
  background-color:  #fff;
  margin: 5%;
  margin-left: 5%;
}

  .container-wrapper{
    text-align:center;
  }

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sed feugiat lectus. Phasellus maximus, ex nec bibendum volutpat, justo erat pellentesque massa, vel malesuada sem lectus tincidunt orci. Aenean eleifend est sit amet dapibus ullamcorper. Nam ornare finibus ex vitae interdum. Sed quis purus eros. Sed ut porttitor dolor, eget ultrices justo. Sed eu leo porta, mattis libero eu, sagittis metus. Vivamus nec lobortis nisi. Suspendisse posuere enim arcu, at interdum dui congue vitae. Aliquam vestibulum accumsan magna. Vivamus a arcu nunc. Cras euismod lacinia augue sed elementum. Phasellus dignissim semper mi at sollicitudin. Vivamus maximus semper nulla. Donec luctus, dolor non viverra aliquam, enim arcu imperdiet sem, et pretium dui ante ac lectus.

I just changed the height to auto, since I thought you meant height when you said width, it should work the same with width though.
I can not help you with your picture. Please include one example picture from the web to your code, so it is easier to help you


text:
Q: Search for "similar questions" across multiple sites? After typing the title of a question, the "similar questions" are displayed.
Is there any feature, that would provide such suggestions across all (or a configured subset of) stackexchange communities?
I came across this question, when writing a question Python postfix notation for map, filter, ...?, where I noticed, that I got only a single result with the stackexchange.com search, but many suggestions on stackoverflow.com.

A: You can search across all sites via the search bar at the top of the Stack Exchange site.
Be careful though because terminology varies. Seasoned Advice and Stack Overflow have very different definitions of apple for instance.
If you're not sure whether your question fits on any specific site, each site has a help centre like this one.
You can always search via a Search Engine of course, that kind of search won't distinguish between different sites by default. If you're really unsure, that's probably a good way to start.
Getting a book on a subject is likely to be a better more structured resource if you're new to a subject than the disparate Q&A here. Beginner books will also teach you terminology.

A: The duplicate finder that pops up works reasonably well on one site but it doesn't help you choose the best site to ask; for that you probably want to use the search engines.
Taking your query: "python postfix notation for map filter" gives this result:
python postfix notation for map filter -site:https://stackoverflow.com site:https://stackexchange.com
That returns just two results, but if you click on the last link, on the last page (in this case, with two results, it's on the first page) that says:
"If you like, you can repeat the search with the omitted results included."
You come up with 448 results, that appears to be a useful result that's relevant to your search terms. Now it's a matter of looking on the first few pages to see if there are sites most suitable for your question.
In some cases our Stack Overflow site is the better site to ask on; all too often, when using the https://stackexchange.com/ search bar, that one site overwhelms the returns. In that case it's often better to style your search as indicated in my first link (or on a different search engine, substituting their syntax). With the search terms for your example there are only two results returned, and one of them is this question. With those example words using an external search engine (and the last link) provides 448 results.
Once you find the best site typing your search terms (a fake title) into the [Ask Question] duplicate finder or using the site's search bar and our query modifiers helps check for duplicates and verify that the site is a good place to ask your question.
A second way to verify that the site is a good fit for your question is to search the site's tags, unfortunately that requires knowing exactly what tags you would want to use (or picking words that show up in the tag info). Sometimes that is done automatically by our search tool, but only for popular tags.
Once you can select a half dozen words that surely must be a part of your question or answer it's easy to whittle the results. Sometimes "quoting a few words together" along with several floating words is what's needed to shake loose what you are looking for.


text:
Q: javafx autocomplete event handler I need your help as I am trying to make textfield that when you type character it drops down suggestions I tried to use controlsfx and put my function on key press handler but I got this error

java.lang.IllegalArgumentException: argument type mismatch


text:
Q: Две страницы на одном листе при генерации pdf puppeteer-ом Есть html-документ из которого puppeteer-ом генерируется pdf.
Как мне привести сгенерированный pdf к виду "две страницы на лист"?

Если это невозможно сделать pagepdfoptions то как это сделать html+css?


text:
Q: Retrofit Post request I want to post user credentials to following url
: http://myurl/authenticate
Parameters : login. Type (JSON)
username : string
password : string
"login":{"username": "JohnDoe","password": "eoDnhoJ" }

If success
{
" r e s u l t " : " S u c c e s s " ,
"response": "Users Session ID"
}

Here is my code
public interface APIService {

    @POST("/authenticate")
    @FormUrlEncoded
    Call<Login> savePost(@Field("username") String username,
                         @Field("password") String password);
}

public class ApiUtils {

    private ApiUtils() {}

    public static final String BASE_URL = "http://myurl/";

    public static APIService getAPIService() {

        return RetrofitClient.getClient(BASE_URL).create(APIService.class);
    }
}

public class Login {
@SerializedName("username")
@Expose
private String username;
@SerializedName("password")
@Expose
private String password;
//getters and setters
}

public class RetrofitClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

public class LoginActivity extends AppCompatActivity {

    private EditText usernameEditText,passwordEditText;
    private Button button;
    private APIService mAPIService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        usernameEditText=(EditText)findViewById(R.id.username);
        passwordEditText=(EditText)findViewById(R.id.password);
        button=(Button)findViewById(R.id.signup);

        mAPIService = ApiUtils.getAPIService();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String uname=usernameEditText.getText().toString();
                String pass=passwordEditText.getText().toString();
                if(TextUtils.isEmpty(uname)){
                    Toast.makeText(LoginActivity.this, "Username cannot be empty", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(TextUtils.isEmpty(pass)){
                    Toast.makeText(LoginActivity.this, "Password cannot be empty", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(pass.length()<4){
                    Toast.makeText(LoginActivity.this, "Password should be greater than four characters", Toast.LENGTH_SHORT).show();
                    return;
                }

                sendPost(uname, new StringBuilder(uname).reverse().toString());

            }
        });
    }

    public void sendPost(String username, String password) {
        mAPIService.savePost(username, password).enqueue(new Callback<Login>() {
            @Override
            public void onResponse(Call<Login> call, Response<Login> response) {

                if(response.isSuccessful()) {
                    showResponse(response.body().toString());
                    Log.i("Pritish", "post submitted to API." + response.body().toString());
                    Intent intent=new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<Login> call, Throwable t) {
                Log.e("Pritish", "Unable to submit post to API.");
            }
        });
    }

    public void showResponse(String response) {
        Log.i("Abbu",response);
    }
}

Whenever i submit username and password i get null values,can some body please help me?And how can iget the sessionId.I tried looking for various egs but i am so confsued right now.

A: Instead of follwing code
@POST("/authenticate")
@FormUrlEncoded
Call<Login> savePost(@Field("username") String username,
                     @Field("password") String password);

Use this code
@POST("/authenticate")
Call<Login> savePost(@Query("username") String username,
                     @Query("password") String password);

A: Step 1: instead of this code
public interface APIService {

    @POST("/authenticate")
    @FormUrlEncoded
    Call<Login> savePost(@Field("username") String username,
                         @Field("password") String password);
}

Use this code:
public interface APIService {

    @POST("/authenticate")
    Call<Login> savePost(@Body RequestBody body);
}

Step 2: instead of this code in LoginActivity
public void sendPost(String username, String password) {
        mAPIService.savePost(username, password).enqueue(new Callback<Login>() {
            @Override
            public void onResponse(Call<Login> call, Response<Login> response) {

                if(response.isSuccessful()) {
                    showResponse(response.body().toString());
                    Log.i("Pritish", "post submitted to API." + response.body().toString());
                    Intent intent=new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<Login> call, Throwable t) {
                Log.e("Pritish", "Unable to submit post to API.");
            }
        });
    }

Change to this code :
public void sendPost(String username, String password) {

        HashMap<String, String> params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);
        String strRequestBody = new Gson().toJson(params);

    //create requestbody
        final RequestBody requestBody = RequestBody.create(MediaType.
                parse("application/json"),strRequestBody);

            mAPIService.savePost(requestBody).enqueue(new Callback<Login>() {
                @Override
                public void onResponse(Call<Login> call, Response<Login> response) {

                    if(response.isSuccessful()) {
                        showResponse(response.body().toString());
                        Log.i("Pritish", "post submitted to API." + response.body().toString());
                        Intent intent=new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }

                @Override
                public void onFailure(Call<Login> call, Throwable t) {
                    Log.e("Pritish", "Unable to submit post to API.");
                }
            });
        }

A: Replace your Login class by following
 @SerializedName("result")
    @Expose
    private String rESULT;
    @SerializedName("response")
    @Expose
    private String response;

    public String getRESULT() {
        return rESULT;
    }

    public void setRESULT(String rESULT) {
        this.rESULT = rESULT;
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }

A: *

*Add ServiceGenerator class :
public class ServiceGenerator {

private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(BASEURL)
                .addConverterFactory(ScalarsConverterFactory.create());

public static <S> S createService(Class<S> serviceClass) {
    Retrofit retrofit = builder.client(httpClient.build()).build();
    return retrofit.create(serviceClass);
}
public static Retrofit getRetrofit()
{
    return builder.client(httpClient.build()).build();
}

}
2.Add interface RetrofitAPI :
 public interface RetrofitApi {
            @POST("/api/v1/user")
            Call<ResponseBody> login(@Body RequestBody loginBody);
    }

3.Add method for login in your manager class :
public void retrofitLogin(JSONObject login, final String tag) {
        RetrofitApi service = ServiceGenerator.createService(RetrofitApi.class);
        Call<ResponseBody> result = service.login(convertJsonToRequestBody(login));
        result.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                retrofitCheckResponse(response, tag);
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (t instanceof IOException) {
                    Log.e("retrofit error", "retrofit error");
                    sendErrorRetrofit(mContext.getString(R.string.ERROR), 500, tag);
                }
            }
        });
    }

Method to convert JSONObject to RequestBody :
 private RequestBody convertJsonToRequestBody(JSONObject jsonObject) {
            if (jsonObject != null) {

                return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
            } else {
                return null;
            }
        }

4.Now call your retrofitLogin method :
JSONObject mLoginParams = new JSONObject();
JSONObject mLoginObj = new JSONObject();
mLoginParams.put("username", uname);
mLoginParams.put("password", pass);
mLoginObj.put("appType","mobile");
mLoginObj.put("user", mLoginParams);
volleyRequest.retrofitLogin(mLoginObj, "Login");


text:
Q: How to integrate $\int_n^{+\infty} x \exp\{-ax^2+bx+c\}dx$? How can I integrate,
$$
\int_n^{+\infty} x \exp\{-ax^2+bx+c\}dx
$$
and what's the result w.r.t the Gaussian function's p.d.f $p(x)$ and c.d.f $\phi(x)$?
Thanks!

A: Completing the square in the quadratic:
$$\eqalign{
\int_n^\infty x \exp(-ax^2+bx+c)\,dx
&= \int_n^\infty\kern-5pt x \exp( -a(x-{\textstyle{b\over 2a})^2 +c+{b^2\over 4a} }  )\,dx\cr
&= \alpha \int_n^\infty\kern-5pt  x \exp( \textstyle {-(x-{\textstyle{b\over 2a})^2   }\over 1/a } )\,dx\cr
&=  \alpha \int_n^\infty\kern-5pt   (x+{\textstyle{b\over 2a}-{b\over2a}}) \exp( \textstyle {-(x-{\textstyle{b\over 2a})^2   }\over 1/a } )\,dx\cr
&=\alpha \int_n^\infty\kern-5pt   (x { -{\textstyle{b\over2a}}}) \exp( {\textstyle {-(x-{\textstyle{b\over 2a})^2   }\over 1/a }} )\,dx
+ \alpha\int_n^\infty\kern-5pt   \textstyle{b\over2a}  \exp( \textstyle {-(x-{\textstyle{b\over 2a})^2   }\over 1/a } )\,dx,\cr
}
$$
where $\alpha=\exp(c+{b^2\over4a})$.
On the right hand side of the last equality above, the first integral can be evaluated using the substitution $u=x-{b\over 2a}$ and the second integral can be expressed in terms of the cumulative distribution function of an appropriate normal random variable.

A: Hint: Since
$\frac{\mathrm d}{\mathrm dx}\exp(-ax^2+bx+c) = (-2ax+b)\exp(-ax^2+bx+c)$, you can
massage the given integrand to something of the form
$$\frac{-1}{2a}\int (-2ax+b)\exp(-ax^2+bx+c)\ \mathrm dx
+ \int \frac{b}{2a}\exp(-ax^2+bx+c)\ \mathrm dx$$
where the first integral now has a perfect integrand and the second,
after further massaging will give
you something involving $\Phi(\cdot)$, the cdf of the standard normal
(Gaussian) random variable. Note that @Wonder's answer does not get
the second term.


text:
Q: Magento - Can I get the standard WYSIWYG editor to work for category descriptions? I would like to use the standard WYSIWYG editor for the category text in Magento. Or at least to have the option. Is there an easy way to 'enable' this, rather than use 3rd party plugins?

A: Even after enabling the System Configuration setting, I had to enable WYSIWYG on the Category Description field on my 1.4.x.x installation. It was a simple database update.
You need to find the attribute ID for the Category Description.
Using phpMyAdmin, browse the eav_attribute table and find your entity_type_id 3 items. Look for attribute_code=description and entity_type_id=3. You should have an attribute_id like 34.
Now go browse the catalog_eav_attribute table and look for the attribute_id you found above. Scroll over to the is_wysiwyg_enabled column. This holds a boolean, 0=disabled, 1=enabled. Change it from 0 to 1, go flush cache and you should now be able to use the WYSIWYG editor in your category description field.

A: For which text? For the category description you have the build in WYSIWYG editor. You can enable this at System -> Configuration -> Content Management -> WYSIWYG Options. By default it's enabled.
Regards

A: Instead of editing stuff in the database as Fiasco Labs suggests.
You can go into Catalog -> Attributes -> Manage Attributes.
Search for the field you're trying to edit (ie: Description.)
And then change the value of 'Enable WYSIWYG' from 'No' to 'Yes'.
This is the same thing but without doing it directly in the database.

A: Easier way to do this would be to go to Admin > Catalog > Attributes > Manage Attributes. Select the attribute, and set Enable WYSIWYG to Yes.


text:
Q: Upload an audio file on node.js, add audio visualisation (with three.js) and save the new file to a video file I would like to upload an audio file to a node server, and create an animation with three js (audio visualization) and make the new file a video file.
(an exemple of audio visualisation : https://www.youtube.com/watch?v=l7iHvXq4hEE)
I found some solutions to make that happen on the client-side with Tone.js or three.js, then record the audio visualization from the browser in "real-time", and send it back to the server,
like this one : https://gracexu94.github.io/FinalProject/
but this is happening in "real time" and I would like here to be able to upload audio of 40minutes without having to wait this amount of time before to get the file back,,,
Any ideas for this process ?
Thank you!


text:
Q: How to pass a file type input into javascript and use it into another php page? Hello and good day everyone! I am here to ask on how to pass a file type using javascript, so that I can use it to another php page. The following is an input for type file:
<input type="file" name="imgCompany" id="imgCompany">

I am getting the file like this in php:
$file = $_FILES['imgCompany']['tmp_name'];

The first question I have to ask is how can I get the $file variable to be place in a javascript function? (same php page). So far this was my attempt to do so:
function addImage() {
  var companyImage = $('#imgCompany').val();
}

The second question I have to ask how do I pass that file value once it is declared in the addImage() function using a method like this:
$.post('addImage.php', {postimage:file},
function(data)
{
    //returns the echoed value from the php file
    $('#result').html(data);
});

Or is there another way?
I am going to use what I pass from the post to another php page, so I can upload that image into a database. I am uploading this image into a database like this:
    ...
    $image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
    //$image_name = addslashes ($_FILES['image']['name']);
    $image_size = getimagesize($_FILES['image']['tmp_name']);

    if ($image_size == FALSE)
        echo "
No Image was Selected
";
    else {

        if (!$insert = $db->query ("INSERT INTO company VALUES('','$companyName','$image')"))
            echo "
Problem uploading the image
";
    else {
        echo "
Company Account successfully created
";
    }

}

A: I cannot read JQuery (nor do I want to), but here are a few pointers:
The file name in file-upload: javascript-how-to-extract-filename-from-a-file-input-control
The second question I have to ask how do I pass that file value once it is declared in the addImage() function using a method like this:
You don't have to, the file will be send in the form you are sending.
I do not understand what you are trying to accomplish by adding javascript to that. The original filename will also be send to the server. (Inspect the $_FILES on arrival to see it for yourself)
About the insertion in the database:
addslashes? Really? Escape it in another way, preferable with the quotation/escape functionality delivered with your database.
And another thing: If you go to "another page" your $_FILES will be empty. Handle it on arrival, not after invoking a new page. I am not sure what or how you are doing it, but keep that in mind when you see an empty $_FILES while you expected some information in it. :-)


text:
Q: where is my __dict__? Class inherited from a namedtuple When I inherit a class from a namedtuple, why the __dict__ is empty? Here are minimal codes prepared to show. You can see that x.__dict__ is empty, but z.__dict__ has the information.
from collections import namedtuple
Person = namedtuple('Person', 'name age')

class Student(Person):
    def print(self):
        print(self.name)

x = Student("Tom",25)

class Employee:
    def __init__(self,name, age):
        self._name = name
        self._age = age
y = Employee("Jerry",24)

class MyEmployee(Employee):
    def print(self):
        print(self._name)
z = MyEmployee("John",22)

print(x.__dict__)
print(y.__dict__)
print(z.__dict__)

Here is the output
{}
{'_name': 'Jerry', '_age': 24}
{'_name': 'John', '_age': 22}

A: In short: there isn't one to begin with. You can test it by checking Person("Alice", 21).__dict__ or even just ("Alice", 21).__dict__, and you will see that both of them raise AttributeError. If you look at the source code of namedtuple, you will see that the construtor (__new__()) of a namedtuple is identical as that of a tuple. And if you look at the source code of tuple.__new__, you will find that no __dict__ has ever been created.
The empty dict you see comes from the fact that you subclassed a namedtuple. The later two were populated inside your __init__ functions. But since nothing is done during your initializer in your Student class, its __dict__ is empty.

A: TLDR: Tuples do not need __dict__ to store values. By default, inheriting from a type class (including object and tuple) adds a __dict__ however.

The __dict__ is an implementation detail used by certain types of objects to store attribute values. Notably, tuples do not use __dict__ to store their values:
>>> joe = ("Joe", 24)
>>> joe[0]        # values available as item
"Joe"
>>> joe.__dict__  # no dict for values
...
AttributeError: 'tuple' object has no attribute '__dict__'

As the name implies, namedtuple are kind of tuples and as such also do not have __dict__. Their attributes are merely aliases to index-lookups, pointing to the same value.
>>> jane = namedtuple("Person", ["name", "age"])("Jane", 24)
>>> jane[0]        # values available as item
"Jane"
>>> jane.name      # values available as item alias
"Jane"
>>> jane.__dict__  # no dict for values
...
AttributeError: 'Person' object has no attribute '__dict__'

The __dict__ attribute is commonly added by the act of inheriting any object. One must define explicit __slots__ to prevent this.
>>> # base object has no __dict__
>>> object().__dict__
AttributeError: 'object' object has no attribute '__dict__'
>>> # inheritance adds __dict__
>>> class ObjectWithDict(object): pass
>>> DictObject().__dict__
{}
>>> # __slots__ prevent adding __dict__
>>> class ObjectWoDict(object): __slots__ = ()
>>> ObjectWoDict().__dict__
AttributeError: 'ObjectWoDict' object has no attribute '__dict__'
>>> # inheritance adds __dict__ – even to __slots__
>>> class ObjectMaybeDict(ObjectWoDict): pass
>>> ObjectMaybeDict().__dict__
{}

The x.__dict__ comes from inheriting Student from Person. It contains no data, since that is already handled by the underlying tuple.
One can understand how Student works by emulating it via inheriting from tuple, aliasing fields via property, but not preventing the creation of __dict__.
>>> class Person(tuple):
...     # no __slots__ -> a __dict__ is added
...     @property
...     def name(self):     # attributes are aliases ...
...         return self[0]  # ... to items in the tuple
...     @property
...     def age(self):
...         return self[1]
...     def __new__(cls, name, age):
...         return super().__new__(cls, (name, age))
...
>>> jimmy = Person("Jimmy", 12)
>>> jimmy[0]    # item access as expected for tuple
"Jimmy"
>>> jimmy.name  # attribute access – that we implemented as item access
"Jimmy"
>>> jimmy.__dict__
{}


text:
Q: Python on Php import troubles
I'm calling a py script from php and everything seems ok untill I import cv2, then the troubles start.
Situation:

*1# I have a folder test/ with test.php and test_script.py.
test.php:
<?php

$command = escapeshellcmd( 'python test_script.py' );
$output = shell_exec($command);

echo $output;

test_script.py:
import os
import json
import numpy as np
import cv2
print('pol')

*
2# If I run it I visualize nothing in test/test.php; instead if I comment "import cv2" it runs perfectly visualizing "pol" as output.

*
3# The path variable called by php is the same called by cmd (yes, windows..)

*4# in cmd I can easily call:
> python test_script.py

and it works fine

Specs
Php:7.2.2
Python: 3.6.5 on Anaconda3
So, how can I make it work the same on php?? Why is not working even if in cmd it works?
Thank you in advance

Update #1
my sdout returns:
Traceback (most recent call last):
    File "predict_test.py", line 10, in
      import cv2
  ImportError: DLL load failed: Access is denied.

but I already set Full control permissions by Users and System, on Anaconda3 folder.


text:
Q: How to set specific language in iOS simulator? I've done this so far:

But I still get language set to english:

Does anyone know if I'm missing something?

edit:
If I do this:
- (void)logAllLocales
{
   NSLocale *curentLocale = [NSLocale currentLocale];
   NSArray *locales = [[NSLocale availableLocaleIdentifiers] sortedArrayUsingSelector:@selector(compare:)];
   for (NSString *locale in locales)
   NSLog(@"locale '%@' is: %@'", locale, [curentLocale displayNameForKey:NSLocaleIdentifier value:locale]);
}

result:
'sv' is: Swedish'
'sv_FI' is: Swedish (Finland)'
'sv_SE' is: Swedish (Sweden)'
I'll get three swedish locale options so technically "sv" should do. But I also tested the other options without luck.
But if the simultor need a reset to change the Lanugage then I think my question is answeded. It's not possible with arguments passed in on launch. =)

A: It's the same procedure you use in physical device.
Go in Settings > General > International and change the Language from English to Swedish

Edit based on 3rd comment in the question

Well the thing is that I deploy to simulator a lot. And before every deploy I usually want to clean the whole simulator with a hoy-key: I've connected "Reset Content and Settings..." to cmd+K. This makes the simulator reset back to english language even if I set it explicitly via the very obvious way pointed out below. (Settings > General > International) I really want it to be an argument passed on launch. Its a very tedious way to do it manually every single time, especially when Im working only with swedish, norweigan and danish at the moment. =)

Try to replace in Localizable.string (En) the entire content with the Swedish / Norvegian and Danish content. So the simulator is in English, read from English string file but show content in another language.

A: I have Xcode 13.2.1 & was able to configure the app language by modifying the scheme options.

*

*Edit Scheme > Options > Application Language

The app will launch with the language settings you provide.
No need to change it manually from the simulator setting.

Credits:

*

*https://medium.com/swlh/app-localization-in-swift-ios-swift-guide-baa2c2e4298e

A: If i got you right, to change the simulator language you just need to change it from the "language" option on simulator screen shot that you have attached. tap it and select the language that you want.

A: As said in my last edit. I think this is not possible since the simulator must reset to actually change system language.


text:
Q: Trouble with setting up vscode Theme color I've installed iceberg theme extension on vscode, and spend decent amount of time to figure out how to change the color of line number in the way to be the same like code section background color. What I have
I want something like in dark+ (default dark) where both sections have same color
What I would like to have
Is it possible to override only line number column color?

A: there are 2 workbench colors for line numbers

*

*editorLineNumber.foreground

*editorLineNumber.activeForeground
Set both color names to the same color in your settings.json file specific for this theme.

A: After some more searching I found editorGutter.background responsible for setting that thing

A: You can add these to your settings.json:
"workbench.colorCustomizations": {
"editorLineNumber.froeground":         ,
"editorGutter.background":             ,
"editorCursor.foreground":             ,
},

Choose the color you like and save the changes. Hope hepful.


text:
Q: java netbeans java.lang.NullPointerException error I am developing a software for my academic purpose. For that I am using Netbeans IDE,sqlite. When I run the code it gives me following error,
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1838)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at ProductInfo.getProductList(ProductInfo.java:109)
at ProductInfo.Show_Products_In_JTable(ProductInfo.java:126)
at ProductInfo.<init>(ProductInfo.java:44)
at ProductInfo$12.run(ProductInfo.java:658)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

And here is the code,
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

public class ProductInfo extends javax.swing.JFrame {

Connection conn=null;
ResultSet rs = null;
PreparedStatement pst=null;

public ProductInfo() {
initComponents();
conn=JavaConnect.ConnectDb();
Show_Products_In_JTable();

}
String imgpath=null;
int pos = 0;

public boolean checkInputs()
{
if(
      txt_name.getText() == null
   || txt_price.getText() == null
   || txt_AddDate.getSelectedDate().getTime() == null
  ){
    return false;
}
else{
    try{
        Double.parseDouble(txt_price.getText());

        return true;
    }catch(Exception ex)
    {
        return false;
    }
}
}

ImageIcon ResizeImage(String imagePath, byte[] pic)
{
ImageIcon myImage = null;

if(imagePath != null)
{
    myImage = new ImageIcon(imagePath);
}else{
    myImage = new ImageIcon(pic);
}

Image img = myImage.getImage();
Image img2 = img.getScaledInstance(lbl_img.getWidth(), lbl_img.getHeight(), Image.SCALE_SMOOTH);
ImageIcon image = new ImageIcon(img2);
return image;

}

 public ArrayList<Product> getProductList()
{
    ArrayList<Product> productList  = new ArrayList<Product>();

    Connection conn=JavaConnect.ConnectDb();;
    ResultSet rs;
    PreparedStatement pst;

try {
    String sql = "SELECT * FROM ProductInfo";
    pst=conn.prepareStatement(sql);
    rs=pst.executeQuery();
    Product product;

    while(rs.next())
    {
        product = new Product(rs.getInt("ProductId"),rs.getString("Name"),Double.parseDouble(rs.getString("Price")),rs.getString("Date"),rs.getBytes("Image"));
        productList.add(product);
    }

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

return productList;

}

public void Show_Products_In_JTable()
{
ArrayList<Product> list = getProductList();
DefaultTableModel model = (DefaultTableModel)JTable_Products.getModel();
// clear jtable content
model.setRowCount(0);
Object[] row = new Object[4];
for(int i = 0; i < list.size(); i++)
{
    row[0] = list.get(i).getId();
    row[1] = list.get(i).getName();
    row[2] = list.get(i).getPrice();
    row[3] = list.get(i).getAddDate();

    model.addRow(row);
}

}

public void ShowItem(int index)
{
   txt_id.setText(Integer.toString(getProductList().get(index).getId()));
    txt_name.setText(getProductList().get(index).getName());
    txt_price.setText(Double.toString(getProductList().get(index).getPrice()));

try {
   Date addDate = null;
    addDate = new SimpleDateFormat("yyyy-MM-dd").parse((String)getProductList().get(index).getAddDate());

    txt_AddDate.getSelectedDate().setTime(addDate);

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

lbl_image.setIcon(ResizeImage(null, getProductList().get(index).getImage()));
}
private void btn_deleteActionPerformed(java.awt.event.ActionEvent evt) {
 if(!txt_id.getText().equals(""))
{
    try {
        String sql = "DELETE FROM ProductInfo WHERE ProductId = ? ";
        pst=conn.prepareStatement(sql);
        pst.execute();

        int id = Integer.parseInt(txt_id.getText());
        pst.setInt(1, id);
        pst.executeUpdate();
        Show_Products_In_JTable();
        JOptionPane.showMessageDialog(null, "Product Deleted");
    }
    catch (SQLException ex) {
        Logger.getLogger(ProductInfo.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "Product Not Deleted");
    }

}else{
    JOptionPane.showMessageDialog(null, "Product Not Deleted : No Id To Delete");
}
}
private void btn_insertActionPerformed(java.awt.event.ActionEvent evt) {

if(checkInputs() && imgpath != null)
{
    try {

        String sql = "INSERT INTO ProductInfo(Name,Price,Date,Image) values(?,?,?,?) ";
        pst=conn.prepareStatement(sql);
        pst.execute();

        pst.setString(1, txt_name.getText());
        pst.setString(2, txt_price.getText());

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String addDate = dateFormat.format(txt_AddDate.getSelectedDate().getTime());

        pst.setDate(3, java.sql.Date.valueOf(addDate));

        InputStream img = new FileInputStream(new File(imgpath));

        pst.setBlob(4, img);

        pst.executeUpdate();
        Show_Products_In_JTable();

        JOptionPane.showMessageDialog(null, "Data Inserted");
    } catch (Exception ex) {
         JOptionPane.showMessageDialog(null, ex.getMessage());
    }
}else{
    JOptionPane.showMessageDialog(null, "One Or More Field Are Empty");
}
System.out.println("Name => "+txt_name.getText());
System.out.println("Price => "+txt_price.getText());
System.out.println("Date => "+txt_AddDate.getSelectedDate().getTime());
System.out.println("Image => "+imgpath);
}

private void btn_ImageActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System.getProperty("user.home")));

FileNameExtensionFilter filter = new FileNameExtensionFilter("*.images", "jpg","png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION)
{
    File selectedFile = file.getSelectedFile();
    String path = selectedFile.getAbsolutePath();
    lbl_img.setIcon(ResizeImage(path, null));
    imgpath = path;
}
else{
    System.out.println("No File Selected");
}
}

private void btn_updateActionPerformed(java.awt.event.ActionEvent evt) {
if(checkInputs() && txt_id.getText() != null)
{

    // update without image
    if(imgpath == null)
    {
        try {
            String sql = "UPDATE ProductInfo SET Name = ?, Price = ?"
                    + ", Date = ? WHERE ProductId = ?";
            pst=conn.prepareStatement(sql);
            pst.execute();

            pst.setString(1, txt_name.getText());
            pst.setString(2, txt_price.getText());

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String addDate = dateFormat.format(txt_AddDate.getSelectedDate().getTime());

            pst.setDate(3, java.sql.Date.valueOf(addDate));

            pst.setInt(4, Integer.parseInt(txt_id.getText()));

            pst.executeUpdate();
            Show_Products_In_JTable();
            JOptionPane.showMessageDialog(null, "Product Updated");

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

    }
    // update With Image
    else{
        try{
        InputStream img = new FileInputStream(new File(imgpath));

         String sql = "UPDATE ProductInfo SET Name = ?, Price = ?"
                    + ", Date = ? WHERE ProductId = ?";
            pst=conn.prepareStatement(sql);
            pst.execute();

            pst.setString(1, txt_name.getText());
            pst.setString(2, txt_price.getText());

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String addDate = dateFormat.format(txt_AddDate.getSelectedDate().getTime());
            //pst.setString(3, addDate);
            pst.setDate(3, java.sql.Date.valueOf(addDate));

            pst.setBlob(4, img);

            pst.setInt(5, Integer.parseInt(txt_id.getText()));

            pst.executeUpdate();
            Show_Products_In_JTable();
            JOptionPane.showMessageDialog(null, "Product Updated");

        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }
}else{
    JOptionPane.showMessageDialog(null, "One Or More Fields Are Empty Or Wrong");
}

}

Here are the variable declaration,
// Variables declaration - do not modify
private javax.swing.JTable JTable_Products;
private javax.swing.JButton btn_Image;
private javax.swing.JButton btn_delete;
private javax.swing.JButton btn_first;
private javax.swing.JButton btn_insert;
private javax.swing.JButton btn_last;
private javax.swing.JButton btn_next;
private javax.swing.JButton btn_previous;
private javax.swing.JButton btn_update;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lbl_date;
private javax.swing.JLabel lbl_id;
private javax.swing.JLabel lbl_image;
private javax.swing.JLabel lbl_img;
private javax.swing.JLabel lbl_name;
private javax.swing.JLabel lbl_price;
private datechooser.beans.DateChooserCombo txt_AddDate;
private javax.swing.JTextField txt_id;
private javax.swing.JTextField txt_name;
private javax.swing.JTextField txt_price;
// End of variables declaration

And this is the entity class,
public class Product {
private int id;
private String name;
private double price;
private String addDate;
private byte[] picture;

public Product(int pid, String pname, double pprice, String pAddDate, byte[] pimg)
{
    this.id = pid;
    this.name = pname;
    this.price = pprice;
    this.addDate = pAddDate;
    this.picture = pimg;

}

public int getId()
{
    return id;
}

public String getName()
{
    return name;
}

public double getPrice()
{
    return price;
}

public String getAddDate()
{
    return  addDate;
}

public byte[] getImage()
{
    return picture;
}

I am a beginner and don't understand the error. Anyone please help me how to solve it?


text:
Q: getting error in running cmake std Tutorial step 2 example I am totally new to cmake and its syntax .But fortunately I am able to run the cmake tutorial step 1 as per the introductions mention on below links  :
https://cmake.org/cmake/help/latest/guide/tutorial/index.html
But I am totally stucked at step 2 project to run using cmake.
I have created the step 2 project and understand the syntax to link the library for doing square root of a number, But I did not understand how to run this as I am getting below error :
user@server:~/TER_CMAKE/Tutorial/step2_build$ cmake ../step2
CMake Error at CMakeLists.txt:19 (add_subdirectory):
  The binary directory

    /home/user/TER_CMAKE/Tutorial/step2/MathFunctions

  is already used to build a source directory.  It cannot be used to build
  source directory

    /home/user/TER_CMAKE/Tutorial/step2/MathFunctions

  Specify a unique binary directory name.

-- Configuring incomplete, errors occurred!

The example is available at below location for step 2 under heading Adding a Library (Step 2)..
https://moodle.rrze.uni-erlangen.de/pluginfile.php/14829/mod_resource/content/5/CMakeTutorial.pdf
My intention is to run my example this way
 step2_build$ cmake ../step2
 step2_build$ cmake --build .
 step2_build$ ./Tutorial 121

As I am not sure that is it good to ask this way on this platform ,But as I do not have any other guidance .I am doing this by my own .
Note: I do not wants to use any tool to run my step 2 example.I wants to run everything using command prompt and cmake command only .where I can understand the cmake .
Edit:
Adding my CMakeLists.txt =
cmake_minimum_required(VERSION 3.5)

#set the project name
project(Tutorial VERSION 1.0)

#specify the c++ std
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)

option(USE_MYMATH "Use tutorial provided math implementation" ON)

#Configure a header file to pass the version number to the source code
configure_file(TutorialConfig.h.in TutorialConfig.h)

#add the MathFunctions Library
add_subdirectory(MathFunctions)

if(USE_MYMATH)
    add_subdirectory(MathFunctions)
    list(APPEND EXTRA_LIBS MathFunctions)
    list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/MathFunctions")
endif()

#add the executable
add_executable(Tutorial tutorial.cpp)

target_link_libraries(Tutorial PUBLIC ${EXTRA_LIBS})

# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
target_include_directories(Tutorial PUBLIC
                           "${PROJECT_BINARY_DIR}"
                           ${EXTRA_LIBS}
                          )

My Source tutorial.cpp file:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>

#ifdef USE_MYMATH
#include "MathFunctions.h"
#endif
#include "TutorialConfig.h"

using namespace std;

int main(int argc, char* argv[])
{
  if (argc < 2) {
    cout << "Usage: " << argv[0] << " number" << endl;
    return 1;
  }

  // convert input to double
  const double inputValue = atof(argv[1]);

  // calculate square root
#ifdef USE_MYMATH
  const double outputValue = mysqrt(inputValue);
#else
  const double outputValue = sqrt(inputValue);
#endif
  cout << "The square root of " << inputValue << " is " << outputValue << endl;
  return 0;
}

ToturialConfig.h.in file :
#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@

#cmakedefine USE_MYMATH

EDIT:
Step2 has a folder MathFuctions,Which has Cmake file mysqrt.cpp file
/TER_CMAKE/Tutorial/step2/MathFunctions/CMakeLists.txt
add_library(MathFunctions mysqrt.cpp)

/TER_CMAKE/Tutorial/step2/MathFunctions/mysqrt.cpp
#include <iostream>

// a hack square root calculation using simple operations
double mysqrt(double x)
{
  if (x <= 0) {
    return 0;
  }

  double result = x;

  // do ten iterations
  for (int i = 0; i < 10; ++i) {
    if (result <= 0) {
      result = 0.1;
    }
    double delta = x - (result * result);
    result = result + 0.5 * delta / result;
    std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
  }
  return result;
}

A: In case USE_MYMATH variable is set add_subdirectory(MathFunctions) is invoked twice. You need to decide and remove one of the occurrences on lines 16 and 19 in you CMakeLists.txt.

A: Two issues I can see:

*

*You're adding the subdirectory "MathFunctions" twice when you configure the build with -DUSE_MYMATH=ON. This is why you are getting "CMake Error at CMakeLists.txt:19 (add_subdirectory):"

To fix, remove
#add the MathFunctions Library
add_subdirectory(MathFunctions)

and rely on
if(USE_MYMATH)
    add_subdirectory(MathFunctions)
    list(APPEND EXTRA_LIBS MathFunctions)
    list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/MathFunctions")
endif()

*In your CMakeLists.txt file, you are doing

target_include_directories(Tutorial PUBLIC
                           "${PROJECT_BINARY_DIR}"
                           ${EXTRA_LIBS}
                          )

Instead of
${EXTRA_LIBS}

It should be
${EXTRA_INCLUDES}

A: in Discourse Cmake Org -- help with tutorial step 2
Josef Angstenberger
jtxa said

The files in Step3 are the expected result if you do everything from Step2.
Can you please compare your files against the ones from Step3 to see if there are any relevant differences?

Blockquote

Marshallb's solution will solve nahesh relkar's problem
Loading Step2/CMakeLists.txt and Step3/CMakeLists.txt into  vimdiff helped me to fix mine


text:
Q: Google Maps Api v2 Android Error loading map on Play Store I am working with google maps API but when i upload my APK to Play Store my map doesn't load, when i run my app directly on my device it works perfect. When i generate my Signet APK and test it on my device (without Play Store, just sending my APK to my device and installing it manually) it works perfect, but if i publish the exactly same APK to Play Store it isnt visible after i downloaod it.
my app gradle
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "development.senseit.com.mapasinteca"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 102
        versionName "1.0.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    signingConfigs {
        release {
            storeFile file('C:\\Users\\jsalazar\\Desktop\\Certificados\\Android\\mapasInteca.jks')
            storePassword '****'
            keyAlias 'mapasinteca'
            keyPassword '****'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.release
        }
        release {
            signingConfig signingConfigs.release
        }
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.google.android.gms:play-services-maps:11.6.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:design:26.1.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
}

My google API key is correct.
I have 2 finger print certificate added to google console, one for debug and one for release (i already trying removing the debug one).

A: I solved my problem adding one SHA-1 that i was missing, it was on Google Play Console (number 1 on image) i was only adding number 2


text:
Q: Troubles with the Bibliography I'm having a problem with th following code. The error is:

Package natbib Error: Bibliography not compatible with author-year citations. ...mand\NAT@force@numbers{}\NAT@force@numbers

\documentclass[12pt,a4paper, spanish]{article}
\usepackage{float}
\usepackage{cite} %referencias
\usepackage[spanish]{babel}
\usepackage{ragged2e} %alineamineto %\begin{center,flushleft,flushright} %endtal y cual
\usepackage[utf8]{inputenc} % Ambos para solución de asuntos de idioma
\usepackage[T1]{fontenc}
\usepackage[usenames]{color} %letra en color
\usepackage{tocbibind} % Bibliografía en el indice
\usepackage{titlesec} % Posibilidad de editar los formatos de chapter
\usepackage{amsmath,amssymb,mathrsfs} % Matemáticas varias
\usepackage[margin=1cm,font=footnotesize,labelfont=bf]{caption}
\usepackage[bottom]{footmisc} %los pies de pagina se pegan al fondo de la página
% Arreglos varios para la inclusion de imagenes
%\usepackage[pdftex]{graphicx}
\usepackage[dvips]{graphicx}
%\usepackage{epstopdf}
\usepackage{graphicx}
\usepackage{subfig}
\usepackage[usenames,dvipsnames,table]{xcolor}
\DeclareGraphicsExtensions{.eps}
\DeclareGraphicsExtensions{.png,.jpg,.pdf,.mps,.gif,.bmp}
\graphicspath{{C:/Users/Administrador/OneDrive/Temasuni/cuarto/TFG/Texto/Fotos/}}
%\graphicspath{{/Users/dani/SkyDrive/Temas uni/3º/Primer Cuatrimestre/Laboratorio de optica/Práctica 6/Graficos/}}
% Para las dimensiones de los márgenes etc
\frenchspacing \addtolength{\hoffset}{-1.5cm}
\addtolength{\textwidth}{3cm} \addtolength{\voffset}{-2.5cm}
\addtolength{\textheight}{4cm}
\topmargin 2cm
% Para el encabezado
\usepackage{fancyhdr}
\fancyhead[R]{07/10/2016}\fancyhead[L]{Encabezado} \fancyfoot[C]{\thepage}
\pagestyle{fancy}
%-- Definir el numero de las secciones a mi estilo.
\renewcommand{\thesection}{\textit{\arabic{section}}}
\renewcommand{\thesubsection}{\textit{\thesection.\arabic{subsection}}}
\renewcommand{\thesubsubsection}{\textit{\thesubsection.\arabic{subsubsection}}}
\renewcommand{\theequation}{\textbf{\arabic{equation}}}
\usepackage{booktabs}
\usepackage{colortbl}
\usepackage{longtable}
\usepackage{footnote}
\usepackage{natbib}

\begin{document}
    \begin{titlepage}
        \begin{center}
            \begin{huge}
                \vspace*{\fill}

                %Aqui va el titulo

            \end{huge}
            \rule{80mm}{0.1mm}\\
            \rule{80mm}{0.1mm}\\

            %nombre
            \vspace{7pt}

            \vspace*{\fill}
        \end{center}
    \end{titlepage}

    \tableofcontents
    \pagebreak
    \section{Abstract/Resumensicoh}
    \section{Introducción teórica}
    \subsection{Objetivos}
    \subsection{Desarrollo del trabajo}

    A la hora de estructurar este trabajo he querido seguir un método inductivo, comenzando por una explicación de todos los conceptos hidrológicos, tecnológicos y geoestadísticos que se van a utilizar para el desarollo de los objetivos. Tendremos tres partes diferenciadas: la física del agua en el suelo, en concreto, el contenido de agua del suelo (humedad) como variable fundamental; los métodos geoestadísticos necesarios para la validación y, finalmente, la herramienta donde los tenemos implementados: ArcGis. Posteriormente expondremos como son nuestros datos y qué tratamiento les  hemos dado. Finalizando con una exposición de los resultados obtenidos y las conclusiones obtenidas.

    \subsection{Introducción a la física del suelo}

    Debido a que  el objetivo principal de este trabajo es validar medidas de humedad  del suelo, merece la pena dar un esbozo del enfoque físico que se le puede dar al comportamiento del agua dentro del suelo y, en concreto, el vital papel juega la humedad del suelo para su estudio. Con mucho más detalle  se explica en \cite{SP} y
    %Está es una parte del sistema complejo que es el suelo

    \vspace{15pt}

    La primera pregunta qué hemos de contestar es qué entendemos por suelo y qué papel juega el agua en él. Como sistema físico el suelo es una mezcla de sustancias en los tres estados de la materia, es un sistema de tres fases, cada una de ellas fundamental para su otorgarle las propiedades extraordinarias  que presenta.

    \begin{itemize}
        \item \textbf{Fase sólida.} En estado sólido se encuentran tanto minerales de diferentes tamaños y composiciones como  materia orgánica (residuos en estado de descomposición y organismos vivos).Desde un pyunto de vista físico dicha parte sólida está formada por partículas individuales que llamamos 'texturales' que  se agrupan en pequeños gránulos de  diferente tamaño \footnote{Desde el límite del tamaño coloidal  $10^{-5}-10^{-9}$ m hasta partículas del orden de los centímetros} que  son lo que conocemos como unidades estructurales de suelo \cite{SP}. Estos gránulos se encuentran separados unos de otros, dejando unos intersticios de tamaño también variable. Es en dichos intersticios es donde se pueden alojar la fase líquida y sólida del suelo.

        \begin{figure}[htb]
            \begin{center}
                \includegraphics{a.jpg} % include ./img/imagen.[pdf|png|jgp] si es pdflatex o ./img/imagen.eps si es latex7

            \end{center}
            \caption{Esquema medidas osciloscopio}

            \label{medidaosci}
        \end{figure}

        La clasificación que se hace de los suelos atiende al tamaño de dichos gránulos y  la composición en marteria orgánica de estos:

    \item \textbf{Fase líquida.} n

    \item \textbf{Fase Gaseosa}n
        \end{itemize}

    \subsection{Humedad del Suelo. Medida}

    \subsubsection{Métodos \textit{in situ}}
    \subsubsection{Métodos Telemáticos: SMAP y SMOS}

    \subsection{Geoestadística. Métodos de Interpolación Espacial}

    \subsubsection{IDW}
    \subsubsection{Krigin}
    \subsubsection{Vecino Natural}
    \subsubsection{Krigin}
    \subsubsection{ArcGis}

    \section{Tratamiento de Datos}

    \section{Resultados}

    \section{Conclusiones}

    \bibliographystyle{acm}
    \bibliography{biblio}

\end{document}

A: Well, I reduced your given code to be minimal.  With the following MWE (see the commented package natbib please!)
\RequirePackage{filecontents}
\begin{filecontents}{\jobname.bib}
@Book{Goossens,
  author    = {Goossens, Michel and Mittelbach, Frank and
               Samarin, Alexander},
  title     = {The LaTeX Companion},
  edition   = {1},
  publisher = {Addison-Wesley},
  location  = {Reading, Mass.},
  year      = {1994},
}
@Book{adams,
  title     = {The Restaurant at the End of the Universe},
  author    = {Douglas Adams},
  series    = {The Hitchhiker's Guide to the Galaxy},
  publisher = {Pan Macmillan},
  year      = {1980},
}
@article{feynman,
  title     = {Very High-Energy Collisions of Hadrons},
  author    = {Richard P. Feynman},
  journal   = {Phys. Rev. Lett.},
  volume    = {23},
  issue     = {24},
  pages     = {1415--1417},
  year      = {1969},
  month     = {Dec},
  doi       = {10.1103/PhysRevLett.23.1415},
  url       = {http://link.aps.org/doi/10.1103/PhysRevLett.23.1415},
  publisher = {American Physical Society},
}
\end{filecontents}

\documentclass[12pt,a4paper, spanish]{article}

\usepackage[spanish]{babel}

\usepackage[utf8]{inputenc} % Ambos para solución de asuntos de idioma
\usepackage[T1]{fontenc}

\usepackage{cite} %referencias
%\usepackage{natbib}

\begin{document}

\nocite{*}
\bibliographystyle{acm}
\bibliography{\jobname} % to use the bibfile created by filecontents

\end{document}

I can compile the code without errors with your used style acm. And get the result

Please not that style acm and natbib can not be used together!


text:
Q: What should the transactionReceipt verification json look like? I'm trying to verify a sandbox transactionReceipt at https://sandbox.itunes.apple.com/verifyReceipt using php and cURL.
The original receipt when it arrives at my server looks like:
{ "signature" = "AksOP5dmXwg 9WjlcE7PwBEFZgcqBnIb0Uv2lSKebWJJpcOZQRL6ejYyv20MzPFDSgAj3GRGoJXWZpyJLAU8qZSQFYQeGljWKZd3XTJN4j1E7fqOQRBdIXSDRJr1phB/11xp smk6m ... dgcxRHuOMZ2tm8npLUm7argOSzQ=="; "purchase-info" = "ewoJIml0ZW0taWQiID0gIj ... jAiOwp9"; "pod" = "100"; "signing-status" = "0"; }

1. Should it have the equals and semicolons?
Wrapping this up for transmission in the cURL I use:
$receipt = json_encode(array("receipt-data" => base64_encode($transactionReceipt)));

which gives:
{"receipt-data":"ewoJInNpZ25hdHVyZSIgPSAiQ ... <lots more of the same> ... XR1cyIgPSAiMCI7Cn0="}

This results in: {"status":-42023} from Apple
If I use:
$receipt = json_encode(array("receipt-data" => $transactionReceipt));

which gives:
{"receipt-data":"{\n\t\"signature\" = \"AksOP5dmXwg 9WjlcE7PwBEFZgcqBnIb0Uv2lSKebWJJpcOZQRL6ejYyv20MzPFDSgAj3GRGoJXWZpyJLAU8qZSQFYQeGljWKZd3XTJN4j1E7fqOQRBdIXSDRJr1phB\/11xp smk6m ... dgcxRHuOMZ2tm8npLUm7argOSzQ==\";\n\t\"purchase-info\" = \"ewoJIml0ZW0taWQiID0gIjM3NTgyNzIyOCI7Cgkib3JpZ2luYWwtdHJhbnNhY3Rpb24taWQiID0gIjEwMDAwMDAwMDA1ODQyNDIiOwoJInB1cmNoYXNlLWRhdGUiID0gIj ... jAiOwp9\";\n\t\"pod\" = \"100\";\n\t\"signing-status\" = \"0\";\n}"}

I get: {"status":21002, "exception":"java.lang.IllegalArgumentException: Property list parsing failed while attempting to read unquoted string. No allowable characters were found. At line number: 1, column: 0."}
2. Can anyone please tell me what the receipt-data json is supposed to look like?
Thanks!

A: I was banging with my head against the walls with the same problem... check this:
$dataToPost = json_encode(array("receipt-data" => $receivedData));

where $receivedData is the receipt base64 encoded.
Then:
$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $dataToPost
    )
);

$context  = stream_context_create($opts);
$result = file_get_contents('https://sandbox.itunes.apple.com/verifyReceipt', false, $context);

It worked for me... give it a try and let me know!

A: This is now working for me! My final bug was that I had, in series of tests and changes, actually modified the receipt data file. Ooops :(. I had indented the receipt by 4 bytes, in preparation for submitting a post to stackoverflow of all things. Indenting the receipt made it invalid, perhaps not surprisingly.


text:
Q: how to find a word in text files from a directory Suppose that I have a directory with name _file and includes two sub directory like _1 and _2 and on each one I have some text files. I want to search a word like foo in one of these text files. How I can do that?
I want to know which text files in the whole directory contain that word?

A: You can use recursive grep with the -l flag to only print the file's name instead of the matched line:
grep -Rl foo .

Or, you can use find:
find . -type f -exec grep -l foo {} +

Or. you can use extglob and normal grep
shopt -s extglob
grep -l foo **/*

A: If you don't want to  install additional software, you can simply use grep in the terminal. To recursively search through directories, you can use the -r option (see man grep for details). The syntax you are looking for is probably:
grep -r "[STRING TO SEARCH FOR]" "[DIRECTORY TO SEARCH]"

So, for instance if I want to search for the string "asdf" in all files in all subdirectories of "/tmp/testdir/" the command looks like this:
grep -r "asdf" "/tmp/testdir/"

The quotation marks are not strictly necessary, but if your string or directory path contains whitespaces, you otherwise would have to mask them using the \ character...

A: Just install gnome-search-tool using sudo apt-get install gnome-search-tool
Search in dash for 'search for files' and launch it.
See image below:

*

*Leave the 'name contains' section empty.

*Select your folder.

*Unfold the 'select more options' part and choose 'contains the text' and then press add.

*Type here the text you want to search for and click find at the bottom right corner.

Enjoy.

A: *

*Open a terminal.

*Install ack-grep by typing sudo apt-get install ack-grep

*Change to the directory you want to search under, and type ack-grep foo. it lists out all the matches in all files under that directory.


text:
Q: Determine if a Turing Machine M, on input w, will move its head to the left, at least once Here is a problem from my formal languages class

Consider the following problem: Determine if a Turing Machine M, on input w,             will move its head to the left, at least once.

*

*Is this problem decidable?

*Can Rice's theorem be applied on this case?

and here is my attempt to answer (1):

Define M' as a turing machine that takes a pair (M,w) as input, where M is a turing machine encoded in some form recognized by M' and w is the input to M.
M' stops and accepts (M,w) whenever the head of the simulated machine M moves to the left while processing input w
For a particular input to M' (M,w), construct the turing machine P as follows:

*

*P executes M' on (M,w)

*P stops and accepts any input if M' accepts (M,w)

We have reduced the Universal Turing Machine U to P. Since we know that L(U) is not decidable, we conclude that L(P) is not decidable. Consequently, M' is not decidable

As to the applicability of Rice's theorem, I'm not sure...
"Any nontrivial property about the language recognized by a Turing machine is undecidable"
moving the head of the machine is not a property of the language itself, it is a property of the machine...
thoughts, please?
Thanks!

A: Your idea that Rice's theorem is inapplicable is correct. For the theorem to hold, we want to have whenever $L(M_1)=L(M_2)$, $M_1$ satisfies the property iff $M_2%$ does. This is evidently not true of the property presently under consideration. Think of two machines identifying a regular language (i.e. recognizable in a single pass), but one machine backs up all the way to the left, while the other does not.
But your reduction does not make sense. At a very high level, the point of a reduction is something like: "I know problem $P_1$ is hard. If I could solve problem $P_2$, voila! Here is a method to solve problem $P_1$. But this should not be possible. Therefore, $P_2$ has to be hard." Typically, $P_1$ is the halting problem, and you want $P_2$ to be the "left-mover" problem. So, given an instance of the halting problem, you manufacture an instance of the left-mover problem. If I read your reduction correctly, you're doing it in the opposite direction.
Now, something else is wrong with your solution. The problem is decidable! Here is the algorithm sketch: observe that if $M$ never moves left on $w$, it is making a single pass on the string. Eventually, $M$ finishes reading $w$ (which is of finite length), and starts reading spaces. Now, you simply look at which state $q$ $M$ is in when it finishes reading $w$, and look at the subgraph of states it visits on reading spaces. None of these should ever involve moving to the left.

A: The problem is actually decidable. The fault in your solution is that $M'$ can accept $<M>, <w>$ without moving left and $M'$ may never halt simulation $<M>$ on $<w>$ but it might move left. You've missed these 2 cases in your solution.
Now coming to the algorithm to solve this problem.
Case 1) If $M$ halts on $w$ and it never moved left, reject it.
Case 2) If $M$ ever moves left, halt and accept.
Case 3) If $M$ stays on the same location for more than $|Q|.|Γ|$ moves, then it means that a configuration gets repeated again which means $M$ stays on this location forever. So, reject it.
Case 4) Otherwise, in this case, $M$ doesn't get stuck at a location, so it actively moves right. So, after a finite number of steps($< |Q|.|Γ|.|w|$) $M$ crosses the input $w$. So, now it encounters a blank symbol. Suppose it is on a blank symbol with state $q$. In a finite number of steps, it moves right and changes the state to $q'$. If $q' = q$, then that means it is on an infinite loop(and moves right forever). One can easily check that after $|Q|^2.|Γ|$ computations, the state gets repeated for sure. If the tape head crosses w and even after $|Q|^2.|Γ|$ computations, tape head doesn't move left, then it'll never move left. So, reject it.
So, in a finite amount of computation one can determine whether a TM on an input ever moves left or not. So, this is decidable


text:
Q: How can I fix Heroku imagecreatefromjpeg() heroku report me a error: Call to undefined function imagecreatefromjpeg() ..at line 177, where at line 177 is:
case 'jpg':
case 'jpeg':
$image_data = imagecreatefromjpeg($src_image);
break;
I think heroku does not support jpeg or something, what can I do in that case?

A: On Heroku, GD is a "shared" extension that you can enable in composer.json. No custom buildpack required, just add the ext-gd line in your composer.json:
{
  "require": {
    "ext-gd": "*"
  }
}

A: You'll need to use a custom buildpack with imagick or gd compiled in.
I don't believe the latest version of heroku's official PHP buildpack has support for this, but I've created my own buildpacks for this too.
See https://github.com/winglian/heroku-buildpack-php (This version is built on 5.4.11 using PHP-FPM, but you can choose an older tagged branch for 5.3 support using mod_php.)


text:
Q: Geometry column isn't visible in the attribute table in QGIS while it is in Python? This code turns a dissolved shapefile to singlepart but the geometry column although it can be shown in Python when I exported as a shp and imported in QGIS the geometry column is not there. What should I do?
import geopandas as gp
import pandas as pd

def multi2single(dissolved):
    gpdf_singlepoly = gpdf[gpdf.geometry.type == 'Polygon']
    gpdf_multipoly = gpdf[gpdf.geometry.type == 'MultiPolygon']

    for i, row in gpdf_multipoly.iterrows():
        Series_geometries = pd.Series(row.geometry)
        df = pd.concat([gp.GeoDataFrame(row, crs=gpdf_multipoly.crs).T]*len(Series_geometries), ignore_index=True)
        df['geometry']  = Series_geometries
        gpdf_singlepoly = pd.concat([gpdf_singlepoly, df])

    gpdf_singlepoly.reset_index(inplace=True, drop=True)
    return gpdf_singlepoly

here is the call:
multi2single(dissolved)

A: Shapefiles don't have a geometry column as such, they store the geometries in the .shp file while the rest of the attributes are stored in the .dbf file.
So while in Python (and other languages) you can consider the geometry to be "just another" attribute when it comes to storage that may not be the case, depending on your output format.
I believe that QGis will never show the geometry in the attribute table as there is little benefit to viewing the geometry in that format, when it is showing you them on the map.


text:
Q: Creates db with wrong number columns I'm trying to create a table with 4 columns (including _id) and no matter what I do it keeps on creating a table with only 3 columns (including _id).
My table definition is the following:
private static final String DATABASE_CREATE =
        "create table collections (_id integer primary key autoincrement, "
        + "name text not null, description text not null, image integer not null);";

And my onCreate:
@Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE);
    }

How I'm accessing the data:
public View getView(int position, View convertView, ViewGroup parent) {

        cursor.moveToPosition(position);

        LinearLayout ll = new LinearLayout(mContext);
        ll.setOrientation(LinearLayout.VERTICAL);

        ImageView i = new ImageView(mContext);

        i.setImageResource(cursor.getInt(3));  //access to the image column
        i.setScaleType(ImageView.ScaleType.FIT_XY);
        i.setLayoutParams(new Gallery.LayoutParams(150, 150));

        // The preferred Gallery item background
        i.setBackgroundResource(mGalleryItemBackground);

        ll.addView(i);

        TextView tv = new TextView(ll.getContext());

        tv.setTag(mText[position]);
        tv.setText(cursor.getString(1)); //access to the name column
        tv.setLayoutParams(new Gallery.LayoutParams(48, 48));
        ll.addView(tv);

        return ll;
    }

No matter what I try, it keeps leaving the column image out of the table… I'll appreciate any help I get.

A: It was a really dumb thing and I'm really sorry for wasting anyone's time. I really appreciate everyone's help.
I wasn't fetching the data correctly. So in the future if anyone repeats my mistake check your fetch methods first.

A: Have you tried including backticks around your table and column names?  This will do some escaping for you:
    private static final String DATABASE_CREATE =
    "create table `collections` (`_id` integer primary key autoincrement, "
    + "`name` text not null, `description` text not null, `image` integer not null);";

A: wild unproved guess: As _id might be ignored or recognized as the default _ID column, its possible that it will not be counted.
Try to get the column number dynamically:
public View getView(int position, View convertView, ViewGroup parent) {

    cursor.moveToPosition(position);

    LinearLayout ll = new LinearLayout(mContext);
    ll.setOrientation(LinearLayout.VERTICAL);

    ImageView i = new ImageView(mContext);

    i.setImageResource(cursor.getInt(cursor.getColumnIndex("image")));  //access to the image column
    i.setScaleType(ImageView.ScaleType.FIT_XY);
    i.setLayoutParams(new Gallery.LayoutParams(150, 150));

    // The preferred Gallery item background
    i.setBackgroundResource(mGalleryItemBackground);

    ll.addView(i);

    TextView tv = new TextView(ll.getContext());

    tv.setTag(mText[position]);
    tv.setText(cursor.getString(cursor.getColumnIndex("name"))); //access to the name column
    tv.setLayoutParams(new Gallery.LayoutParams(48, 48));
    ll.addView(tv);

    return ll;
}

To the rest (off topic):

*

*You should read about recycling views in an adapter

*You could also try the SimpleCursorAdapter class


text:
Q: CSS: Backdrop Filter Slow on Android Chrome I have coded a website in Next.js.
I decided to have some text boxes in front of the background with backdrop-filter enabled in order to achieve the "glass like" effect.
Particularly I have added these lines in css
.textbox {
      background: rgba( 255, 255, 255, 0.3 );
      backdrop-filter: blur( 10px );
      -webkit-backdrop-filter: blur( 10px ); */
      box-shadow: 0 8px 32px 0 rgba( 0, 0, 0, 0.18 );
      border-radius: 10px;
}

This works very well, as expected. On my pc there is no lag, however on my phone (chrome),
i can easily see frame drops and lags when the backdrop filter is applied. If i remove this, it gets again smooth. Is this normal? Is there any solution for this?
If i just blur the background it works and there is no lag. But, i don't get the desired result.
Thank you.


text:
Q: If long content in datagridviewcell(textbox) show right characters in my textcell of a Datagridview the right characters are more importent than the left one. But if the cell is too small for the hole text it just shows some characters beginning from the left side. But I want the right characters.
Is there a possibility to let the right characters have a higher priority to be shown than the left characters?


text:
Q: Print Assigned Graph Color Name - Networkx In the code below, I've assigned a color (as a numerical value, not a color name) to a node based on vertex coloring rules. Subsequently, I plot the graph and display the colors. Last, I print the associated numerical color to the node. However, I want to actually print the "name" of the color that is shown in the plot. How can I convert the color number to a color name?

*

*Assign colors to nodes based on vertex coloring rules

%matplotlib inline
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

# get the maximum vertex degree
max_deg = max(G.degree())
max_deg = max_deg[1]
print('maximum degree = {}'.format(max_deg))

# Create the set of possible colors.
num_colors = max_deg+1
colors = set(range(num_colors))

# We'll store the color of each node as an integer property called 'color'.  Start by initializing
# all the colors to -1 (meaning not yet colored)
for v in complete_graph.nodes():
    complete_graph.nodes[v]['color'] = -1

# loop over all nodes
for v in complete_graph.nodes():

    print('processing node {}'.format(v))

    # copy the possible colors
    possible = colors.copy()

    # find colors of neighbors
    nbrs = set([complete_graph.nodes[w]['color'] for w in complete_graph.neighbors(v) if complete_graph.nodes[w]['color']!= -1])

    # remove neighbor colors from the set of possible colors
    possible -= nbrs

    # pick a color for the current node
    c = next(iter(possible))

    print('  neighbor colors: ', nbrs)
    print('  possible colors: ', possible)
    print('  selected color:  ', c)

    #update the color
    complete_graph.nodes[v]['color'] = c

Example output for a complete graph with 9 nodes (only Node 0 is printed below):
  processing node 0
  neighbor colors:  set()
  possible colors:  {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  selected color:   0

*Plot the complete graph and color the vertices based on the assigned color numbers

plt.figure(figsize=(5,5))
nx.draw(complete_graph,pos,node_color=[d['color'] for v,d in complete_graph.nodes(data=True)],width=2,cmap=plt.cm.Set3)

Output:

*Print node and associated color number

print(complete_graph.nodes(data=True))
[(0, {'color': 0}), (1, {'color': 1}), (2, {'color': 2}), (3, {'color': 3}), (4, {'color': 4}), (5, {'color': 5}), (6, {'color': 6}), (7, {'color': 7}), (8, {'color': 8}), (9, {'color': 9})]

I would prefer it to read:{'color': Green)

A: Well first the you solve that issue just modifying one line, the in wich you declare the colors.
colors = set(range(num_colors))

to this line instead
colors = {'red', 'blue', 'green'}

I imagine that this is not what you want, given that you may want to get the "human"(to say it in a way) representation of the colors or maybe the RGB of this colors. But here's the problem that I found, when we use nx.draw to represent the node, and pass it the nodes_color parameter, internally it uses matplotlib.scatter. Read this from the documentation:

node_color (color or array of colors (default='#1f78b4')) – Node color. Can be a single
color or a sequence of colors with the same length as nodelist. Color can be string, or rgb
(or rgba) tuple of floats from 0-1. If numeric values are specified they will be mapped to
colors using the cmap and vmin,vmax parameters. See matplotlib.scatter for more details.

So in a way that's out of my knowledge, networkx uses matplotlib.scatter to transform that numerics values into color.
So I only see two options, one you declare the colors explicitly like I said before, or second you find out how matplotlib.scatter make that transformation.


text:
Q: Do I need to open ports in my firewall to see LAN games on Minecraft? If so, which? Lately I've been having some trouble with Minecraft LAN games. Not with hosting them  or even with joining them exactly, but with seeing them at all. Here's the situation:

*

*I am not able to see Minecraft LAN games on my multiplayer screen automatically

*I can see them if I add them as I would a server on the internet

*I can join them if I add them, or if I connect to them directly

Basically, I can join games but not find them automatically. It just says "Scanning for games on your local network..." indefinitely. My current theory is that while joining games obviously doesn't require opened ports discovering them might - is this the case?
As far as I know I can't permit specific applications through my firewall (I'm on Linux, and not that I'd care to just give a blanket permit to Java in any case) so I can't test this without having some idea of what ports would be required. It's also possible it's another issue pertinent to Linux or something else altogether, though.
This isn't a huge deal as I can just ask what port the server is being hosted on, but it's been bugging me. Oh, and in case anyone comes across this question with a similar problem, I'm just going to reiterate:
You can join the game by connecting to it directly, just ask for the port. The person hosting will receive a message with it when they open the game. Then you can directly connect to it at (probably) 192.168.#.###:####.
UPDATE: Hosting on LAN works fine, I just can't see the games others host. Additionally, I should clarify I actually mean opening ports on my local firewall, I said port forwarding but that was not actually what I meant.
For a further clarification, this isn't isolated to one person - I've tried with both my brothers, neither of whom is using any special security software that I know of. And they can see each others'.

A: Newer Fedora versions (Fedora 18 and onwards) use Firewalld to manage iptables rules. The iptables service that loads rules out of /etc/sysconfig/iptables is not present by default. A bunch of my answer involves manually bashing about in iptables rules. This is a bit of new ground for me, as my main experience with firewalld up to this point has been making a beeline back to traditional reading of iptables rules out of the save file. Most of the firewalld information was collected on the fly based on the iptables rules that it implemented.
I double-checked this on a Fedora 20 VM that I've been fiddling with. When a rule is set in firewall-config, the packet for a new connection must go through the following steps to be accepted.

*

*New packet hits INPUT chain. Packets in existing connections are automatically accepted.

*All prospective connections from the outside are sent to the either the INPUT_ZONES_SOURCE chain or INPUT_ZONES chain, based on whether they were picked out based on source IP or the interface the packet came in on. The logic within each is pretty much the same, other than the IP/interface note. I'll be focusing on INPUT_ZONES_SOURCE for my example.

*I added my Minecraft rule to the 'home' zone, so I had added an entry in home->sources stating that packets coming from the network address of 10.20.30.0/24 were coming from home. In INPUT_ZONES_SOURCE, there was a rule that would send all packets coming from that IP range to the IN_home chain.

*In the IN_home chain I had three chains dedicated to specific tasks: IN_home_log, IN_home_deny (this was empty, as I hadn't set anything), and IN_home_allow.

*IN_home_allow held all of the allowed services for the 'home' zone, including the 25565 rule that I had just put in. Though I didn't start up a Minecraft server or bind anything else to TCP/25565, I could see that some other default rules did record that packets were being accepted, so traffic was being evaluated against this rule.

*Any rule that does not get accepted will eventually splatter against the last rule of the INPUT chain. The final rule will reject any packet that is still on the chain.

To get to the point of my explanation, could I confirm that you've set an input interface or a IP address/range for the zone that you're allowing the port in? You've placed a rule to allow the port in a given zone, but it sounds as though the packet doesn't have a way to reach that rule and be accepted.
You can list a table using iptables -nvL. Firewalld sets up a lot of chains, so if you want to take a look at one in particular, add the chain name as an argument: iptables -nvL <chain-name>. If you can see numbers greater than zero in the lefthand columns, this means that packets have reached and triggered the rule. (The action the rule takes is in the third column).
To force your firewall to accept everything, and to see if something along the line is causing you grief, you could stop the firewalld service altogether temporarily.
systemctl stop firewalld
You can alternately flush the tables with iptables -F, though I'm not sure when/if firewalld will repopulate the chains on their own without a rule change to prompt it to do so.
Hopefully this will solve your issue. But if you want/need to go to a custom iptables layout by having the firewall load its rules out of /etc/sysconfig/iptables, you will need to install and enable the service, as well as disable firewalld.

*

*Install iptables service: yum install iptables-services

*Stop Firewalld: systemctl stop firewalld

*Disable Firewalld: systemctl disable firewalld

*Start the iptables service (If you don't have an /etc/sysconfig/iptables at this point, this won't do anything): systemctl start iptables

*Enable the iptables service: systemctl enable iptables

A: No you do not need to forward ports for playing on LAN. Port Forwarding is only for connections that are leaving/incoming through your router, ie. internet game hosting. It's part of something called Network Address Translation, NAT for short. Without going into too much technical detail, basically it's a clever way routers hide/protect your computer from being exposed on the public internet. So, in order to allow public internet computers to talk to your computer, you have to "expose" certain ports that the router will allow to talk to your computer. Anything that's going on within your local network, LAN, does not need to go out to the public internet, so NAT is not involved, and therefore no port forwarding needed.
Now, there can be other things at play, such as if you or your buddy have installed any 3rd party Firewall software on your computer, it may be blocking the game. If so, either temporarily disable it, or tell it to allow your game to make connections. For the normal Windows firewall built into Vista and up, it will ask you if you want to allow the program to talk to the network (LAN) usually the first time you run it.

A: It is necessary to open UDP port 4445, commonly used for the service upnotifyp. I tested this across a couple games and, since it's actually a registered port rather than the random ones Minecraft usually chooses, I think it can safely be assumed to be consistent across games. I hope someone else finds a use for this, it took a fair amount of effort to figure out what was wrong.