问:
java.net.UnknownHostException: Unable to resolve host "gist.githubusercontent.com": No address associated with hostname
I written json and created url with the help of git.but now i am not able to get the requested data as result is coming null.Please help me in that

```<code>public class TestActivity extends AppCompatActivity {
    Button btnHit;
   ListView moviList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
         btnHit= (Button) findViewById(R.id.btn);
        moviList=(ListView)findViewById(R.id.lvMovie);

       /* btnHit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new JSONTask().execute("https://gist.githubusercontent.com/PoonamWadekar/5c69afdcbe9c68240c546f73bcb40c69/raw/050254dd568a972442cdff0d984c396b9b340b7f/movie.json");
            }

        });*/

    }

    public class JSONTask extends AsyncTask<String,String,List<MovieModel>>{

        @Override
        protected List<MovieModel> doInBackground(String... params) {
            HttpURLConnection httpURLConnection = null;
            BufferedReader reader = null;
            try {
                URL url = new URL(params[0]);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.connect();
                InputStream inputStream = httpURLConnection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                String finalJson=buffer.toString();
                JSONObject parentObj=new JSONObject(finalJson);
                JSONArray parentArray=parentObj.getJSONArray("movies");
                List<MovieModel> movieModelList=new ArrayList<>();

                for (int i=0; i<parentArray.length() ; i++)
                {
                JSONObject finalObj=parentArray.getJSONObject(i);
                    MovieModel movieModel=new MovieModel();
                    movieModel.setMovie(finalObj.getString("movie"));
                    movieModel.setYear(finalObj.getInt("year"));
                    movieModel.setRating((float) finalObj.getDouble("rating")/2);
                    movieModel.setStory(finalObj.getString("story"));
                    //movieModel.setImage(finalObj.getString("image"));
                    List<MovieModel.Caste> casteList=new ArrayList<>();
                    for (int j=0;j<finalObj.getJSONArray("caste").length();j++){
                        MovieModel.Caste caste=new MovieModel.Caste();
                        caste.setName(finalObj.getJSONArray("caste").getJSONObject(j).getString("name"));
                        casteList.add(caste);
                    }
                    movieModel.setCasteList(casteList);

                    movieModelList.add(movieModel);
                    Log.d("hi","list+++++++++++++++++++++++" +movieModelList);
                }
                return movieModelList;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if (httpURLConnection != null)
                    httpURLConnection.disconnect();
                try {
                    if (reader != null)
                        reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;

        }
        @Override
        protected void onPostExecute(List<MovieModel> result) {
            super.onPostExecute(result);
            if (result==null){
                Log.d("Hi","sorry no result");
                return;
            }

            //set data to recycler view
            MovieAdapter adapter=new MovieAdapter(getApplicationContext(),R.layout.movie_cell,result);

            moviList.setAdapter(adapter);

        }

    }

    public class MovieAdapter extends ArrayAdapter{
        private List<MovieModel> movieModelList=new ArrayList<MovieModel>();
        private int resource;
        LayoutInflater inflater;

        public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
            super(context, resource, objects);
            movieModelList=objects;
            this.resource=resource;
            inflater= (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

        }

        @NonNull
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView==null)
            {
                convertView=inflater.inflate(resource,null);
            }
            ImageView movieIcon;
            TextView name;
            TextView year;
            RatingBar ratingBar;
            TextView tvCaste;
            TextView story;

            movieIcon= (ImageView) convertView.findViewById(R.id.place_image);
            name= (TextView) convertView.findViewById(R.id.tv_name);
            year= (TextView) convertView.findViewById(R.id.tv_year);
            ratingBar= (RatingBar) convertView.findViewById(R.id.rt_ratebar);
            tvCaste= (TextView) convertView.findViewById(R.id.tv_cast);
            story= (TextView) convertView.findViewById(R.id.tv_story);

            name.setText(movieModelList.get(position).getMovie());
            year.setText(" year -"+ movieModelList.get(position).getYear());
            StringBuffer stringBuffer=new StringBuffer();
            for (MovieModel.Caste caste: movieModelList.get(position).getCasteList()){
                stringBuffer.append(caste.getName() + ",");
            }
            tvCaste.setText(stringBuffer);

            story.setText(movieModelList.get(position).getStory());
            // rating bar
            ratingBar.setRating(movieModelList.get(position).getRating()/2);

            return convertView;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.actionbar_profile,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();

        if(id==R.id.refresh){
            String url="https://gist.githubusercontent.com/PoonamWadekar/5c69afdcbe9c68240c546f73bcb40c69/raw/9e3de75ffa48c70f81ad07b7623e5fd0789142f0/movie.json";
           Log.d("url____",url);
            new JSONTask().execute(url);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
</code>```

答:
It is working fine on my device.
Few doubts regarding your scenario.

Do you have internet permission set in manifest.xml file

Are you using emulator for running application?

If your are using WiFi, try reconnecting and check again.

Are you using VPN? If yes then disconnect from VPN and try again.
Thanks

Body:
I written json and created url with the help of git.but now i am not able to get the requested data as result is coming null.Please help me in that

public class TestActivity extends AppCompatActivity {
    Button btnHit;
   ListView moviList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
         btnHit= (Button) findViewById(R.id.btn);
        moviList=(ListView)findViewById(R.id.lvMovie);

       /* btnHit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new JSONTask().execute("https://gist.githubusercontent.com/PoonamWadekar/5c69afdcbe9c68240c546f73bcb40c69/raw/050254dd568a972442cdff0d984c396b9b340b7f/movie.json");
            }

        });*/

    }

    public class JSONTask extends AsyncTask<String,String,List<MovieModel>>{

        @Override
        protected List<MovieModel> doInBackground(String... params) {
            HttpURLConnection httpURLConnection = null;
            BufferedReader reader = null;
            try {
                URL url = new URL(params[0]);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.connect();
                InputStream inputStream = httpURLConnection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                String finalJson=buffer.toString();
                JSONObject parentObj=new JSONObject(finalJson);
                JSONArray parentArray=parentObj.getJSONArray("movies");
                List<MovieModel> movieModelList=new ArrayList<>();

                for (int i=0; i<parentArray.length() ; i++)
                {
                JSONObject finalObj=parentArray.getJSONObject(i);
                    MovieModel movieModel=new MovieModel();
                    movieModel.setMovie(finalObj.getString("movie"));
                    movieModel.setYear(finalObj.getInt("year"));
                    movieModel.setRating((float) finalObj.getDouble("rating")/2);
                    movieModel.setStory(finalObj.getString("story"));
                    //movieModel.setImage(finalObj.getString("image"));
                    List<MovieModel.Caste> casteList=new ArrayList<>();
                    for (int j=0;j<finalObj.getJSONArray("caste").length();j++){
                        MovieModel.Caste caste=new MovieModel.Caste();
                        caste.setName(finalObj.getJSONArray("caste").getJSONObject(j).getString("name"));
                        casteList.add(caste);
                    }
                    movieModel.setCasteList(casteList);

                    movieModelList.add(movieModel);
                    Log.d("hi","list+++++++++++++++++++++++" +movieModelList);
                }
                return movieModelList;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if (httpURLConnection != null)
                    httpURLConnection.disconnect();
                try {
                    if (reader != null)
                        reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;

        }
        @Override
        protected void onPostExecute(List<MovieModel> result) {
            super.onPostExecute(result);
            if (result==null){
                Log.d("Hi","sorry no result");
                return;
            }

            //set data to recycler view
            MovieAdapter adapter=new MovieAdapter(getApplicationContext(),R.layout.movie_cell,result);

            moviList.setAdapter(adapter);

        }

    }

    public class MovieAdapter extends ArrayAdapter{
        private List<MovieModel> movieModelList=new ArrayList<MovieModel>();
        private int resource;
        LayoutInflater inflater;

        public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
            super(context, resource, objects);
            movieModelList=objects;
            this.resource=resource;
            inflater= (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

        }

        @NonNull
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView==null)
            {
                convertView=inflater.inflate(resource,null);
            }
            ImageView movieIcon;
            TextView name;
            TextView year;
            RatingBar ratingBar;
            TextView tvCaste;
            TextView story;

            movieIcon= (ImageView) convertView.findViewById(R.id.place_image);
            name= (TextView) convertView.findViewById(R.id.tv_name);
            year= (TextView) convertView.findViewById(R.id.tv_year);
            ratingBar= (RatingBar) convertView.findViewById(R.id.rt_ratebar);
            tvCaste= (TextView) convertView.findViewById(R.id.tv_cast);
            story= (TextView) convertView.findViewById(R.id.tv_story);

            name.setText(movieModelList.get(position).getMovie());
            year.setText(" year -"+ movieModelList.get(position).getYear());
            StringBuffer stringBuffer=new StringBuffer();
            for (MovieModel.Caste caste: movieModelList.get(position).getCasteList()){
                stringBuffer.append(caste.getName() + ",");
            }
            tvCaste.setText(stringBuffer);

            story.setText(movieModelList.get(position).getStory());
            // rating bar
            ratingBar.setRating(movieModelList.get(position).getRating()/2);

            return convertView;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.actionbar_profile,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();

        if(id==R.id.refresh){
            String url="https://gist.githubusercontent.com/PoonamWadekar/5c69afdcbe9c68240c546f73bcb40c69/raw/9e3de75ffa48c70f81ad07b7623e5fd0789142f0/movie.json";
           Log.d("url____",url);
            new JSONTask().execute(url);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


来源: stackexchange

问:
Akka Cluster manual join
I'm trying to find a workaround to the following limitation: When starting an Akka Cluster from scratch, one has to make sure that the first seed node is started. It's a problem to me, because if I have an emergency to restart all my system from scratch, who knows if the one machine everything relies on will be up and running properly? And I might not have the luxury to take time changing the system configuration. Hence my attempt to create the cluster manually, without relying on a static seed node list.

Now it's easy for me to have all Akka systems registering themselves somewhere (e.g. a network filesystem, by touching a file periodically). Therefore when starting up a new system could

Look up the list of all systems that are supposedly alive (i.e. who touched the file system recently).

a. If there is none, then the new system joins itself, i.e. starts the cluster alone. b. Otherwise it tries to join the cluster with  Cluster(system).joinSeedNodes using all the other supposedly alive systems as seeds.

If 2. b. doesn't succeed in reasonable time, the new system tries again, starting from 1. (looking up again the list of supposedly alive systems, as it might have changed in the meantime; in particular all other systems might have died and we'd ultimately fall into 2. a.).

I'm unsure how to implement 3.: How do I know whether joining has succeeded or failed? (Need to subscribe to cluster events?) And is it possible in case of failure to call Cluster(system).joinSeedNodes again? The official documentation is not very explicit on this point and I'm not 100% how to interpret the following in my case (can I do several attempts, using different seeds?):

An actor system can only join a cluster once. Additional attempts will
  be ignored. When it has successfully joined it must be restarted to be
  able to join another cluster or to join the same cluster again.

Finally, let me precise that I'm building a small cluster (it's just 10 systems for the moment and it won't grow very big) and it has to be restarted from scratch now and then (I cannot assume the cluster will be alive forever).

Thx

答:
You don't need seed-nodes. You need seed nodes if you want the cluster to auto-start up.

You can start your individual application and then have them "manually" join the cluster at any point in time. For example, if you have http enabled, you can use the akka-management library (or implement a subset of it yourself, they are all basic cluster library functions just nicely wrapped).

I strongly discourage the touch approach. How do you sync on the touch reading / writing between nodes? What if someone reads a transient state (while someone else is writing it) ?

I'd say either go full auto (with multiple seed-nodes), or go full "manual" and have another system be in charge of managing the clusterization of your nodes. By that I mean you start them up individually, and they join the cluster only when ordered to do so by the external supervisor (also very helpful to manage split-brains).

ContentLicense: CC BY-SA 3.0

Title: Akka Cluster manual join


问:
Error: Could not build Objective-C module 'Firebase'
When I compile the application I get an error equal to this:

Could not build Objective-C module 'Firebase'

This error appear in import Firebase of my file swift.

答:
Can you please try to take a look at my answer here

TL;DR make sure you are running cocoapods version 1.4.0 minimum. It fixes static framework imports.

You can do this by running sudo gem install cocoapods on your terminal and verify your version by typing pod --version


问:
Can i use a test framework like testNG in RIDE with RobotFramework?
I'm using robot framework with RIDE in order to automate a desktop windows application.
Is there any way that i can use test frameworks like TESTNG because i need to make dependences between tests and many other features related to this framework.

Best regards,

答:
RIDE is a Robot Framework files editor and supports running those tests, using the Plugin Test Runner. It does not allow to edit Java, Python or even YAML files.

There are some options to "call" TestNG runner, but it is not integration:

In your tests steps add calls to Process or OperatingSystem Libraries to run the TestNG files

Use the Run Anything Plugin to define TestNG runner scripts

Create library (Java or Python) which acts as a wrapper for calling TestNG

(Eventually do some post-processing to integrate TestNG outputs with Robot Framework's, by using rebot)


问:
Batch file appending text to the end of a .txt file is locking the file
We have a process that uses a batch file which, in short, repeatedly gets some plain text data and appends it to the end of a .txt file for later processing. When the data is processed, the .txt is deleted.

This is done in a very simple and basic way by using the ">>" operator to append the data to the .txt file, then a 'DEL' cmd to delete the .txt file.

However, one user is having an issue running this. They are able to append data to the .txt file but are unable to delete it as the file seems to be locked. They get this message when the batch file tries to delete:

"The process cannot access the file because it is being used by another process."

The .txt file being created is on a network drive, and no other user is able to delete the file (or change it, etc.) either.

However, if the user with the problem reboots their PC, the file is able to be edited and deleted (which seems to suggest that there is some process on the user's PC that is using the file).

The below batch file is an extremely simplified demo I made which experiences the issue for the user, but not for anyone else. This is not the 'real' process of course, but illustrates the issue without any superfluous code and is totally independent of anything else that the main process is doing.

```<code>:: we want to repeatedly append text to the end of a txt file
echo test >> test.txt
echo test >> test.txt
echo test >> test.txt

pause

:: but then we cannot delete the file as it appears to be locked
del test.txt

pause
</code>```

The user with the issue has just got a new PC using Windows 10. Everyone else is using Windows 7. Maybe that is the root of the issue, but I don't know why? I understand that command prompt had some changes for Win10, but they sound pretty cosmetic.

Any pointers would be appreciated. I've been scouring the Internet for hours and can't find anything like this issue. Maybe I am doing something so fundamentally wrong that no one would have encountered this?!

Thanks in advance.

答:
I'm having a similar problem on Windows 7 that produces the same error message but my circumstances are a bit different. In my case, I have a batch file open in an editor, I make changes, and save it. Then I run the batch file and it completes and closes the console window. I make changes and attempt to save the file again and get the same error message. If I wait 30 seconds or so I can then save the batch file again but when I run it again I get the same error.

It doesn't matter how I close the console window. I can let the batch file complete and close the window or terminate the batch file through Task Manager or click the X in the top, right corner of the window and get the same results.

It also doesn't matter what editor I use. I get the same results.

In my case, the file is on a local drive (C:) but that drive does have a drive mapping for the network but no other machines are running.

Do you encounter the same problem if the .txt file is created locally, e.g. C:?

If the Win10 machine is using a drive mapping, do you get the same problem if you use a UNC rather than a drive mapping?

In my case the console window is closed so I know cmd.exe is not holding the file open but I'm wondering if it is something to do with memory management or garbage collection.

Can the user delete the file if they log off and back on rather than rebooting?

There is one other thing that might cause. Windows now has something called "delayed writes". I've run into this problem occasionally in batch files. Try putting a delay in the batch file instead of a pause using something like

```<code>PING 0.0.0.1 -n 3 -w 1000>NUL 2>&1
</code>```

Just to see if it affects anything.

Body:
We have a process that uses a batch file which, in short, repeatedly gets some plain text data and appends it to the end of a .txt file for later processing. When the data is processed, the .txt is deleted.

This is done in a very simple and basic way by using the ">>" operator to append the data to the .txt file, then a 'DEL' cmd to delete the .txt file.

However, one user is having an issue running this. They are able to append data to the .txt file but are unable to delete it as the file seems to be locked. They get this message when the batch file tries to delete:

"The process cannot access the file because it is being used by another process."

The .txt file being created is on a network drive, and no other user is able to delete the file (or change it, etc.) either.

However, if the user with the problem reboots their PC, the file is able to be edited and deleted (which seems to suggest that there is some process on the user's PC that is using the file).

The below batch file is an extremely simplified demo I made which experiences the issue for the user, but not for anyone else. This is not the 'real' process of course, but illustrates the issue without any superfluous code and is totally independent of anything else that the main process is doing.

:: we want to repeatedly append text to the end of a txt file
echo test >> test.txt
echo test >> test.txt
echo test >> test.txt

pause

:: but then we cannot delete the file as it appears to be locked
del test.txt

pause

The user with the issue has just got a new PC using Windows 10. Everyone else is using Windows 7. Maybe that is the root of the issue, but I don't know why? I understand that command prompt had some changes for Win10, but they sound pretty cosmetic.

Any pointers would be appreciated. I've been scouring the Internet for hours and can't find anything like this issue. Maybe I am doing something so fundamentally wrong that no one would have encountered this?!

Thanks in advance.

Body:
I'm having a similar problem on Windows 7 that produces the same error message but my circumstances are a bit different. In my case, I have a batch file open in an editor, I make changes, and save it. Then I run the batch file and it completes and closes the console window. I make changes and attempt to save the file again and get the same error message. If I wait 30 seconds or so I can then save the batch file again but when I run it again I get the same error.

It doesn't matter how I close the console window. I can let the batch file complete and close the window or terminate the batch file through Task Manager or click the X in the top, right corner of the window and get the same results.

It also doesn't matter what editor I use. I get the same results.

In my case, the file is on a local drive (C:) but that drive does have a drive mapping for the network but no other machines are running.

Do you encounter the same problem if the .txt file is created locally, e.g. C:?

If the Win10 machine is using a drive mapping, do you get the same problem if you use a UNC rather than a drive mapping?

In my case the console window is closed so I know cmd.exe is not holding the file open but I'm wondering if it is something to do with memory management or garbage collection.

Can the user delete the file if they log off and back on rather than rebooting?

There is one other thing that might cause. Windows now has something called "delayed writes". I've run into this problem occasionally in batch files. Try putting a delay in the batch file instead of a pause using something like

PING 0.0.0.1 -n 3 -w 1000>NUL 2>&1

Just to see if it affects anything.


问:
Combine of information based on two dataframes in R
This is my sample data

```<code>> data.frame
              a     b     c     d
W_1_N        NA    NA    NA    NA
W_1_E         2     2     2     4
W_1_C         4     2     2     4
W_1_D        NA    NA    NA    NA
</code>```

First I had to combine elements from matrix to get pairs of column names of them, where one of element is 4 and another is 2 in the same row.

In a result it looks like this

```<code>W_1_E.1  d  a
W_1_E.2  d  b
W_1_E.3  d  c
W_1_C.1  a  b
W_1_C.2  a  c
W_1_C.3  d  b
W_1_C.4  d  c
</code>```

I wanted only pairs where one element is 4 and other is 2 in the same row. W_1_N and W_1_D have only  NA so was ommited. W_1_E appears in 3 rows because there are 3 pairs of (4,2) in row in sample data.W_1_C has 4 pairs.

This is code:

```<code>  lst=data.frame(df) %>%
    rownames_to_column("rn") %>%
    drop_na() %>%
    gather(key, value, -rn) %>%
    group_by(rn, value) %>%
    summarise(l = list(unique(key))) %>%
    split(.$rn)

pair=do.call("rbind", lapply(lst, function(x) expand.grid(x$l[[1]],
x$l[[2]])))
</code>```

It works perfectly, but now I have second data.frame:

```<code>              a     b     c     d
W_1_N         0     1     1     1
W_1_E         1     1     0     0
W_1_C         1     1     1     0
W_1_D         1     0     1     1
</code>```

Here is my problem, I want to get only this pairs where value of both elements of pair is 1 in second data.frame. For example first pair of my result W_1_E.1  d  a should be eliminated because d has value 0 in W_1_E row in second data.frame.

The output should be:

```<code>W_1_C.1  a  b
W_1_C.2  a  c
</code>```

d has value 0 in W_1_E row, so all rows with W_1_E in my result data.frame were eliminated (all pars were with d). The last two rows were eliminated because d is also 0 in W_1_C row in second dataframe.

Thanks for your help

答:
How's this?</p>

```<code>x <- "N             a     b     c     d
W_1_N        NA    NA    NA    NA
W_1_E         2     2     2     4
W_1_C         4     2     2     4
W_1_D        NA    NA    NA    NA "
x1 <- read.table(text = x, header = TRUE)

x <- "N             a     b     c     d
W_1_N         0     1     1     1
W_1_E         1     1     0     0
W_1_C         1     1     1     0
W_1_D         1     0     1     1  "
x2 <- read.table(text = x, header = TRUE)

df <- merge(x1, x2, by="N")
df$a <- ifelse(df$a.y == 0,NA,df$a.x)
df$b <- ifelse(df$b.y == 0,NA,df$b.x)
df$c <- ifelse(df$c.y == 0,NA,df$c.x)
df$d <- ifelse(df$d.y == 0,NA,df$d.x)
df <- df[ , c(1,10:13)]

library(tidyr)
df_all <- df %>%
  gather(key = key1, value, 2:5)

df2 <- df_all[!is.na(df_all$value) & df_all$value == 2,]
df4 <- df_all[!is.na(df_all$value) & df_all$value == 4,]
merge(df2[,1:2], df4[1:2], by = "N", all.x = FALSE, all.y = FALSE)
</code>```

Body:
This is my sample data

> data.frame
              a     b     c     d
W_1_N        NA    NA    NA    NA
W_1_E         2     2     2     4
W_1_C         4     2     2     4
W_1_D        NA    NA    NA    NA

First I had to combine elements from matrix to get pairs of column names of them, where one of element is 4 and another is 2 in the same row.

In a result it looks like this

W_1_E.1  d  a
W_1_E.2  d  b
W_1_E.3  d  c
W_1_C.1  a  b
W_1_C.2  a  c
W_1_C.3  d  b
W_1_C.4  d  c

I wanted only pairs where one element is 4 and other is 2 in the same row. W_1_N and W_1_D have only  NA so was ommited. W_1_E appears in 3 rows because there are 3 pairs of (4,2) in row in sample data.W_1_C has 4 pairs.

This is code:

  lst=data.frame(df) %>%
    rownames_to_column("rn") %>%
    drop_na() %>%
    gather(key, value, -rn) %>%
    group_by(rn, value) %>%
    summarise(l = list(unique(key))) %>%
    split(.$rn)

pair=do.call("rbind", lapply(lst, function(x) expand.grid(x$l[[1]],
x$l[[2]])))

It works perfectly, but now I have second data.frame:

              a     b     c     d
W_1_N         0     1     1     1
W_1_E         1     1     0     0
W_1_C         1     1     1     0
W_1_D         1     0     1     1

Here is my problem, I want to get only this pairs where value of both elements of pair is 1 in second data.frame. For example first pair of my result W_1_E.1  d  a should be eliminated because d has value 0 in W_1_E row in second data.frame.

The output should be:

W_1_C.1  a  b
W_1_C.2  a  c

d has value 0 in W_1_E row, so all rows with W_1_E in my result data.frame were eliminated (all pars were with d). The last two rows were eliminated because d is also 0 in W_1_C row in second dataframe.

Thanks for your help

Body:
How's this?

x <- "N             a     b     c     d
W_1_N        NA    NA    NA    NA
W_1_E         2     2     2     4
W_1_C         4     2     2     4
W_1_D        NA    NA    NA    NA "
x1 <- read.table(text = x, header = TRUE)

x <- "N             a     b     c     d
W_1_N         0     1     1     1
W_1_E         1     1     0     0
W_1_C         1     1     1     0
W_1_D         1     0     1     1  "
x2 <- read.table(text = x, header = TRUE)

df <- merge(x1, x2, by="N")
df$a <- ifelse(df$a.y == 0,NA,df$a.x)
df$b <- ifelse(df$b.y == 0,NA,df$b.x)
df$c <- ifelse(df$c.y == 0,NA,df$c.x)
df$d <- ifelse(df$d.y == 0,NA,df$d.x)
df <- df[ , c(1,10:13)]

library(tidyr)
df_all <- df %>%
  gather(key = key1, value, 2:5)

df2 <- df_all[!is.na(df_all$value) & df_all$value == 2,]
df4 <- df_all[!is.na(df_all$value) & df_all$value == 4,]
merge(df2[,1:2], df4[1:2], by = "N", all.x = FALSE, all.y = FALSE)


问:
Is there a way to mock an $? return using Pester?
I'm writing tests for a PowerShell application, using Pester.

I have been able to create mocks for most functions, but I haven't been able to mock a function returning the $? variable. I'm currently using it to evaluate the returns from AWS CLI commands.

This is, for example, to mock a failing AWS CLI command return.

Any thoughts?

答:
We created an auxiliary function and passed the $? value.

```<code>function Test-LastExitCodeIsFalse ($last_exit) {
    if ($last_exit) {
       return $false
    }
    $true
}
</code>```

And a usage being

```<code>aws s3 <an aws command>
if (Test-LastExitCodeIsFalse($?)) {
   throw "AWS Exception"
}
</code>```

Using Pester, then we just mock the Test-LastExitCodeIsFalse function to return false. And we have a unit test with a failing AWS instance :)

ContentLicense: CC BY-SA 4.0

Body:
We created an auxiliary function and passed the $? value.

function Test-LastExitCodeIsFalse ($last_exit) {
    if ($last_exit) {
       return $false
    }
    $true
}

And a usage being

aws s3 <an aws command>
if (Test-LastExitCodeIsFalse($?)) {
   throw "AWS Exception"
}

Using Pester, then we just mock the Test-LastExitCodeIsFalse function to return false. And we have a unit test with a failing AWS instance :)


问:
Safari disabled select list, and non-disabled select list appear the same
I recently did the UI for an application and I have two select lists:

```<code><select id="location" class="form-control" disabled> </select>

<select class="form-control valid" data-val="true" data-val-required="The Reason field is required.">       <option value="2">Earth</option>
    <option selected="selected" value="3">Mars</option>
    <option value="4">Jupiter</option>
    <option value="6">Saturn</option>
</select>
</code>```

The first is disabled. It works and looks just fine on everything except Safari on an iPad (and I'd assume iPhone's, iPods, etc.)

On an iPad the two select lists look identical, even though one is disabled. Is there any way to get disabled  select lists to appear "disabled" on these devices or am I missing some important attribute that Safari expects? I have tried disabled="disabled", disabled, and a few other things to no avail.

I have a fiddle here.

答:
Just set the opacity for the device width you are targeting like this:</p>

```<code> @media (max-width:768px) {
   select:disabled {
      opacity: 0.5;
   }
 }
</code>```

Body:
I recently did the UI for an application and I have two select lists:

<select id="location" class="form-control" disabled> </select>

<select class="form-control valid" data-val="true" data-val-required="The Reason field is required.">       <option value="2">Earth</option>
    <option selected="selected" value="3">Mars</option>
    <option value="4">Jupiter</option>
    <option value="6">Saturn</option>
</select>

The first is disabled. It works and looks just fine on everything except Safari on an iPad (and I'd assume iPhone's, iPods, etc.)

On an iPad the two select lists look identical, even though one is disabled. Is there any way to get disabled  select lists to appear "disabled" on these devices or am I missing some important attribute that Safari expects? I have tried disabled="disabled", disabled, and a few other things to no avail.

I have a fiddle here.

Body:
Just set the opacity for the device width you are targeting like this:

 @media (max-width:768px) {
   select:disabled {
      opacity: 0.5;
   }
 }


问:
Display list of files inside table
as of now here is my code.

index.html

```<code><!DOCTYPE html>
<html>
<head>
<base target="_top">

<script>
function handleFormSubmit(formObject)
{
google.script.run.testSearch(formObject);

}
</script>

<style>
table, th, td {
    border: 1px solid black;
}
</style>

</head>

<body>
<script>
      google.script.run.testSearch(formObject);

</script>

 <div class="container">
   <form method="" onsubmit="handleFormSubmit(this)">
    <input type="text" id="txtsearch" name="txtsearch" placeholder="Search" Required>
    <input id= "mybutton" type="submit" value="Search" >
  </form>

</div>

</body>
</html>
</code>```

adn here is my code.gs

```<code>function doGet() {
  return HtmlService.createHtmlOutputFromFile('index');

}
function testSearch(formObject){
  var txtsearch = formObject.txtsearch;
  var filename

  var files = DriveApp.searchFiles('fullText contains "'+txtsearch+'"');
  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file.getName());

  }
}
</code>```

The index.html's output displays only a textbox and button,actually this code is working and it will display any file name that i've been searched IN Logger.log my goal here is how can i display that inside an html table? I hope I can add the table below the search box and do not redirect to any page.

TYSM

答:
Here is a working example of your script:
Code:

function doGet(e) { // main function
  var template = HtmlService.createTemplateFromFile('index.html');
  return template.evaluate().setTitle('Search Drive').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function SearchFiles(searchTerm) {
  var searchFor ="fullText contains '" + searchTerm + "'"; //single quotes are needed around searchterm
  var names = [];
  var files = DriveApp.searchFiles(searchFor);
  while (files.hasNext()) {
    var file = files.next();
    var fileId = file.getId();// To get FileId of the file
    var lm = file.getLastUpdated();
    var name = file.getName()+"|~|"+file.getUrl()+"|~|"+lm; // Im concatenating the filename with file id separated by |~|
    names.push(name); // adding to the array
    Logger.log(file.getUrl());
  }
  return names; // return results
}

// Process the form
function processForm(searchTerm) {
  var resultToReturn;
  Logger.log('processForm was called! ' + searchTerm);
  resultToReturn  = SearchFiles(searchTerm);
  Logger.log('resultToReturn: ' + resultToReturn);
  return resultToReturn; // return the results
}
```

<p>Index:</p>

<pre class="lang-js prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<base target="_top">

<script>
   function displayMessage() {
        var searchTerm;
        searchTerm = document.getElementById('idSrchTerm').value;
        console.log('searchTerm: ' + searchTerm );
        // Below call means: call to processForm passing the searchTerm value (previously escaped) and after finish call the handleResults function
         google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
       }

          function handleResults(results){
         var length=results.length; // total elements of results
         for(var i=0;i<length;i++)
         {
         var item=results[i];
         item=item.split("|~|"); // split the line |~|, position 0 has the filename and 1 the file URL
         document.writeln("<b>"+item[0]+"</b> (Last modified: "+item[2]+")<br/><br/>"); // write result
        }
        document.writeln("End of results...");
       }

</script>

<style>
table, th, td {
    border: 1px solid black;
}
</style>

</head>

<body>

 <div class="container">
    Search: <input type="text" id="idSrchTerm" name="search">
    <input type="button" value="Search" name="submitButton" onclick="displayMessage()"/>

</div>

</body>
</html>
</code>```

Title: Display list of files inside table

Body:
as of now here is my code.

index.html

<!DOCTYPE html>

<base target="_top">

   <form method="" onsubmit="handleFormSubmit(this)">
    <input type="text" id="txtsearch" name="txtsearch" placeholder="Search" Required>
    <input id= "mybutton" type="submit" value="Search" >
  </form>

adn here is my code.gs

function doGet() {
  return HtmlService.createHtmlOutputFromFile('index');

}
function testSearch(formObject){
  var txtsearch = formObject.txtsearch;
  var filename

  var files = DriveApp.searchFiles('fullText contains "'+txtsearch+'"');
  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file.getName());

  }
}

The index.html's output displays only a textbox and button,actually this code is working and it will display any file name that i've been searched IN Logger.log my goal here is how can i display that inside an html table? I hope I can add the table below the search box and do not redirect to any page.

TYSM

Body:
Here is a working example of your script:
Code:

function doGet(e) { // main function
  var template = HtmlService.createTemplateFromFile('index.html');
  return template.evaluate().setTitle('Search Drive').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

function SearchFiles(searchTerm) {
  var searchFor ="fullText contains '" + searchTerm + "'"; //single quotes are needed around searchterm
  var names = [];
  var files = DriveApp.searchFiles(searchFor);
  while (files.hasNext()) {
    var file = files.next();
    var fileId = file.getId();// To get FileId of the file
    var lm = file.getLastUpdated();
    var name = file.getName()+"|~|"+file.getUrl()+"|~|"+lm; // Im concatenating the filename with file id separated by |~|
    names.push(name); // adding to the array
    Logger.log(file.getUrl());
  }
  return names; // return results
}

// Process the form
function processForm(searchTerm) {
  var resultToReturn;
  Logger.log('processForm was called! ' + searchTerm);
  resultToReturn  = SearchFiles(searchTerm);
  Logger.log('resultToReturn: ' + resultToReturn);
  return resultToReturn; // return the results
}

Index:

<!DOCTYPE html>
<html>
<head>
<base target="_top">

<script>
   function displayMessage() {
        var searchTerm;
        searchTerm = document.getElementById('idSrchTerm').value;
        console.log('searchTerm: ' + searchTerm );
        // Below call means: call to processForm passing the searchTerm value (previously escaped) and after finish call the handleResults function
         google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
       }

          function handleResults(results){
         var length=results.length; // total elements of results
         for(var i=0;i<length;i++)
         {
         var item=results[i];
         item=item.split("|~|"); // split the line |~|, position 0 has the filename and 1 the file URL
         document.writeln("<b><a href='"+item[1]+"' target='_blank'>"+item[0]+"</b></a> (Last modified: "+item[2]+")<br/><br/>"); // write result
        }
        document.writeln("End of results...");
       }

</script>

<style>
table, th, td {
    border: 1px solid black;
}
</style>

</head>

<body>

 <div class="container">
    Search: <input type="text" id="idSrchTerm" name="search">
    <input type="button" value="Search" name="submitButton" onclick="displayMessage()"/>

</div>

</body>
</html>


问:
Batch script to search for a partial folder name by referencing a partial PC name
I'd like to create a batch file that can search for a partial folder name by referencing a partial PC name, using the common last 4 characters of each.

For instance, all PC's are named "computer####" and we have shared network folders named Store_####.

I need to be able to drop this bat file on remote PC's, which all have different last 4 digits in the PC and store names.  However, the last 4 of the computer names (at any given store) will always match the last 4 of the shared network folder.

The bat file needs to look at the computername, then search for the matching store number using the same last 4 digits, in a shared network drive... and then map it.

The first 3 lines work for mapping, but not for the map and search (for the S drive). I've been searching this site for 2 hours now. I'm a beginner at scripting. Any help would be much appreciated!

```<code>net use /PERSISTENT: YES

net use H: \\example.tn\users\%username% /p:YES

net use G: \\example.tn\shared /p:YES

net use S: \\example.tn\Stores\Store_%computername% /p:YES

if exist *name* (echo found it) else (echo not found)
</code>```

答:
I figured it out...

set string=%computername:~5,4%

net use /PERSISTENT: YES

net use g: \example.tn\shared /p:YES

net use h: \example.tn\users\%username% /p:YES

net use S: "\example.tn\Stores\STORE_%string%" /p:YES

The ~5 ignores the first 5 characters, then the ,4 looks at the following 4 characters.

...TY for the input!

Body:
I'd like to create a batch file that can search for a partial folder name by referencing a partial PC name, using the common last 4 characters of each.

For instance, all PC's are named "computer####" and we have shared network folders named Store_####.

I need to be able to drop this bat file on remote PC's, which all have different last 4 digits in the PC and store names.  However, the last 4 of the computer names (at any given store) will always match the last 4 of the shared network folder.

The bat file needs to look at the computername, then search for the matching store number using the same last 4 digits, in a shared network drive... and then map it.

The first 3 lines work for mapping, but not for the map and search (for the S drive). I've been searching this site for 2 hours now. I'm a beginner at scripting. Any help would be much appreciated!

net use /PERSISTENT: YES

net use H: \\example.tn\users\%username% /p:YES

net use G: \\example.tn\shared /p:YES

net use S: \\example.tn\Stores\Store_%computername% /p:YES

if exist *name* (echo found it) else (echo not found)


问:
show icon in actionbar/toolbar with AppCompat-v7 21
I tried these - but still do not see the icon like before:

```<code>getSupportActionBar().setLogo(R.drawable.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
</code>```

It seems to work when I use custom toolbar - but that would force me to touch all layouts - is there a better way to do so?

答:
```<code>toolbar.setLogo(resize(logo, (int) Float.parseFloat(mContext.getResources().getDimension(R.dimen._120sdp) + ""), (int) Float.parseFloat(mContext.getResources().getDimension(R.dimen._35sdp) + "")));

public Drawable resize(Drawable image, int width, int height)
{
    Bitmap b = ((BitmapDrawable) image).getBitmap();
    Bitmap bitmapResized = Bitmap.createScaledBitmap(b, width, height, false);
    return new BitmapDrawable(getResources(), bitmapResized);
}
</code>```

Body:
I tried these - but still do not see the icon like before:

getSupportActionBar().setLogo(R.drawable.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);

It seems to work when I use custom toolbar - but that would force me to touch all layouts - is there a better way to do so?


问:
AsyncTask still operating after the method (.cancel)
AsyncTask still runs after calling the method new myTask.cancel(). I call the method when i press the back button, or when i change the fragment with a spinner. I have logged the progress of increments, and even after the myTask.cancel is called, the increments still rises.

My AsyncTask class

```<code> public class myTask extends AsyncTask<Void, Integer, String> {
        private static final String TAG = "myTask";
        private ProgressBar budgetProgressBar=null;
        private TextView textView1;
        double b_val,e_val;
        int position;
        private Context mContext;

        public myTask(){
        }

        public myTask(double b_val ,double e_val,ProgressBar budgetProgressBar, TextView textView1) {
            this.b_val = b_val;
            this.textView1=textView1;
            this.e_val = e_val;
            pStatus = (int) e_val;
            this.budgetProgressBar= budgetProgressBar;
            position = (int) budgetProgressBar.getTag();
            maxBudget = (int) this.b_val;
        }

        int pStatus;
        int maxBudget;

        @Override
        protected void onPreExecute() {
            budgetProgressBar.setMax(maxBudget);
            budgetProgressBar.setVisibility(View.VISIBLE);

               budgetProgressBar.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
    //        }
        }

        @Override
        protected String doInBackground(Void... params) {

            int incrementor =10;

                for (int i = incrementor; i<=pStatus && !isCancelled(); i+=incrementor){

                    if (isCancelled()){
                        Log.d(TAG, "doInBackground: CANCELLED");
                        break;
                    }

                    try {

                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    publishProgress(i);
                }

            return "Complete";
        }

        @Override
        protected void onProgressUpdate(Integer... p) {

            super.onProgressUpdate(p);
            Log.d(TAG, "onProgressUpdate: ");
            if ((int) budgetProgressBar.getTag() == position){
                budgetProgressBar.incrementProgressBy(p[0]);
                budgetProgressBar.setProgress(p[0]);
                textView1.setText(p[0]+"/"+maxBudget);
               // Log.d(TAG, "Setting progress to " + p[0]);

                double calc =(e_val/b_val)*100;
                if (calc>100){
                    calc-=100;
                    textView1.setText("-"+ ((int) calc)+"%");
                }else{
                    textView1.setText(((int) calc)+"%");
                }

            }

        }

    }
</code>```

Cancelling the AsyncTask

```<code>new myTask().cancel(true);
</code>```

答:
The AsyncTask#cancel does not stop the doInBackground task even if the method name suggests it as that. What happens is that doInBackground will run until the end and it will call onCancel instead of onPostExecute in the end.

So you might want to add a volatile field flag to AsyncTask and set that as cancelled for example

```<code>AsyncTask
private volatile boolean isRunning = true;

public void cancelTask() // sets isRunning to false
</code>```

And you would check for isRunning instead of isCancelled().

Body:
AsyncTask still runs after calling the method new myTask.cancel(). I call the method when i press the back button, or when i change the fragment with a spinner. I have logged the progress of increments, and even after the myTask.cancel is called, the increments still rises.

My AsyncTask class

 public class myTask extends AsyncTask<Void, Integer, String> {
        private static final String TAG = "myTask";
        private ProgressBar budgetProgressBar=null;
        private TextView textView1;
        double b_val,e_val;
        int position;
        private Context mContext;

        public myTask(){
        }

        public myTask(double b_val ,double e_val,ProgressBar budgetProgressBar, TextView textView1) {
            this.b_val = b_val;
            this.textView1=textView1;
            this.e_val = e_val;
            pStatus = (int) e_val;
            this.budgetProgressBar= budgetProgressBar;
            position = (int) budgetProgressBar.getTag();
            maxBudget = (int) this.b_val;
        }

        int pStatus;
        int maxBudget;

        @Override
        protected void onPreExecute() {
            budgetProgressBar.setMax(maxBudget);
            budgetProgressBar.setVisibility(View.VISIBLE);

               budgetProgressBar.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
    //        }
        }

        @Override
        protected String doInBackground(Void... params) {

            int incrementor =10;

                for (int i = incrementor; i<=pStatus && !isCancelled(); i+=incrementor){

                    if (isCancelled()){
                        Log.d(TAG, "doInBackground: CANCELLED");
                        break;
                    }

                    try {

                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    publishProgress(i);
                }

            return "Complete";
        }

        @Override
        protected void onProgressUpdate(Integer... p) {

            super.onProgressUpdate(p);
            Log.d(TAG, "onProgressUpdate: ");
            if ((int) budgetProgressBar.getTag() == position){
                budgetProgressBar.incrementProgressBy(p[0]);
                budgetProgressBar.setProgress(p[0]);
                textView1.setText(p[0]+"/"+maxBudget);
               // Log.d(TAG, "Setting progress to " + p[0]);

                double calc =(e_val/b_val)*100;
                if (calc>100){
                    calc-=100;
                    textView1.setText("-"+ ((int) calc)+"%");
                }else{
                    textView1.setText(((int) calc)+"%");
                }

            }

        }

    }

Cancelling the AsyncTask

new myTask().cancel(true);

Body:
The AsyncTask#cancel does not stop the doInBackground task even if the method name suggests it as that. What happens is that doInBackground will run until the end and it will call onCancel instead of onPostExecute in the end.

So you might want to add a volatile field flag to AsyncTask and set that as cancelled for example

AsyncTask
private volatile boolean isRunning = true;

public void cancelTask() // sets isRunning to false

And you would check for isRunning instead of isCancelled().


问:
How make Activity run to service
I'm new to java and would like to know how to do an activity run along with a service in the background. So that when the activity is closed and reopened it continues along with the service. I do not know how to explain it.

Suppose 3 services where each one is executed every hour.

Service 1... 1 hour ... Service 2 ... 1 hour ... Service 3. Finished.

And each time it is executed a textview is set visible in the activity. However when the activity is closed the textviews are not created.

The only way I found was by using variables as shown in the example below

Service 1:

```<code>public int service_one_done = 1;
</code>```

Service 2:

```<code>public int service_two_done = 1;
</code>```

Service 3:

```<code>public int service_three_done = 1;
</code>```

Activity onCreate:

```<code>if (service_one_done == 1) { textview_example1.setVisibility(View.VISIBLE)
} if (service_two_done == 1) { textview_example2.setVisibility(View.VISIBLE)
} if (service_three_done == 1) { textview_example3.setVisibility(View.VISIBLE)
}
</code>```

I would like to know if there is a better way to do this

答:
In my Service class I wrote this

```<code>private static void sendMessageToActivity(Location l, String msg) {
    Intent intent = new Intent("GPSLocationUpdates");
    // You can also include some extra data.
    intent.putExtra("Status", msg);
    Bundle b = new Bundle();
    b.putParcelable("Location", l);
    intent.putExtra("Location", b);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
</code>```

and at the Activity side we have to receive this Broadcast message

```<code>LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
            mMessageReceiver, new IntentFilter("GPSLocationUpdates"));
</code>```

By this way you can send message to an Activity. here mMessageReceiver is the class in that class you will perform what ever you want....

in my code I did this....

```<code>private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        String message = intent.getStringExtra("Status");
        Bundle b = intent.getBundleExtra("Location");
        lastKnownLoc = (Location) b.getParcelable("Location");
        if (lastKnownLoc != null) {
            tvLatitude.setText(String.valueOf(lastKnownLoc.getLatitude()));
            tvLongitude
                    .setText(String.valueOf(lastKnownLoc.getLongitude()));
            tvAccuracy.setText(String.valueOf(lastKnownLoc.getAccuracy()));
            tvTimestamp.setText((new Date(lastKnownLoc.getTime())
                    .toString()));
            tvProvider.setText(lastKnownLoc.getProvider());
        }
        tvStatus.setText(message);
        // Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }
};
</code>```

reference here

Title: How make Activity run to service

Body:
I'm new to java and would like to know how to do an activity run along with a service in the background. So that when the activity is closed and reopened it continues along with the service. I do not know how to explain it.

Suppose 3 services where each one is executed every hour.

Service 1... 1 hour ... Service 2 ... 1 hour ... Service 3. Finished.

And each time it is executed a textview is set visible in the activity. However when the activity is closed the textviews are not created.

The only way I found was by using variables as shown in the example below

Service 1:

public int service_one_done = 1;

Service 2:

public int service_two_done = 1;

Service 3:

public int service_three_done = 1;

Activity onCreate:

if (service_one_done == 1) { textview_example1.setVisibility(View.VISIBLE)
} if (service_two_done == 1) { textview_example2.setVisibility(View.VISIBLE)
} if (service_three_done == 1) { textview_example3.setVisibility(View.VISIBLE)
}

I would like to know if there is a better way to do this

Body:
In my Service class I wrote this

private static void sendMessageToActivity(Location l, String msg) {
    Intent intent = new Intent("GPSLocationUpdates");
    // You can also include some extra data.
    intent.putExtra("Status", msg);
    Bundle b = new Bundle();
    b.putParcelable("Location", l);
    intent.putExtra("Location", b);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

and at the Activity side we have to receive this Broadcast message

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
            mMessageReceiver, new IntentFilter("GPSLocationUpdates"));

By this way you can send message to an Activity. here mMessageReceiver is the class in that class you will perform what ever you want....

in my code I did this....

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        String message = intent.getStringExtra("Status");
        Bundle b = intent.getBundleExtra("Location");
        lastKnownLoc = (Location) b.getParcelable("Location");
        if (lastKnownLoc != null) {
            tvLatitude.setText(String.valueOf(lastKnownLoc.getLatitude()));
            tvLongitude
                    .setText(String.valueOf(lastKnownLoc.getLongitude()));
            tvAccuracy.setText(String.valueOf(lastKnownLoc.getAccuracy()));
            tvTimestamp.setText((new Date(lastKnownLoc.getTime())
                    .toString()));
            tvProvider.setText(lastKnownLoc.getProvider());
        }
        tvStatus.setText(message);
        // Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }
};

reference here


问:
HWnd of Visual Studio 2010
Is there a way to get the HWnd pointer to the top window of Visual Studio 2010 from a VSIX extension?  (I would like to change the title of the window).</p>

答:
I'm assuming you want to do this programatically in C#?

You'll need to define this P/Invoke inside your class:

```<code>[DllImport("user32.dll")]
static extern int SetWindowText(IntPtr hWnd, string text);
</code>```

Then have some code that looks similar to the following:

```<code>Process visualStudioProcess = null;
//Process[] allProcesses = Process.GetProcessesByName("VCSExpress"); // Only do this if you know the exact process name
// Grab all of the currently running processes
Process[] allProcesses = Process.GetProcesses();
foreach (Process process in allProcesses)
{
    // My process is called "VCSExpress" because I have C# Express, but for as long as I've known, it's been called "devenv". Change this as required
    if (process.ProcessName.ToLower() == "vcsexpress" ||
        process.ProcessName.ToLower() == "devenv"
        /* Other possibilities*/)
    {
        // We have found the process we were looking for
        visualStudioProcess = process;
        break;
    }
}

// This is done outside of the loop because I'm assuming you may want to do other things with the process
if (visualStudioProcess != null)
{
    SetWindowText(visualStudioProcess.MainWindowHandle, "Hello World");
}
</code>```

Doc on Process: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx

Doc on P/Invoke: http://msdn.microsoft.com/en-us/library/aa288468%28VS.71%29.aspx

Trying this code on my local, it seems to set the window title, but Visual Studio overwrites it under many conditions: gains focus, enters/leaves debug mode...  This could be troublesome.

Note: You can GET the window title straight from the Process object, but you can't set it.

ContentLicense: CC BY-SA 2.5

Title: HWnd of Visual Studio 2010

Body:
I'm assuming you want to do this programatically in C#?

You'll need to define this P/Invoke inside your class:

[DllImport("user32.dll")]
static extern int SetWindowText(IntPtr hWnd, string text);

Then have some code that looks similar to the following:

Process visualStudioProcess = null;
//Process[] allProcesses = Process.GetProcessesByName("VCSExpress"); // Only do this if you know the exact process name
// Grab all of the currently running processes
Process[] allProcesses = Process.GetProcesses();
foreach (Process process in allProcesses)
{
    // My process is called "VCSExpress" because I have C# Express, but for as long as I've known, it's been called "devenv". Change this as required
    if (process.ProcessName.ToLower() == "vcsexpress" ||
        process.ProcessName.ToLower() == "devenv"
        /* Other possibilities*/)
    {
        // We have found the process we were looking for
        visualStudioProcess = process;
        break;
    }
}

// This is done outside of the loop because I'm assuming you may want to do other things with the process
if (visualStudioProcess != null)
{
    SetWindowText(visualStudioProcess.MainWindowHandle, "Hello World");
}

Doc on Process: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx

Doc on P/Invoke: http://msdn.microsoft.com/en-us/library/aa288468%28VS.71%29.aspx

Trying this code on my local, it seems to set the window title, but Visual Studio overwrites it under many conditions: gains focus, enters/leaves debug mode...  This could be troublesome.

Note: You can GET the window title straight from the Process object, but you can't set it.


问:
Not able to use @Autowired with @Mock while creating unit test cases
I have a service say MainService and it has few managers which are initialised with @Autowired, and it is using some external service which are also @Autowired.

My purpose is to create unit test cases so that I can access the inmemory DB with managers, and want to mock the external service.

Now problem which I am facing is if I use @Autowired in my unit test and use @Mock for external services, then it doesn't use mock methods, Instead it uses the actual implementation. If I do @InjectMocks then it doesn't pick the data from repo as it doesn't find the respective dependencies for managers, and if I use @Autowired and @InjectMocks together it still not being able to use the Mocks.

Something like this

```<code>@Service
public class MainService extends AbstractService
{
  @Autowired
  Manager1 manager1;

  @Autowired
  Manager2 manager2;

  @Autowired
  Manager3 manager3;

@Trace(dispatcher = true)
public void mainMethod(int data)
{
 int data1 = manager1.getData(int xyz);\\ getting data from DAO
 int data2 = manager1.getData(int xyz);\\ getting data from DAO
 int data3 = manager1.getData(int xyz);\\ getting data from
                                        \\External Service
    }

  }
</code>```

Now the test case I am writing is

```<code>@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class TestClass {

  @InjectMocks
  @Autowired
  MainService service;

  @Autowired
  RepoForManager1 repoManager1;

  @Autowired
  RepoForManager2 repoManager2;

  @Mock
  Manager3 manager3;

  @Before
  public void initTest()
  {
      MockitoAnnotations.initMocks(this);
      int dataFirst=1;
      int dataSecond =2;
      int dataThird=3;
      int dataForMethod=4;
      repoManager1.save(dataFirst);
      repoManager2.save(dataSecond);
     }

   @Test
      public void testMethod()
      {

         Mockito.when(manager3.getData(Mockito.anyInt())).thenReturn(dataThird);
         service.mainMethod(dataForMethod);
       }
 }
</code>```

This is a replication of the actual service, when I debug the test I found that the mock is not being used, its using actual implementation, and when I removed @Autowired from MainService then it only execute the mocked method.

答:
Instead of using Field Injection(using @Autowired on class variables) use Constructor Injection. This way you can initialize your MainService class with some mocks and some real Implementations. Something like this

```<code>    @Service
    public class MainService extends AbstractService
    {

      private final Manager1 manager1;

      private final Manager2 manager2;

      private final SomeExternalService externalService;

       @Autowired
       public MainService(Manager1 manager1, Manager2 manager2, SomeExternalService externalService)

            this.manager1= manager1;
            this.manager2= manager2;
            this.externalService = externalService;
    }
            ........................
   }
</code>```

From your test class don't Autowire MainService. Just Autowire Manager1 and Manager2 and Create Mock for SomeExternalService(and initialize it). And then create instance of MainService using constructor.

```<code>    public class TestClass {

          MainService service;

          @Autowired
          RepoForManager1 repoManager1;

          @Autowired
          RepoForManager2 repoManager2;

          @Mock
          SomeExternalService externalService;

          @Before
          public void setUp(){
           service = new MainService(repoManager1, repoManager2, externalService);
          }
   }
</code>```

Body:
I have a service say MainService and it has few managers which are initialised with @Autowired, and it is using some external service which are also @Autowired.

My purpose is to create unit test cases so that I can access the inmemory DB with managers, and want to mock the external service.

Now problem which I am facing is if I use @Autowired in my unit test and use @Mock for external services, then it doesn't use mock methods, Instead it uses the actual implementation. If I do @InjectMocks then it doesn't pick the data from repo as it doesn't find the respective dependencies for managers, and if I use @Autowired and @InjectMocks together it still not being able to use the Mocks.

Something like this

@Service
public class MainService extends AbstractService
{
  @Autowired
  Manager1 manager1;

  @Autowired
  Manager2 manager2;

  @Autowired
  Manager3 manager3;

@Trace(dispatcher = true)
public void mainMethod(int data)
{
 int data1 = manager1.getData(int xyz);\\ getting data from DAO
 int data2 = manager1.getData(int xyz);\\ getting data from DAO
 int data3 = manager1.getData(int xyz);\\ getting data from
                                        \\External Service
    }

  }

Now the test case I am writing is

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class TestClass {

  @InjectMocks
  @Autowired
  MainService service;

  @Autowired
  RepoForManager1 repoManager1;

  @Autowired
  RepoForManager2 repoManager2;

  @Mock
  Manager3 manager3;

  @Before
  public void initTest()
  {
      MockitoAnnotations.initMocks(this);
      int dataFirst=1;
      int dataSecond =2;
      int dataThird=3;
      int dataForMethod=4;
      repoManager1.save(dataFirst);
      repoManager2.save(dataSecond);
     }

   @Test
      public void testMethod()
      {

         Mockito.when(manager3.getData(Mockito.anyInt())).thenReturn(dataThird);
         service.mainMethod(dataForMethod);
       }
 }

This is a replication of the actual service, when I debug the test I found that the mock is not being used, its using actual implementation, and when I removed @Autowired from MainService then it only execute the mocked method.

Body:
Instead of using Field Injection(using @Autowired on class variables) use Constructor Injection. This way you can initialize your MainService class with some mocks and some real Implementations. Something like this

    @Service
    public class MainService extends AbstractService
    {

      private final Manager1 manager1;

      private final Manager2 manager2;

      private final SomeExternalService externalService;

       @Autowired
       public MainService(Manager1 manager1, Manager2 manager2, SomeExternalService externalService)

            this.manager1= manager1;
            this.manager2= manager2;
            this.externalService = externalService;
    }
            ........................
   }

From your test class don't Autowire MainService. Just Autowire Manager1 and Manager2 and Create Mock for SomeExternalService(and initialize it). And then create instance of MainService using constructor.

    public class TestClass {

          MainService service;

          @Autowired
          RepoForManager1 repoManager1;

          @Autowired
          RepoForManager2 repoManager2;

          @Mock
          SomeExternalService externalService;

          @Before
          public void setUp(){
           service = new MainService(repoManager1, repoManager2, externalService);
          }
   }


问:
Configuring log4j.xml in Tomcat
I would like to configure the logs for a simple app running in a tomcat and i'd like to send all logs except error level ones to one file, and the errors to other one.

How should i configure the log4j.xml to make it works?

```<code><appender name="regular-container" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="regularLogs.log" />
</appender>

<appender name="error-container" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="errorLogs.log" />
</appender>

<logger name="regular-container">
 ?????????????????????
</logger>

<logger name="error-container">
 ?????????????????????
</logger>
</code>```

答:
Thanks for answer, but it didnt work. Using filter parameter for each appender, yes.</p>

```<code><filter class="org.apache.log4j.varia.LevelRangeFilter">
        <param name="levelMin" value="ERROR" />
        <param name="levelMax" value="FATAL" />
    </filter>
</code>```

Title: Configuring log4j.xml in Tomcat

Body:
I would like to configure the logs for a simple app running in a tomcat and i'd like to send all logs except error level ones to one file, and the errors to other one.

How should i configure the log4j.xml to make it works?

<appender name="regular-container" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="regularLogs.log" />
</appender>

<appender name="error-container" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="errorLogs.log" />
</appender>

<logger name="regular-container">
 ?????????????????????
</logger>

<logger name="error-container">
 ?????????????????????
</logger>

Body:
Thanks for answer, but it didnt work. Using filter parameter for each appender, yes.

<filter class="org.apache.log4j.varia.LevelRangeFilter">
        <param name="levelMin" value="ERROR" />
        <param name="levelMax" value="FATAL" />
    </filter>


问:
Finding all ng-model elements of a particular child elements
I have written on directive I just want all the ng-model elements inside the element where the directive is placed
This is my html element with loggerhelp  directive

```<code><input type="text" loggerhelp  />
</code>```

This is my directive

```<code>    angular
 .module('app').directive('loggerhelp', loggerhelp);

loggerhelp($mdDialog) {
        var Popupdirective = {
            restrict: 'A',
            scope: false,
            link: popupController
        }
        return Popupdirective
        function popupController(scope, element, attr) {
// Here i want all the child ng-model elements.
            console.log(element)
            alert();
        }
    }
</code>```

答:
You can achieve this by fourth parameter of directive , i.e NgModelController, Read doc.

Code should be like:

```<code> link: function(scope, element, attr, ngModel) {
      $timeout(function() {
        console.log(element);
        console.log(ngModel.$viewValue);
      }, 0)
    }
</code>```

See this example fiddle

Body:
I have written on directive I just want all the ng-model elements inside the element where the directive is placed
This is my html element with loggerhelp  directive

<input type="text" loggerhelp  />

This is my directive

    angular
 .module('app').directive('loggerhelp', loggerhelp);

loggerhelp($mdDialog) {
        var Popupdirective = {
            restrict: 'A',
            scope: false,
            link: popupController
        }
        return Popupdirective
        function popupController(scope, element, attr) {
// Here i want all the child ng-model elements.
            console.log(element)
            alert();
        }
    }

Body:
You can achieve this by fourth parameter of directive , i.e NgModelController, Read doc.

Code should be like:

 link: function(scope, element, attr, ngModel) {
      $timeout(function() {
        console.log(element);
        console.log(ngModel.$viewValue);
      }, 0)
    }

See this example fiddle


问:
version 1.7 of the jvm is not suitable for this product. version 1.8 greater is required for eclipse nano in window
I am trying to launch Eclipse Nano in Windows 7, but getting the error:

```<code>Version 1.7 of the JVM is not suitable for this product. version 1.8 greater is required for Eclipse Nano in Windows
</code>```

I already have Java 8 installed on the system

答:
I too got the same error while installing

Possible reason for the error - The eclipse version, you are installing and the Java version should be of same bit, i.e. either 32 bit or 64 bit

Solution: I have downloaded both the java for 64 bit and 32 bit and installed, now my problem is gone.

Please let me know if it works for you.

Body:
I am trying to launch Eclipse Nano in Windows 7, but getting the error:

Version 1.7 of the JVM is not suitable for this product. version 1.8 greater is required for Eclipse Nano in Windows

I already have Java 8 installed on the system


问:
Using IS NULL to convert NULL dates
I'm running a query to change some returned data around in SQL Server 2016, and I am getting a conversion error (Conversion failed when converting date and/or time from character string).

```<code>SELECT jobs.name,
       CASE WHEN jact.start_execution_date IS NULL THEN 'No Execution'
            ELSE jact.start_exeuction_date
       END AS start_execution_date
FROM   msdb.dbo.sysjobactivity jact
       INNER JOIN msdb.dbo.sysjobs jobs
         ON jact.job_id = jobs.job_id
</code>```

The start_execution_date column is a DATETIME type. This column either has a datetime format of (YYYY-MM-DD HH:MM:SS.mmm) or NULL in it. I even tried using COALESCE to make the code a little easier to read but that also did not work and gave the same error. When viewing the returned result set up to the point of the error, it is failing at the first row that has a NULL in this column. What am I doing wrong/not considering?

```<code>SELECT COALESCE(jact.start_execution_date, 'No Execution')
</code>```

答:
Your result set (the output of this query) has to have the same field type in each field. It's like a derived table, so you can't have a varchar 'No Execution' residing in the same field as your date from jact.start_execution_date.

However, you can cast the date as a VARCHAR() like:

```<code>COALESCE(CAST(jact.start_execution_date AS VARCHAR(20), 'No Execution') as start_execution_date
</code>```

Just know that your date is now a string date, which is fine if this is being outputted somewhere.

Title: Using IS NULL to convert NULL dates

Body:
I'm running a query to change some returned data around in SQL Server 2016, and I am getting a conversion error (Conversion failed when converting date and/or time from character string).

SELECT jobs.name,
       CASE WHEN jact.start_execution_date IS NULL THEN 'No Execution'
            ELSE jact.start_exeuction_date
       END AS start_execution_date
FROM   msdb.dbo.sysjobactivity jact
       INNER JOIN msdb.dbo.sysjobs jobs
         ON jact.job_id = jobs.job_id

The start_execution_date column is a DATETIME type. This column either has a datetime format of (YYYY-MM-DD HH:MM:SS.mmm) or NULL in it. I even tried using COALESCE to make the code a little easier to read but that also did not work and gave the same error. When viewing the returned result set up to the point of the error, it is failing at the first row that has a NULL in this column. What am I doing wrong/not considering?

SELECT COALESCE(jact.start_execution_date, 'No Execution')

Body:
Your result set (the output of this query) has to have the same field type in each field. It's like a derived table, so you can't have a varchar 'No Execution' residing in the same field as your date from jact.start_execution_date.

However, you can cast the date as a VARCHAR() like:

COALESCE(CAST(jact.start_execution_date AS VARCHAR(20), 'No Execution') as start_execution_date

Just know that your date is now a string date, which is fine if this is being outputted somewhere.


问:
get next immediate same date using php

i need to get immediate date like if i select date is 05 then output will be 2017-07-05 cause select date already passed

if i select 12 then output will be 2017-06-12 cause this date future date

final if i select previous date of current month then output will be next month same date and if i select future date of current month then output will be same month

i have tired but not working this

```<code>$today = date("Y-m-d");
$next_payment_date = date('Y-m-d', strtotime('+1 month', $today));
</code>```

or

```<code>$time = time();
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));
</code>```

thanks in your advance

答:
use this,</p>

```<code>$today = date('Y-m-d');
$nextDate = date('Y-m-d', strtotime('+1 month'));
or $nextDate = date('Y-m-d', strtotime('+1 month', strtotime($today));
</code>```

Title: get next immediate same date using php

Body:
i need to get immediate date like if i select date is 05 then output will be 2017-07-05 cause select date already passed

if i select 12 then output will be 2017-06-12 cause this date future date

final if i select previous date of current month then output will be next month same date and if i select future date of current month then output will be same month

i have tired but not working this

$today = date("Y-m-d");
$next_payment_date = date('Y-m-d', strtotime('+1 month', $today));

or

$time = time();
date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));

thanks in your advance

Body:
use this,

$today = date('Y-m-d');
$nextDate = date('Y-m-d', strtotime('+1 month'));
or $nextDate = date('Y-m-d', strtotime('+1 month', strtotime($today));


问:
Too few parameters: the query defines 1 parameters but you only bound 0
Symfony Version 3.2.8

I am unsure what is causing this error, according to Doctrine Documentation the setParameter function is being used correctly?

Broken Code:

```<code>public function getNewShipChoices($uid, $fid) {
        /*Identify ships all ready added in fleet and do not allow them to be added again*/
        $q2 = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = :uid')->setParameter('uid', $uid)
                    ->andWhere('c2.fleetId = :fid')->setParameter('fid', $fid);

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $q2->getDQL()))->andWhere('c3.userid = :uid')->setParameter('uid', $uid);

        return $query->getQuery()->getResult();
    }
</code>```

Another thing I tried was to hard code the setParameter values, which brings the same error message

```<code> ->where('c.userid = :uid')->setParameter('uid', 1)
                            ->andWhere('c2.fleetId = :fid')->setParameter('fid', 1);
</code>```

Working Code:
Replacing the setParameter with hard coded values instead of passing in 2 integer values of 1 and 1 works fine.

```<code> public function getNewShipChoices($uid, $fid) {
        $q2 = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = 1')
                    ->andWhere('c2.fleetId = 1');

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $q2->getDQL()))->andWhere('c3.userid = 1');

        return $query->getQuery()->getResult();
    }
</code>```

Did I miss something completely obvious?

答:
Doctrine expression 'notIn' accepts array values in second argument. You have given query. Also, you should bind parameter using 'setParameter' to avoid injection.
Please try this. </p>

```<code>public function getNewShipChoices($uid, $fid) {
        $shipIds = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = 1')
                    ->andWhere('c2.fleetId = 1')
                    ->getQuery()
                    ->getResult();

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $shipIds))->andWhere('c3.userid = :UserId')->setParameter(":UserId", $uid);

        return $query->getQuery()->getResult();
    }
</code>```

Body:
Symfony Version 3.2.8

I am unsure what is causing this error, according to Doctrine Documentation the setParameter function is being used correctly?

Broken Code:

public function getNewShipChoices($uid, $fid) {
        /*Identify ships all ready added in fleet and do not allow them to be added again*/
        $q2 = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = :uid')->setParameter('uid', $uid)
                    ->andWhere('c2.fleetId = :fid')->setParameter('fid', $fid);

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $q2->getDQL()))->andWhere('c3.userid = :uid')->setParameter('uid', $uid);

        return $query->getQuery()->getResult();
    }

Another thing I tried was to hard code the setParameter values, which brings the same error message

 ->where('c.userid = :uid')->setParameter('uid', 1)
                            ->andWhere('c2.fleetId = :fid')->setParameter('fid', 1);

Working Code:
Replacing the setParameter with hard coded values instead of passing in 2 integer values of 1 and 1 works fine.

 public function getNewShipChoices($uid, $fid) {
        $q2 = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = 1')
                    ->andWhere('c2.fleetId = 1');

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $q2->getDQL()))->andWhere('c3.userid = 1');

        return $query->getQuery()->getResult();
    }

Did I miss something completely obvious?

Body:
Doctrine expression 'notIn' accepts array values in second argument. You have given query. Also, you should bind parameter using 'setParameter' to avoid injection.
Please try this.

public function getNewShipChoices($uid, $fid) {
        $shipIds = $this->createQueryBuilder('c')
                    ->select('DISTINCT (c2.shipId)')
                    ->join('AppBundle:ShipsFleet', 'c2')
                    ->where('c.userid = 1')
                    ->andWhere('c2.fleetId = 1')
                    ->getQuery()
                    ->getResult();

        $query = $this->createQueryBuilder('c3');
        $query->where($query->expr()->notIn('c3.shipId', $shipIds))->andWhere('c3.userid = :UserId')->setParameter(":UserId", $uid);

        return $query->getQuery()->getResult();
    }


问:
Can't center a View in an activity in XML (Android)
I have created a new (second) activity in my android app, and right now there is one view in the content_area_reduction.xml (EditText). The file looks like this:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.myname.appname.AreaReductionActivity"
    tools:showIn="@layout/activity_area_reduction">

        <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>

</RelativeLayout>
</code>```

The problem is, the view appears on the left of the screen instead of center. How do I fix this issue? Will post more code if needed.

Thank you

答:
try this code:</p>

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.company.myname.appname.AreaReductionActivity"
tools:showIn="@layout/activity_area_reduction">

    <EditText
        android:id="@+id/edit2"
        android:layout_width="200dip"
        android:layout_height="50dip"
        android:textAlignment="center"
        android:layout_gravity="center"

/>

</FrameLayout>
</code>```

Body:
I have created a new (second) activity in my android app, and right now there is one view in the content_area_reduction.xml (EditText). The file looks like this:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.myname.appname.AreaReductionActivity"
    tools:showIn="@layout/activity_area_reduction">

        <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>

</RelativeLayout>

The problem is, the view appears on the left of the screen instead of center. How do I fix this issue? Will post more code if needed.

Thank you

Body:
try this code:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.company.myname.appname.AreaReductionActivity"
tools:showIn="@layout/activity_area_reduction">

    <EditText
        android:id="@+id/edit2"
        android:layout_width="200dip"
        android:layout_height="50dip"
        android:textAlignment="center"
        android:layout_gravity="center"

/>

</FrameLayout>


问:
How to call object from one class to another in C#
I have a problem that I just can't solve on my own. I am new to programming and I would appreciate if you could help me with this issue:

I have a class I would like to inherit from:

```<code>namespace rsDeployer.Common.SQLServerCommunication
{
    public class RSDatabaseConnectionCreator: LoggerBase
    {
        public RSProfile profile;
        public RSDatabaseConnectionCreator(RSProfile profile)
        {
            this.profile = profile;
        }

        public SqlConnection CreateConnection(RSDatabaseNames DatabaseName, bool UseWindowsAuthentication, bool testConnection = false)
        {
            var connectionString = BuildRSDatabaseConnectionString(DatabaseName, UseWindowsAuthentication);
            if (testConnection)
            {
                return IsConnectionAvailable(connectionString) ? new SqlConnection(connectionString) : null;
            }
            return new SqlConnection(connectionString);
        }
    }
}
</code>```

and I would like to call CreateConnection() in another class to inject to methods to allow me to open connection and then execute scripts.

Edit 1 - class I would like to have it injected to.

```<code>        public void QueryExecution(string SQLQuery)
    {

        //here's where I would like to inject it
        SqlCommand command = new SqlCommand(SQLQuery, conn);
        var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
        file.WriteLine(command);
        file.Close();
    }
</code>```

If this question is way to silly to deserve answer would you just point in the direction where I should read about it?

I hope this question is well asked and clear.
Thanks in advance.

答:
Like this,

```<code>public void QueryExecution(string SQLQuery)
{
    RSProfile profile = new RSProfile();
    RSDatabaseConnectionCreator instance = new RSDatabaseConnectionCreator(profile);
    SqlConnection conn = instance.CreateConnection(...);
    SqlCommand command = new SqlCommand(SQLQuery, conn);
    var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
    file.WriteLine(command);
    file.Close();
    conn.Close();
}
</code>```

You also told that you want to inherit from this class, here is another approach,

```<code>public class RSDatabaseConnectionCreator : LoggerBase
{
    public virtual object CreateConnection() // by virtual you can override it.
    {
      return new object();
    }
}

public class AnotherClass : RSDatabaseConnectionCreator {

    public AnotherClass() {
        CreateConnection(); // by inheriting RSDatabaseConnectionCreator , you can reach public functions.
    }

    public override object CreateConnection() // or you can override it
    {
        // here might be some user Login check
        return base.CreateConnection(); // then you open connection
    }
}
</code>```

Hope helps,

Body:
I have a problem that I just can't solve on my own. I am new to programming and I would appreciate if you could help me with this issue:

I have a class I would like to inherit from:

namespace rsDeployer.Common.SQLServerCommunication
{
    public class RSDatabaseConnectionCreator: LoggerBase
    {
        public RSProfile profile;
        public RSDatabaseConnectionCreator(RSProfile profile)
        {
            this.profile = profile;
        }

        public SqlConnection CreateConnection(RSDatabaseNames DatabaseName, bool UseWindowsAuthentication, bool testConnection = false)
        {
            var connectionString = BuildRSDatabaseConnectionString(DatabaseName, UseWindowsAuthentication);
            if (testConnection)
            {
                return IsConnectionAvailable(connectionString) ? new SqlConnection(connectionString) : null;
            }
            return new SqlConnection(connectionString);
        }
    }
}

and I would like to call CreateConnection() in another class to inject to methods to allow me to open connection and then execute scripts.

Edit 1 - class I would like to have it injected to.

        public void QueryExecution(string SQLQuery)
    {

        //here's where I would like to inject it
        SqlCommand command = new SqlCommand(SQLQuery, conn);
        var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
        file.WriteLine(command);
        file.Close();
    }

If this question is way to silly to deserve answer would you just point in the direction where I should read about it?

I hope this question is well asked and clear.
Thanks in advance.

Body:
Like this,

public void QueryExecution(string SQLQuery)
{
    RSProfile profile = new RSProfile();
    RSDatabaseConnectionCreator instance = new RSDatabaseConnectionCreator(profile);
    SqlConnection conn = instance.CreateConnection(...);
    SqlCommand command = new SqlCommand(SQLQuery, conn);
    var file = new StreamWriter(@"D:\Project\rsDeployer\ImportedQuery.txt");
    file.WriteLine(command);
    file.Close();
    conn.Close();
}

You also told that you want to inherit from this class, here is another approach,

public class RSDatabaseConnectionCreator : LoggerBase
{
    public virtual object CreateConnection() // by virtual you can override it.
    {
      return new object();
    }
}

public class AnotherClass : RSDatabaseConnectionCreator {

    public AnotherClass() {
        CreateConnection(); // by inheriting RSDatabaseConnectionCreator , you can reach public functions.
    }

    public override object CreateConnection() // or you can override it
    {
        // here might be some user Login check
        return base.CreateConnection(); // then you open connection
    }
}

Hope helps,


问:
How can i apply multiple filters in react?
How can I filter a list with multiple fields? The program that I have has a list of data where there are 2 filters: work and city, but if I select both it doesn't take both the fields it only filters the previously selected field.

How can a make this program filter with both the fields?

答:
You could use a local variable inside your render() function and filter twice depending on whether or not said filter is on or not.

I have posted a simple demo below. Enter the full name or city to filter the list.

class MyApp extends React.Component {

  constructor() {
    super();
    this.state = {
      filterName: "",
      filterCity: "",
      friends: [
        {id: 1, name: "Carl", city: "New York"},
        {id: 2, name: "Anna", city: "New York"},
        {id: 3, name: "Carl", city: "Sydney"}
      ]
    };
  }

  changeFilterName = (e) => {
    this.setState({filterName: e.target.value});
  }

  changeFilterCity = (e) => {
    this.setState({filterCity: e.target.value});
  }

  render() {
    let friends = this.state.friends.slice();
    if(this.state.filterName) {
      friends = friends.filter(item => item.name.toLowerCase() == this.state.filterName.toLowerCase());
    }
    if(this.state.filterCity) {
      friends = friends.filter(item => item.city.toLowerCase() == this.state.filterCity.toLowerCase());
    }
    return(

        Name:
        <input id="name" onChange={this.changeFilterName} value={this.state.filterName} />
        City:
        <input id="city" onChange={this.changeFilterCity} value={this.state.filterCity} />

          {friends.map(item =>
{item.name + " - " + item.city}
)}

    );
  }
}

ReactDOM.render(<MyApp />, document.getElementById("myApp"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="myApp"></div></code>```

Body:
You could use a local variable inside your render() function and filter twice depending on whether or not said filter is on or not.

I have posted a simple demo below. Enter the full name or city to filter the list.

class MyApp extends React.Component {

  constructor() {
    super();
    this.state = {
      filterName: "",
      filterCity: "",
      friends: [
        {id: 1, name: "Carl", city: "New York"},
        {id: 2, name: "Anna", city: "New York"},
        {id: 3, name: "Carl", city: "Sydney"}
      ]
    };
  }

  changeFilterName = (e) => {
    this.setState({filterName: e.target.value});
  }

  changeFilterCity = (e) => {
    this.setState({filterCity: e.target.value});
  }

  render() {
    let friends = this.state.friends.slice();
    if(this.state.filterName) {
      friends = friends.filter(item => item.name.toLowerCase() == this.state.filterName.toLowerCase());
    }
    if(this.state.filterCity) {
      friends = friends.filter(item => item.city.toLowerCase() == this.state.filterCity.toLowerCase());
    }
    return(
      <div>
        <label for="name">Name: </label>
        <input id="name" onChange={this.changeFilterName} value={this.state.filterName} />
        <label for="city">City: </label>
        <input id="city" onChange={this.changeFilterCity} value={this.state.filterCity} />
        <ul>
          {friends.map(item => <li key={item.id}>{item.name + " - " + item.city}</li>)}
        </ul>
      </div>
    );
  }
}

ReactDOM.render(<MyApp />, document.getElementById("myApp"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="myApp"></div>