text:
Q: Couldnt display data from firebase in recyclerview I am developing an android app which shows the user with the latest jobs from various fields. I want to display the jobs that the user has applied so far in "Your Applications" section.
But the values are not getting retrieved. It displays a blank activity. I have attached the code.
Applications.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Application;
import android.app.ProgressDialog;
import android.os.Bundle;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class Applications extends AppCompatActivity {

    DatabaseReference databaseReference;
    FirebaseDatabase firebaseDatabase;
    RecyclerView recyclerView;
    FirebaseUser user;
    FirebaseAuth mAuth;
    ArrayList<Post> posts;
    MyAdap adap;
    ProgressDialog pd;
    long maxid=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_applications);
        recyclerView = findViewById(R.id.work);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAuth = FirebaseAuth.getInstance();
        user = mAuth.getCurrentUser();
        posts = new ArrayList<>();
        pd= new ProgressDialog(Applications.this);
        pd.setMessage("Loading...");
        pd.show();

        getSupportActionBar().setTitle("Your Applications");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference("Job Applications");

        Query query = databaseReference.orderByChild(String.valueOf(maxid+1)).equalTo(user.getUid());
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds: dataSnapshot.getChildren()){
                    Post p = ds.getValue(Post.class);
                    posts.add(p);
                }
                pd.dismiss();
                adap = new MyAdap(Applications.this, posts);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                pd.dismiss();
            }
        });
    }
}

Posts.java
    public class Post {
    private String jobtitle, jobtype, company, location;

    public Post() {
    }

    public Post(String jobtitle, String jobtype, String company, String location) {
        this.jobtitle = jobtitle;
        this.jobtype = jobtype;
        this.company = company;
        this.location = location;
    }

    public String getJobtitle() {
        return jobtitle;
    }

    public void setJobtitle(String jobtitle) {
        this.jobtitle = jobtitle;
    }

    public String getJobtype() {
        return jobtype;
    }

    public void setJobtype(String jobtype) {
        this.jobtype = jobtype;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

MyAdap.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

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

    Context cb;
    ArrayList<Post> posts;

    public MyAdap(Context c, ArrayList<Post> applications){
        cb=c;
        posts=applications;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(cb).inflate(R.layout.post, parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.jobTitle.setText(posts.get(position).getJobtitle());
        holder.jobType.setText(posts.get(position).getJobtype());
        holder.location.setText(posts.get(position).getLocation());
        holder.companyName.setText(posts.get(position).getCompany());
    }

    @Override
    public int getItemCount() {
        return posts.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView jobTitle, jobType,companyName,location;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            jobTitle = itemView.findViewById(R.id.jobTitle);
            jobType = itemView.findViewById(R.id.jobType);
            companyName = itemView.findViewById(R.id.companyName);
            location = itemView.findViewById(R.id.location);
        }
    }
}

Here is the image of the database.

A: I think you have a problem with your orderByChild and equalTo method in the Query section. Please try without the Query and if you want to add sorting read details here.
And one more thing you don't have any jobtype in your database but in your POJO class you have this field in your Constructor.
databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds: dataSnapshot.getChildren()){
                Post p = ds.getValue(Post.class);
                posts.add(p);
            }
            pd.dismiss();
            adap = new MyAdap(Applications.this, posts);
            recyclerView.setAdapter(adap);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            pd.dismiss();
        }
    });

A: You are not attaching adapter to recycle view
adap = new MyAdap(Applications.this, posts);
recyclerView.setAdapter(adap)

you need to set adpater to recycle view

A: As said by abdul add the adapter to the recycler view and also add the android lifecycle method onStart(); method and in the add adapter.startlisteneing();


text:
Q: How to access dynamic arrays in struct with ctypes? This is my minimal example code.
import ctypes as c
import numpy as np
import subprocess

## the c code
c_code = """

#include<string.h>
#include<stdlib.h>
typedef struct My_Struct_{
    int n;
    float *b;

}My_Struct;

My_Struct *my_struct_new(int n) {
    My_Struct *result = malloc(sizeof *result);
    result->n = n;
    result->b = malloc(n*sizeof result->b[0]);
    memset(result->b,1.0,n*sizeof result->b[0]);
    return result;
}

"""
## creating the so file
with open('temp.c', 'w') as f:
    f.write(c_code)
cmmd = "gcc -std=c99 -lm -shared -o temp.so -fPIC temp.c -lm -Wall -pedantic"
print subprocess.call(cmmd, shell=True)

## importing the so file
c_foo=c.cdll.LoadLibrary("./temp.so")
n = 5

class My_Struct(c.Structure):
 _fields_= [("n",c.c_int),
            ("b",c.POINTER(c.c_float*n))]
my_struct_new = c_foo.my_struct_new
my_struct_new.argtype = [c.c_int]
my_struct_new.restype = c.POINTER(My_Struct)

## creating the struct
p_my_struct = my_struct_new(n)

# trying to read from the struct
print p_my_struct.contents.b[0]
print np.ctypeslib.as_array(p_my_struct.contents.b, (n,1))

But instead of the expected
[[1.0, 1.0, 1.0, 1.0, 1.0]]

I get:
<__main__.c_float_Array_5 object at 0x35fe3b0>
[[]
 [�@�^]
 [��A��������]
 [`��J�]
 [t*Op]]

A: You passed a pointer instead of the array. It should be as_array(p_my_struct[0].b[0], (n, 1)).
Comments:

*

*You have a typo. It should be argtypes with an s.

*memset sets a char value, so each value will be c_float.from_buffer(bytearray('\1\1\1\1')) == 2.3694278276172396e-38.

*If you want the values as a Python list, use p_my_struct[0].b[0][:].

redpajama_set_name: RedPajamaStackExchange


text:
Q: Datapump Import Fails With ORA-39006, ORA-39213: "Metadata processing is not available" I am trying to import multiple dmp files using impdp command i got this error DataPump import (impdp) reports the errors:
Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production

With the Partitioning, OLAP and Data Mining options

ORA-39006: internal error

ORA-39213: Metadata processing is not available

Attempting to correct the error ORA-39213 via
dbms_metadata_util.load_stylesheets also reports errors similar to:
SQL> exec dbms_metadata_util.load_stylesheets;

BEGIN dbms_metadata_util.load_stylesheets; END;

* ERROR at line 1: ORA-22288: file or LOB operation FILEEXISTs failed

Permission denied

ORA-06512: at "SYS.DBMS_METADATA_UTIL", line 1807

ORA-06512: at line 1

A: login from sys and run below query worked for me oracle 11.2
exec dbms_metadata_util.load_stylesheets;


text:
Q: Gluing two hyperbolic surfaces along boundary components in terms of fuchsian representations. Let $\Sigma:=\Sigma_g(\beta_1)$ and $\Sigma':=\Sigma_{g'}'(\beta_2)$ be two hyperbolic surfaces of genus $g$ and $g'$ with boundaries $\beta_1$ and $\beta_2$ of the same length.
Choose base points $p_1 \in \beta_1$ and $p_2 \in \beta_2$ and Fuchsian representation $\rho_1: \pi_1(\Sigma, p_1) \to \operatorname{PSL}(2, \mathbb{R})$ and $\rho': \pi_1(\Sigma', p_2) \to  \operatorname{PSL}(2, \mathbb{R})$.
Choose presentations
$$ \pi_1(\Sigma,p_1) = \langle  A_1, \dots A_g, B_1, \dots, B_g, \beta_1 \ | \  [A_1, B_1], \dots [A_g, B_g] \beta_1 =1 \rangle$$
$$ \pi_1(\Sigma',p_2) = \langle  A_1', \dots A_g', B_1', \dots, B_g', \beta_2 \ | \  [A_1', B_1'], \dots [A_g', B_g'] \beta_2 =1 \rangle$$
Since $\beta_1$ and $\beta_2$ are of the same lengths, there exists an isometry of $S^1$ sending $p_1 \mapsto p_2$. We use this isometry to glue $\Sigma_1$ to $\Sigma'$ along $\beta_1$ and $\beta_2$ and obtain new hyperbolic surface $\Sigma \cup_{\beta_1 } \Sigma'$.
Is there a natural way to describe the resulting Fuchsian representation $\rho'': \pi_1(\Sigma \cup_{\beta} \Sigma') \to \operatorname{PSL}(2, \mathbb{R})$?
I would appreciate a reference describing how gluing two hyperbolic surfaces translates to gluing their respective Fuchsian representations.

A: Let me make some additional necessary assumptions for my answer. First, I'll assume that $\beta_1$ and $\beta_2$ are both geodesics. Second, I'll assume that they are oriented so that the gluing preserves orientation (which means one of them has the positive boundary orientation with respect to its surface, and the other has the negative boundary orientation).
Let's think of the oriented closed curve $\beta_i$ as representing an element of the fundamental group denoted $[\beta_i] \in \pi_1(\Sigma_i,p_i)$, i.e. the path homotopy class of $\beta_i$. Under the Fuchsian representation $\rho_i$, one obtains a hyperbolic element $\gamma_i = \rho_i[\beta_i] \in \text{PSL}(2,\mathbb R)$, whose axis is a hyperbolic geodesic $L_i$. Let's choose a base point $\tilde p_i \in L_i$ which is a lift of the base point $p$ (here I am using the developing map embedding of the universal covering space of $\Sigma_i$ into $\mathbb H^2$, with respect to which $\rho_i(\Sigma_i)$ acts as deck transformation group).
Since $\gamma_1$ and $\gamma_2$ are both orientation preserving hyperbolic isometries with the same translation length, they are conjugate elements of $\text{PSL}(2,\mathbb R)$. More specifically, there is a unique $\delta \in \text{PSL}(2,\mathbb R)$ such that $\delta(L_1)=L_2$ preserving orientation, and $\delta(\tilde p_1)=\tilde p_2$.
The Fuchsian representation $\rho''$ can now be described as follows. The restriction of $\rho''$ to $\pi_1(\Sigma_1,p_1)$ is equal to $\rho_1$. The restriction of $\rho''$ to $\pi_1(\Sigma_2,p_2)$ is equal to $\delta^{-1} \rho_2 \delta$. Both restrictions agree under the identification of $[\beta_1]=[\beta_2]$. Using the universal property for the amalgamated free product, it follows that $\rho''$ now extends to a representation $\pi_1(\Sigma_1 \cup_\beta \Sigma_2,p) \to \text{PSL}(2,\mathbb R)$.
There's still some work to do to prove that $\rho''$ is a representation that produces the glued up hyperbolic structure on the surface $\Sigma_1 \cup_\beta \Sigma_2$, but perhaps this is a good place to stop.


text:
Q: Specifying integer latent variable in stan I'm learning Bayesian data analysis. I try to replicate the tutorials by Trond Reitan by stan, which are originally created by WinBugs.
Specifically, I have following data and model
weta.windata<-list(numdet=c(0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2, 0, 3, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 1, 0, 3, 1, 1, 3, 1, 1, 2, 0, 2, 1, 1, 1, 1,0, 0, 0, 2, 0, 2, 4, 3, 1, 0, 0, 2, 0, 2, 2, 1, 0, 0, 1),
           numvisit=c(4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4,4, 4, 4, 4, 4, 4, 4 ,4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3),
           nsites=72)

model_string1="
data{
int nsites;
real<lower=0> numdet[nsites];
real<lower=0> numvisit[nsites];
}
parameters{
real<lower=0> p;
real<lower=0> psi;
int<lower=0> z[nsites];
}
model{
p~uniform(0,1);
psi~uniform(0,1);

for(i in 1:nsites){
z[i]~ bernoulli(psi);
p.site[i]~z[i]*p;
numdet[i]~binomial(numvisit[i],p.site[i]);
}
}
"

mcmc_samples <- stan(model_code=model_string1,
                      data=weta.windata,
                      pars=c("p","psi","z"),
                      chains=3, iter=30000, warmup=10000)

The context is about detecting wetas in fields. There are 72 sites. for each site, researchers visited several times (i.e., numvisit) and recorded the number of times weta found (i.e., numdet).
There is a latent variable z, describing whether one site has weta or not. psi is the probability that one site has weta. p is the detection rate.
The problem I have is I can not declare z to be integers
parameters or transformed parameters cannot be integer or integer array;  found declared type int, parameter name=z
Problem with declaration.

However, if I set z to be real, that is,
real<lower=0> z[nsites];

the problem becomes I cannot set the variable from bernoulli as integer...
No matches for:

  real ~ bernoulli(real)

I'm very new to stan. Forgive me if this question is very silly.

A: Stan doesn't support integer parameters or hacks to let you pretend real variables are integers.  What it does support is marginalizing the integer variables out of the density.  You can then reconstruct them with much more efficiency and much higher tail resolution.
The chapter in the manual on latent discrete parameters is the place to start.  It includes an implementation of the CJS population models, which may be familiar.  I implemented the Dorazio and Royle occupance models as a case study and Hiroki Ito translated the entire Kery and Schaub book to Stan. They're all linked under users >> documentation on the web site.

A: I ran into this mysterious error with ulam while answering practice problems in Statistical Rethinking. When you're constructing a list to pass to the data argument to ulam be sure to use = rather than <- for assignment. If you don't the list you construct won't have named components, and a missing name produces this error.


text:
Q: Is there a way to force Mac OS X to close all the applications when restarting? I sometimes shut down my Mac, and I cannot wait it shuts down because I am urgently requested to do something in another office that would require some hours. In some cases, an application that opens a dialog box asking if I really want to close the application blocks the shut down, and when I return I find the Mac still on.
Is there a way to force the Mac to close any applications, instead of blocking the shut down?

A: All you need is to open Terminal.app and type:
sudo shutdown now

That way the system will be forced to terminate all open programs, ignoring any unsaved file changes.
So, in order to be able to launch it via the desktop, you need to open Applescript editor, and type:
do shell script "shutdown now" with administrator privileges

Save the script as an Application, and drag it in your Dock, or somewhere where you'll find it instantly.


text:
Q: Is it possible to set a gtk theme for flatpak apps independet from the Gnome theme configuration? Is it possible to set a gtk theme for flatpak apps independent from the Gnome theme configuration?
For Gnome I am using the POP! Slim theme, which is not available in the flatpak theme repo yet. Only the dark and light slim version is available there. For Flatpak apps, I could live with the normal giant POP! theme, which is already available in the flatpak theme repo. Right now the only way that works for me to set the POP! theme for Flatpak is by setting my whole Gnome theme to Pop! standard.
Is there a different way to handle the flatpak gtk theme independently from the Gnome setting?

A: Yes, it is possible.
A simple method is to install a theme, and it will switch to newest installed theme automatically.
e.g.
flatpak install org.gtk.Gtk3theme.Yaru


text:
Q: Sandboxed web part failing with "No available sandboxed code execution server could be found" I'm deploying a web part as a component of a sandboxed solution from Visual Studio 2010 to Windows 7 SharePoint Foundation Server 2010 on my development box, and I receive the following error when viewing the web part on the deployed web part page:
Web Part Error: No available sandboxed code execution server could be found.

[SPUserCodeExecutionPipelineFailedException: No available sandboxed code execution server could be found.]
  at Microsoft.SharePoint.UserCode.SPUserCodeExecutionManager.Execute(Type userCodeWrapperType, SPSite site, SPUserCodeExecutionContext executionContext)
  at Microsoft.SharePoint.UserCode.SPUserCodeWebPartRemoteExecutionHelper.<>c__DisplayClassa.b__9()
  at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
  at Microsoft.SharePoint.UserCode.SPUserCodeWebPartRemoteExecutionHelper.ExecuteRequestInSandBox(HttpContext context, SPWeb web, SPWebPartManager manager, SPUserCodeWebPart userCodeWebPart)

[SocketException: No connection could be made because the target machine actively refused it 192.168.222.1:32846]

 Server stack trace:
  at System.Net.Sockets.Socket.Connect(IPAddress[] addresses, Int32 port)
  at System.Runtime.Remoting.Channels.RemoteConnection.CreateNewSocket(AddressFamily family)
  at System.Runtime.Remoting.Channels.RemoteConnection.CreateNewSocket()
  at System.Runtime.Remoting.Channels.SocketCache.GetSocket(String machinePortAndSid, Boolean openNew)
  at System.Runtime.Remoting.Channels.Tcp.TcpClientTransportSink.SendRequestWithRetry(IMessage msg, ITransportHeaders requestHeaders, Stream requestStream)
  at System.Runtime.Remoting.Channels.Tcp.TcpClientTransportSink.ProcessMessage(IMessage msg, ITransportHeaders requestHeaders, Stream requestStream, ITransportHeaders& responseHeaders, Stream& responseStream)
  at System.Runtime.Remoting.Channels.BinaryClientFormatterSink.SyncProcessMessage(IMessage msg)

 Exception rethrown at [0]:
  at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
  at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
  at Microsoft.SharePoint.Administration.ISPUserCodeExecutionHostProxy.Execute(Type userCodeWrapperType, Guid siteCollectionId, SPUserToken userToken, String affinityBucketName, SPUserCodeExecutionContext executionContext)
  at Microsoft.SharePoint.UserCode.SPUserCodeExecutionManager.Execute(Type userCodeWrapperType, SPSite site, SPUserCodeExecutionContext executionContext)

I've heard this can be related to the 'SharePoint 2010 User Code Host' service being stopped, and sure enough it isn't running. However, when I start the service it immediately stops itself, with no warning or error (the Event log only shows the "started successfully" message).
This in turn (I've heard) may be related to the 'SharePoint Foundation Search V4' service being stopped, but this isn't the case.
Has anyone else come across this issue and managed to resolve it?

Edit:
I've found the following several times in the SharePoint logs:
Performance Counter OS (pdh) call failed with error code PDH_INVALID_HANDLE.
 - Unhandled exception System.ComponentModel.Win32Exception: Unknown error (0xc0000bbc)     at Microsoft.SharePoint.Win32.SPPdh.CheckReturnValue(PDH_STATUS status, Boolean throwOnError)     at Microsoft.SharePoint.Utilities.SPPerformanceCounter.NextValue(Int32 retry, Int32 retryInterval)     at Microsoft.SharePoint.UserCode.SPUserCodePerformanceCounterHelper..ctor(String processName, Int32 processInstanceId) thrown while reading perf counters for process "SPUCWorkerProcess".

This can apparently be caused by the 'SharePoint 2010 User Code Host' service running as a user that isn't in the required local user groups WSS_ADMIN_WPG and WSS_WPG. However, my service is using the 'Network Service' user, which is in both groups.
James Pritz has an interesting article on the matter, but his resolution(s) didn't work for me.

A: check if the 'Microsoft SharePoint Foundation Sandboxed Code Service' service is started
SharePoint 2010 Central Administration -> System Settings -> Manage Services on Server

A: This was the fix for me
Original link: http://social.technet.microsoft.com/Forums/en-US/sharepoint2010setup/thread/0efa29a6-9bb1-4c2f-a4ef-113bb2601aa5/
regedit:
In HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\PerfProc\Performance
If "Disable Performance Counters" is 1, set it to 0 !
Then start "SharePoint 2010 User Code host" in  Services.

A: Try this
Add User for service "SharePoint 2010 User Code Host" to "Performance Monitor Users" group.

A: I had the same error, and I just closed and reopened my PowerShell window to make it work.
Hope this can help in some cases.

A: It has become increasingly obvious that reinstalling SharePoint is going to be necessary.
The symptoms seem to point to a permissions issue with the user accounts used to run the services, which are notoriously difficult to configure correctly outside of SharePoint's own installation process.


text:
Q: Magento 1.9 collection multi conditions I read many posts and articles but still didn't find a solution.
I would like to filter my product collection with this condition:
...
WHERE ('supplier_id' = 1 AND 'product_type' = 'first_type')
OR ('supplier_id' = 2 AND 'product_type' = 'another_type')
...

Is it possible to achieve this using addFieldToFilter method?
Any other suggestions are welcome as well!

A: Can you try by this way, I think this will solve your problem
->getSelect()->where(" (`Your attribute` = 'Value' AND `Your attribute` = 'Value') OR (`Your attribute` = 'Value' AND `Your attribute` = 'Value')");

In your case in the getSelect() could be:
->getSelect()->where("(`supplier_id` = '1' AND `product_type` = 'first_type') OR (`supplier_id` = '2' AND `product_type` = 'another_type')");


text:
Q: R, data.table: How to prevent fread from inferring NAs for one column? I have a csv that has a column with string values. One of these values is a the literal string NA, which I want to treat as a string. Other columns have actual NAs that I would like to treat as NAs. Is there a way for me to specify that fread should not automatically parse NAs for one column? I have tried using the colClasses argument, but this doesn't seem to work. (I suspect it runs the conversion after the automatic parsing of NAs happens, while I'm looking for something that works like pandas converters argument that seems to perform the casting while reading.)
MWE:
test.csv:
strings,other.values
NA,blah
blah,NA

I want to read the NA in strings as the character sequence NA, but the NA in other.values as the value NA.
> library(data.table)
> df <- fread('test.csv', header=TRUE) # adding colClasses=c('strings'='character') doesn't help
> df
    strings other.values
1:    <NA>         blah
2:    blah         <NA>
> which(is.na(df), arr.ind=TRUE)
     row col
[1,]   1   1
[2,]   2   2

desired output:
> df
   strings other.values
1:      NA         blah
2:    blah         <NA>
> which(is.na(df), arr.ind=TRUE)
     row col
[2,]   2   2

In case it's relevant, here's a comparison with Python's pandas, which does what I want in this case with its converters argument (though of course I want to do other stuff in R).
>>> import pandas as pd
>>> df = pd.read_csv('test.csv')
>>> df
  strings other.values
0     NaN         blah
1    blah          NaN
>>> df.isnull()
   strings  other.values
0     True         False
1    False          True
>>> df = pd.read_csv('test.csv', converters={'strings':str})
>>> df
  strings other.values
0      NA         blah
1    blah          NaN
>>> df.isnull()
   strings  other.values
0    False         False
1    False          True

Edit: of course, it's possible in this simple case to just do something like this:
> library(dplyr)
> df <- df |> mutate(strings = case_when(is.na(strings) ~ 'NA', TRUE ~ strings))

But this seems like a hack and not generalizable in the way I'm hoping for (for instance, if there are blank spaces in the strings column that would get parsed as NAs, this would collapse the difference).

A: One potential option is to add quotation marks to values in the "strings" column with a preprocessing step, i.e.
Contents of "test.csv":
strings,other.values
NA,blah
blah,NA

library(data.table)

df <- fread(cmd = "sed 's/^/\"/;s/,/\",/' ~/Desktop/test.csv", header = TRUE)
df
#>    strings other.values
#> 1:      NA         blah
#> 2:    blah         <NA>

If the "strings" column is at another position you can tweak the sed command to suit, e.g.
Contents of "test2.csv":
xx,yy,strings,other.values
1,string,NA,blah
2,test,blah,NA

df2 <- fread(cmd = "sed 's/,/,\"/2;s/,/\",/3' ~/Desktop/test2.csv", header = TRUE)
df2
#>    xx     yy strings other.values
#> 1:  1 string      NA         blah
#> 2:  2   test    blah         <NA>


text:
Q: SelectionTracker does not select anything in my Recyclerview When I click on the items nothing happens
I try to change the color, to display the number of selected elements, to display logs
Nothing is happening
MyViewHolder
class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {

val name: TextView = view.list_item_name
val phone: TextView = view.list_item_phone

// More code here
fun getItemDetails(): ItemDetailsLookup.ItemDetails<Long> =
    object : ItemDetailsLookup.ItemDetails<Long>() {
        override fun getSelectionKey(): Long? = itemId

        override fun getPosition(): Int = adapterPosition

    }

}

My ItemDetailsLookup
class MuLookup(private val rv: RecyclerView) : ItemDetailsLookup<Long>() {
    override fun getItemDetails(event: MotionEvent): ItemDetails<Long>? {
        val view = rv.findChildViewUnder(event.x, event.y)
        if (view != null) {
            return (rv.getChildViewHolder(view) as MyViewHolder)
                .getItemDetails()
        }
        return null
    }
}

My adapter
class PersonAdapter(
    private val listItems: List<Person>,
    private val context: Context
) : RecyclerView.Adapter<MyViewHolder>() {

    init {
        setHasStableIds(true)
    }

    private var tracker: SelectionTracker<Long>? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        return MyViewHolder(
            LayoutInflater.from(context)
                .inflate(R.layout.list_item_jf, parent, false)
        )
    }

    override fun getItemCount(): Int {
        return listItems.size
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.name.text = listItems[position].name
        holder.phone.text = listItems[position].phone

        val parent = holder.name.parent as LinearLayout

        if (tracker!!.isSelected(position.toLong())) {
            parent.background = ColorDrawable(
                Color.parseColor("#80deea")
            )
        } else {
            Timber.i("zeze ${tracker!!.selection}")
            // Reset color to white if not selected
            parent.background = ColorDrawable(Color.WHITE)
        }

    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    fun setTracker(tracker: SelectionTracker<Long>?) {
        this.tracker = tracker
    }

}

My activity
class MainActivity : AppCompatActivity() {

    private var tracker: SelectionTracker<Long>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (savedInstanceState != null)
            tracker?.onRestoreInstanceState(savedInstanceState)

        val myList = listOf(
            Person("Alice", "555-0111"),
            Person("Bob", "555-0119"),
            Person("Carol", "555-0141"),
            Person("Dan", "555-0155"),
            Person("Eric", "555-0180"),
            Person("Craig", "555-0145")
        )

        my_rv.layoutManager = LinearLayoutManager(this)
        my_rv.setHasFixedSize(true)

        val adapter = PersonAdapter(myList, this)
        my_rv.adapter = adapter

        tracker = SelectionTracker.Builder<Long>(
            "selection-1",
            my_rv,
            StableIdKeyProvider(my_rv),
            MuLookup(my_rv),
            StorageStrategy.createLongStorage()
        ).withSelectionPredicate(
            SelectionPredicates.createSelectAnything()
        ).build()

        tracker?.addObserver(
            object : SelectionTracker.SelectionObserver<Long>() {
                override fun onSelectionChanged() {
                    val nItems: Int? = tracker?.selection?.size()

                    if (nItems != null && nItems > 0) {

                        // Change title and color of action bar

                        title = "$nItems items selected"
                        supportActionBar?.setBackgroundDrawable(
                            ColorDrawable(Color.parseColor("#ef6c00"))
                        )
                    } else {

                        // Reset color and title to default values

                        title = "RVSelection"
                        supportActionBar?.setBackgroundDrawable(
                            ColorDrawable(Color.parseColor("#126c00"))
                        )
                    }
                }
            })

        adapter.setTracker(tracker)

    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)

        tracker?.onSaveInstanceState(outState)
    }
}

Thank you
Solution: Tracker works I added a setOnClickListener on my view like Khaled Qasem suggest
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    holder.name.text = listItems[position].name
    holder.phone.text = listItems[position].phone

    val parent = holder.name.parent as LinearLayout

    holder.name.setOnClickListener {
        Timber.i("zeze ici")
        if (tracker!!.isSelected(position.toLong())) {
            Timber.i("zeze la")
            parent.background = ColorDrawable(
                Color.parseColor("#80deea")
            )
        } else {
            Timber.i("zeze ${tracker!!.selection}")
            // Reset color to white if not selected
            parent.background = ColorDrawable(Color.WHITE)
        }
    }
}

Color change et number of items is displayed in supportActionBar

A: The problem is that Recyclerview selection is activated only when one item has initially been selected, then you can select other items by simply tapping them.
If you will always need the user to select an item, or to have an item selected, you can use the selectionTracker to initially select one item from the recyclerview:
selectionTracker.select(someItemId)

Now, you can simply select other items from the list by single tapping them.

A: In my case, the solution was to tell the user to long-press the first selection:

Long-press for first setting, then tap other settings for multiple
  selection

My implementation was different but I also observed that the SelectionTracker selected nothing from my RecyclerView.  I could not understand from some SelectionTracker example code how it was supposed to work.  The example showed how the highlight could be set when the a ViewHolder got recycled:
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val number = list[position]
    tracker?.let {
        holder.bind(number, it.isSelected(position.toLong()))
    }
}

fun bind(value: Int, isActivated: Boolean = false) {
    text.text = value.toString()
    itemView.isActivated = isActivated
}

But how is isActivated supposed to be set to true when the user taps the row?
The answer is the user is not supposed to tap; the user is supposed to long-press:

To start selecting items we have to activate first the multi selection mode by long pressing on any item.

A: instead of this you just need to add a click Listener when you create a view holder:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {

    val myViewHolder = MyViewHolder(
        LayoutInflater.from(context)
            .inflate(R.layout.list_item_jf, parent, false)
    )
    myViewHolder.setOnClickListener {
        // Add what you what you need here
    }
    return myViewHolder
}


text:
Q: Bash: trying to echo a string if there isn't enough memory left on the server I would like my script to echo a string, in case there isn't enough memory left on the server. I have tried many things, but the script does not work, I'm afraid its because of converting a string into a number ?
Here is what I have got:
freem=`free -m | sed -n '3p' | tail -c6 | xargs`
max_memory=1000
if [ freem -lt max_memory ]
then echo 'not enough'
else echo 'yay'
fi

freem does have the correct value, but the if does not work, it says:
check_memory.sh: 3: [: Illegal number: freem

I have tried many things, but I cannot get it to work :(.
Could someone please help me ?
Thank you

A: The answer of fedorqui already shows what you missed (the $'s for the variable names). I'd use something like:
let freem=$(free -m | awk '/cache:/ {print $NF}')
let max_memory=1000
if [ $freem -lt $max_memory ]
then echo 'not enough'
else echo 'yay'
fi

I prefer using $( ) instead of back ticks for readability. By using let you state that arg is an arithmetic expression, which makes more sense when comparing values.


text:
Q: Shiny DT, custom button to select filtered rows I would like to include custom buttons as extensions to the data.table in the minimal reproducible example below. This example is essentially taken from this question.
As I have several data.tables in my application, I tried to generalize the node in the JS code of the action definition of the button with the function var table = $(this.api().table().node()).DataTable();, which does not work. If I insert var table = $('#DataTables_Table_0').DataTable(); it works fine, but is not general any more.
Any help is really appreciated!
library(shiny)
library(DT)

ui <- fluidPage(

  titlePanel("Select only filtered rows using selectall button"),

  br(),
  br(),

  DT::dataTableOutput("tableTest")
)

# Define server logic required to draw a histogram
server <- function(input, output) {

  output$tableTest <- DT::renderDataTable({

    datatable(mtcars,
      escape = F,
      rownames = F,
      filter = 'top',
      class = "compact hover row-border",
      extensions = c('Scroller', 'Select', 'Buttons'),

      options = list(
        select = list(style = "multi", items = "row"),
        columnDefs = list(list(className = 'dt-center', targets = "_all")),
        language = list(info = 'Showing _START_ to _END_ of _TOTAL_ variables'),
        deferRender = TRUE,
        scrollY = 500,
        scroller = TRUE,
        dom = "Blfrtip",
        buttons =
          list(
            list(extend='selectAll',
              className='selectAll',
              text="select all rows",
              action = DT::JS(
                "function () {
                var table = $(this.api().table().node()).DataTable();
                table.rows({ search: 'applied'}).deselect();
                table.rows({ search: 'applied'}).select();
              }")
            ),
            list(extend='selectNone',
              text="DeselectAll",
              action = DT::JS(
                "function () {
                var table = $(this.api().table().node()).DataTable();
                table.rows({ search: 'applied'}).select();
                table.rows({ search: 'applied'}).deselect();
              }")
            ))
      ),
      selection = "none"
    ) }, server = F
  )
}

# Run the application
shinyApp(ui = ui, server = server)

A: I have not tried, but I think you can do:
action = JS(
  "function(e, table, node, config) {",
  "  table.rows({ search: 'applied'}).deselect();",
  "  table.rows({ search: 'applied'}).select();",
  "}"
)


text:
Q: Overriding Java security properties on a Dataproc cluster to overcome SSL handshake issue with MS SQL 2019 I am stuck with a problem with Java security setting preventing my Dataproc cluster (Image 2.0.32-debian10) running PySpark to connect to SQL Server 2019 with Spark/JDBC connector (spark:spark.jars.packages=com.microsoft.azure:spark-mssql-connector_2.12:1.2.0 and sqljdbc4-2.0.jar). It seems the security level of the cluster and SQL Server 2019 (running on a GCE) do not match and there is this SSL/TLS error during handshake.

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The driver
could not establish a secure connection to SQL Server by using Secure
Sockets Layer (SSL) encryption. Error: "No appropriate protocol
(protocol is disabled or cipher suites are inappropriate)".
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1368)
at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1412)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1058)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:833)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:716)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)

I could bypass this by using Jupyter Notebook to directly modify "Local Disk/usr/lib/jvm/temurin-8-jdk-amd64/jre/lib/security/java.security" and comment out this part of the code "jdk.tls.disabledAlgorithms=SSLv3, TLSv1, TLSv1.1, RC4, DES, MD5withRSA,
DH keySize lessThan 1024, EC keySize lessThan 224, 3DES_EDE_CBC, anon, NULL,
include jdk.disabled.namedCurves", and I will be able to connect to SQL Server successfully.
However this would work only if my Dataproc cluster is a single node cluster. If it's a standard cluster (e.g. 1 master+2 workers), it seems the node doesn't recognize this change in security properties and I faced the same error as before (perhaps because the job is distributed to a worker node which does not recognize the change in java.security in the master node local disk).
I tried passing these as the cluster properties hoping it would apply the change in security properties to worker nodes as well:
spark:spark.driver.extraJavaOptions='-Djava.security.properties==gs://greenline-demo-341617-spark-src/Demo/02_Microsoft_SQL/java.security',spark:spark.executor.extraJavaOptions='-Djava.security.properties==gs://greenline-demo-341617-spark-src/Demo/02_Microsoft_SQL/java.security'
But I'm stuck at this error instead

Exception in thread "main" java.lang.InternalError: internal error:
SHA-1 not available.
at sun.security.provider.SecureRandom.init(SecureRandom.java:108)
at sun.security.provider.SecureRandom.(SecureRandom.java:79)
at java.security.SecureRandom.getDefaultPRNG(SecureRandom.java:198)
at java.security.SecureRandom.(SecureRandom.java:162)
at java.util.UUID$Holder.(UUID.java:96)
at java.util.UUID.randomUUID(UUID.java:142)

Connection string url_db = "jdbc:sqlserver://10.148.xx.xx:1433;databaseName=AdventureWorks2019;sslProtocol=TLSv1;encrypt=false"


text:
Q: How to ignore part of the functionality in the code if the user types a certain command The "(Type 1 if you dont want to upload an Image.)" doesn't actually work, how do I make it functional ? For example if someone prefers not to add an image into the embed, they can just type "1" and it will ignore the last question.
     if (command === 'call') {
        const questions = [
            { answer: null, field: 'title' },
            { answer: null, field: 'description' },
            { answer: null, field: 'image (**Type 1 if you dont want to upload an Image.**)' },
          ];
          let current = 0;

          const sent = await message.channel.send(
            `**Note 1 of ${questions.length}:**\nWhat would you like the ${questions[current].field} be?`,
          );

          const filter = (response) => response.author.id === message.author.id;
          const collector = sent.channel.createMessageCollector(filter, {
            max: questions.length,
            time: MINUTES * 60 * 1000,
          });

          collector.on('collect', (message) => {

            questions[current++].answer = message.content;
            const hasMoreQuestions = current < questions.length;

            if (hasMoreQuestions) {
              message.channel.send(
                `**Note ${current + 1} of ${questions.length}:**\nWhat would you like the ${questions[current].field} be?`,
              );
            }
          });

          collector.on('end', (collected, reason) => {
            if (reason === 'time') {
              return message.channel.send(
                `${collected.size} questions out of ${questions.length} in ${MINUTES} minutes. Timed out. Please contact Conspet if you think it's a bug. `,
              );
            }

            const embed = new MessageEmbed()
              .setTitle(questions[0].answer)
              .setDescription(questions[1].answer)
              .setColor(0000)
              .setThumbnail("https://images-ext-2.discordapp.net/external/q99pFdqE5zoDRfQb7DDLVOwEpnN6r4OQRR2ZxvqizpM/%3Fwidth%3D434%26height%3D434/https/media.discordapp.net/attachments/814046875555463169/867305615684010014/ezgif.com-optimize.gif?width=270&height=270")
              .setImage(questions[2].answer)
              .setFooter(`Blue Origin - SFS © 2020.` + ` Announcement Identity: ` + makeid(10))
            client.channels.cache.get('814036808304164895').send(embed)
            client.channels.cache.get('814036808304164895').send("**Ping** - @everyone")
          });
        }
      });

A: If you know that it's the last question, you could check the answer. You should only use .setImage() if the answer is not "1".
collector.on('end', (collected, reason) => {
  if (reason === 'time') {
    return message.channel.send(
      `${collected.size} questions out of ${questions.length} in ${MINUTES} minutes. Timed out. Please contact Conspet if you think it's a bug. `,
    );
  }

  const embed = new MessageEmbed()
    .setTitle(questions[0].answer)
    .setDescription(questions[1].answer)
    .setColor(0000)
    .setThumbnail('https://images-ext-2.discordapp.net/external/q99pFdqE5zoDRfQb7DDLVOwEpnN6r4OQRR2ZxvqizpM/%3Fwidth%3D434%26height%3D434/https/media.discordapp.net/attachments/814046875555463169/867305615684010014/ezgif.com-optimize.gif?width=270&height=270')
    .setFooter(`Blue Origin - SFS © 2020.` + ` Announcement Identity: ` + makeid(10));

  if (questions[2].answer !== '1')
    embed.setImage(questions[2].answer);

  client.channels.cache.get('814036808304164895').send(embed);
  client.channels.cache
    .get('814036808304164895')
    .send('**Ping** - @everyone');
});


text:
Q: Tikz - better way of scaling and positioning reusable parts I have some Tikz figures which I use in multiple other figures. Right now I put them in a scope and use xshift/yshift/scale to place them at the position I want them to be. I have one example. I need a figure in a LaTeX document which has a \linewidth of 336pt, thus I want to work on my picture with this width in mind. I start by creating a frame of the desired width and scale. Next I want some boxes in it with some content. One of the boxes contains a stickman which I use in other figures as well. My current solution looks like this:
Here is one example:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}
\begin{tikzpicture}[node distance=0pt]

    % Stickman
    \begin{scope}[xshift=38pt, yshift=105pt, anchor=sout west, scale=0.45,local bounding box=person]
        \draw[thin, line cap=round] (0.05,1) -- (-0.05, 1.1); % hair1
        \draw[thin, line cap=round] (-0.05,1) -- (-0.2, 1.12); % hair1
        \draw[thick] (0,0) circle [radius=1]; % head

        \draw[thin] plot [smooth,tension=1.5] coordinates{(-0.7,0.45) (-0.5,0.52) (-0.4,0.52)}; % leyebrow
        \draw[fill=black] (-0.5,0.25) ellipse (0.1 and 0.15);
        \draw[thin] plot [smooth,tension=1.5] coordinates{(0.3,0.40) (0.1,0.50) (-0.1,0.50)}; % leyebrow
        \draw[fill=black] (0.1,0.20) ellipse (0.1 and 0.15);

        \draw[thick] plot [smooth,tension=1.5] coordinates{(-0.75,-0.4) (-0.2,-0.6) (0.3,-0.53)}; % mouth

        \draw[thick] (-0.15,-1) .. controls (-0.4,-2.5) .. (-0.5,-4); % torso

        \draw[thick] (-0.2,-1.3) -- (0.35, -2.55) -- (1.5, -2.2); % rarm
        \draw[thick,rotate around={110:(1.5, -2.2)}] (1.5, -2.4) ellipse (0.1 and 0.2);
        \draw[thick] (-0.2,-1.3) -- (-1.55, -2.55) -- (-1.75, -4.1); % rarm
        \draw[thick,rotate around={-5:(-1.75, -4.1)}] (-1.75, -4.3) ellipse (0.1 and 0.2);

        \draw[thick] (-0.5,-4) -- (0.7, -5.3) -- (1.4,-6.8); % rleg
        \draw[thick,rotate around={25:(1.4,-6.8)}] (1.65,-6.8) ellipse (0.25 and 0.1);
        \draw[thick] (-0.5,-4) -- (-0.95,-5.8) -- (-2.3,-7); % rleg
        \draw[thick,rotate around={-35:(-2.3,-7)}] (-2.05,-7) ellipse (0.25 and 0.1);
    \end{scope}

    \tikzstyle{box}=[draw, very thick, minimum height=120pt] % box style
    % Stickman Box
    \node[box, anchor=south west, minimum width=60pt] (FrameInput) at (5pt, 5pt) {};
    \node[above=of FrameInput] (xy) {Input};

    % Second box
    \node[box, minimum width=120pt, right=of FrameInput, xshift=15pt] (FrameNextStep) {};
    \node[above=of FrameNextStep] (xy) {NextStep};

    % Box Connections
    \path[->, very thick] (FrameInput) edge (FrameNextStep);

    % Picture Frame
    \draw[thick] (0,0) rectangle (336pt, 150pt); % frame
\end{tikzpicture}
\end{document}

This results in the following image:

I just wonder if there are better ways to solve this. e.g. by specifying my stickman should have a max width / height which equals to the FrameInput box without manually tuning the scale parameter of the scope. The same applies for the x/y shift, is there a better / more elegant way for positioning it?

A: *

*calculate the width and height and lowerleft anchor of original stickman in a pgfinterruptboundingbox environment.

*calculate the shift offset and scale value

*draw the correct stickman with lowerleft corner at (0, 0)
Here is the code:
\documentclass[border=1cm]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning, calc}
\makeatletter
\tikzset{
  stickman height/.store in=\stickman@height,
  stickman height=2cm,
  stickman x sep/.store in=\stickman@x@sep,
  stickman x sep=3pt,
  stickman y sep/.store in=\stickman@y@sep,
  stickman y sep=3pt,
}
\gdef\@stickman{
  \draw[thin, line cap=round] (0.05,1) -- (-0.05, 1.1); % hair1
  \draw[thin, line cap=round] (-0.05,1) -- (-0.2, 1.12); % hair1
  \draw[thick] (0,0) circle [radius=1]; % head

  \draw[thin] plot [smooth,tension=1.5] coordinates{(-0.7,0.45) (-0.5,0.52) (-0.4,0.52)}; % leyebrow
  \draw[fill=black] (-0.5,0.25) ellipse (0.1 and 0.15);
  \draw[thin] plot [smooth,tension=1.5] coordinates{(0.3,0.40) (0.1,0.50) (-0.1,0.50)}; % leyebrow
  \draw[fill=black] (0.1,0.20) ellipse (0.1 and 0.15);

  \draw[thick] plot [smooth,tension=1.5] coordinates{(-0.75,-0.4) (-0.2,-0.6) (0.3,-0.53)}; % mouth

  \draw[thick] (-0.15,-1) .. controls (-0.4,-2.5) .. (-0.5,-4); % torso

  \draw[thick] (-0.2,-1.3) -- (0.35, -2.55) -- (1.5, -2.2); % rarm
  \draw[thick,rotate around={110:(1.5, -2.2)}] (1.5, -2.4) ellipse (0.1 and 0.2);
  \draw[thick] (-0.2,-1.3) -- (-1.55, -2.55) -- (-1.75, -4.1); % rarm
  \draw[thick,rotate around={-5:(-1.75, -4.1)}] (-1.75, -4.3) ellipse (0.1 and 0.2);

  \draw[thick] (-0.5,-4) -- (0.7, -5.3) -- (1.4,-6.8); % rleg
  \draw[thick,rotate around={25:(1.4,-6.8)}] (1.65,-6.8) ellipse (0.25 and 0.1);
  \draw[thick] (-0.5,-4) -- (-0.95,-5.8) -- (-2.3,-7); % rleg
  \draw[thick,rotate around={-35:(-2.3,-7)}] (-2.05,-7) ellipse (0.25 and 0.1);
}
\newlength\pre@y@max
\newlength\pre@y@min
\newlength\pre@other
\tikzset{
  stickman/.pic={
    \begin{pgfinterruptboundingbox}
    \begin{scope}[opacity=0, local bounding box=pre]
      \@stickman
    \end{scope}
    \path (pre.north);
    \pgfgetlastxy{\pre@other}{\pre@y@max}
    \path (pre.south);
    \pgfgetlastxy{\pre@other}{\pre@y@min}
    \pgfmathparse{(\stickman@height - 2*\stickman@y@sep)/(\pre@y@max - \pre@y@min)}
    \global\let\temp@scale\pgfmathresult
    \end{pgfinterruptboundingbox}
    \draw[line width=1pt] let \p1 = (pre.south west), \p2 = (pre.north west), \p3 = (pre.north east) in
      let \p{anchor} = ($(\stickman@x@sep,\stickman@y@sep)-\temp@scale*(pre.south west)$) in
      let \p{other} = ($2*(\stickman@x@sep,\stickman@y@sep)+\temp@scale*(\p3)-\temp@scale*(\p1)$) in
      coordinate (shift) at (\p{anchor})
      coordinate (clip) at (\p{other});
    \begin{scope}[local bounding box=now]
      \draw[line width=1pt] (0, 0) rectangle (clip);
      \begin{scope}[scale=\temp@scale, shift=(shift)]
        \@stickman
      \end{scope}
    \end{scope}
    \coordinate (-north) at (now.north);
    \coordinate (-east) at (now.east);
    \coordinate (-west) at (now.west);
    \coordinate (-south east) at (now.south east);
  }
}
\makeatother

\begin{document}
\begin{tikzpicture}[node distance=0pt]
  \pic [stickman height=3cm] (a) at (0, 0) {stickman};
  \pic [stickman height=3cm, xshift=1cm, stickman x sep=10pt] (b) at (a-south east) {stickman};
  \draw[->, very thick] (a-east) -- (b-west);
  \node[above] at (a-north) {Input};
  \node[above] at (b-north) {NextStep};
\end{tikzpicture}
\end{document}


text:
Q: Why does IE prompts for installing ActiveX control in a .cab but then blocks it anyway? I am embedding an ActiveX control (not developed by me) into a website, deployed in a .cab file.
At first the control was not loaded but, after adding my webserver to the Trusted site list, I can get IE to prompt me whether I want to install the .cab or not

I click 'yes' but then I cannot access the controls of the .ocx, and I keep on getting "Object doesn't support property or method..." errors.
If I manually register the .ocx and the .ax files in the cab, everything works fine.
Is there a way to understand why IE is blocking the control although I'm telling it to run it?

A: If the ActiveX control is not being installed from a code signed cab file then IE cannot verify its authenticity and as such will actively block it.
Steps to fix this:
1) Add the website to the trusted sites in Internet Explorer Options -> Security and set the security level to low or to a custom level allowing unsafe or unsigned ActiveX control to run.
2) Ask the publisher of the third party control for a code signed  cab file. many publisher do provide this option on request after purchase of a license. please confirm this with them.


text:
Q: "SSH server" in Windows? I have some command-line commands to execute on a Windows machine.  The programs I need to run are only available on Windows.
Is there a way to easily to do something like I would do with SSH?  Example of what I mean:
ssh username@windows-box.mycompany.com "remote command to execute"

...or do I have to Remote Desktop just to do this?  (I'd like to run the commands programmatically from another computer rather than running them by hand.)

A: One approach, of course, is to actually run an SSH server on the windows box.  But a more Windows-focused solution is a tool from the SysInternals folks (now part of Microsoft) called PsExec, which is designed to do exactly what you want.

A: You need a SSH server running on windows. like http://www.kpym.com/2/kpym/index.htm
There isnt any installed by default, And I have been using this for some time. it is good

A: I've had a lot of good experience installing cygwin and its sshd port.  There are wrappers which will turn it into a windows service, and you get the bash shell as an extra.
http://chinese-watercolor.com/LRP/printsrv/cygwin-sshd.html is a decent starting point, you can evaluate if it is what you want.

A: You can use the freesshd server from fresshd.com. It does work great, you will set-up the server in seconds :)

A: As of 2015-06-02, Microsoft has announced upcoming support for SSH.

A: Cygwin has a ssh server, howtogeek has a simple guide you can follow
http://www.howtogeek.com/howto/41560/how-to-get-ssh-command-line-access-to-windows-7-using-cygwin/

A: you can install an SSH server on your Windows machines, or you can turn on Terminal services on windows (check your documentation), and then use Perl(or Python) to do a telnet to the server to execute your commands. See Net::Telnet(Perl) for examples of connecting through telnet


text:
Q: text auto fadein when page opened? I am working on a personal website and I want my page to appear blank initially. then the header fades in after a about a second and then the navbar  to fade in after that.
I've only learned how to make things fadein on click, so I looking for help on how to make them fade in automatically, once the page loads.
thanks!

A: You can use jQuery's .delay in $(document).ready:
$(document).ready(function() {
      console.log("document ready occurred!");
      // Add your animations is here:
      var myHeader = $('#header');
      myHerader.delay(500).fadeIn('300');
});

You can use your animations, or maybe use animate.css

A: The animate.css library might be helpful for this: https://daneden.github.io/animate.css/
What you want to do is install the library and write some css like this:

Hello World

When the page loads the animation will happen immediately without any click events.
Here is a link to a fiddle: https://jsfiddle.net/txx00wzr/
Hope this helps.

A: You should start by having your items hidden, the use jQuery's .ready() event to trigger a .fadeIn(). The .fadeIn() function accepts a callback parameter that allows you to chain your animations.
Here's a simple example:

$(function() {
  $(".header").fadeIn(5000, function() {
    $(".header nav").fadeIn(5000);
  });
});
.header {
  display: none;
  height: 100px;
  width: 100%;
  background-color: #ccc;
}

.header nav {
  display: none;
  list-style-type: none;
}

Nav 1

Nav 2

Nav 3

Nav 4

Nav 5

A: If you want to use plain javascript, I'd recommend you to specify display: none; style for all body children initially and then use the onload event like this:
Function fade_in() must make elements visible. I used this line of code: document.getElementById( "<element_id>" ).style.display = "block";
If you want them appear not immediately, but smoothly, just set transition to the value you need.
To make delays, you can use setTimeout() function: setTimeout() on W3Schools
If I have understood you correctly, the solution is that simple.


text:
Q: Hide keyboard when showing SLComposeViewController alerts with No twitter Accounts found I am using the following code for showing the alert for no twitter account configured in settings app of device.
SLComposeViewController *viewController = [[SLComposeViewController alloc] init];
viewController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
//hide tweet sheet
viewController.view.hidden = YES;
[self presentViewController:viewController animated:NO completion:nil];
//hide the keyboard
[viewController.view endEditing:YES];

It is working perfectly fine except that it is not hiding the keyboard. Basically I just want the UIAlertView that can direct users to the settings app. Since the alert view is handled by the social framework, I am unable to find the exact point where I can place the code to hide the keyboard. I can hide the Tweet sheet by    viewController.view.hidden = YES;
Can someone please suggest me so as how to hide the keyboard?


text:
Q: Python streamlit: When using element (here selectbox) within empty().container() doesn't update the variable value outside As an example to recreate my issue I use the following code:
import streamlit as st
from time import sleep
pg = st.empty()
with pg.container():
    start = st.button("start")
if start:
    pg.empty()
    sleep(0.02)
    with pg.container():
        num = st.selectbox("select num",[0,1,2,3,4])
        print(num)
    print(f'value of num outside is: {num}')
    if num:
        pg.empty()
        sleep(0.02)
        with pg.container():
            st.text(f"you selected: {num}")

Thank you in advance.
expected output is:
start button -> on clicked -> selectbox element (prints "0" and "value of num outside is 0" in cmd as it is the default selected option) -> on selecting any number except 0,example 2, container is emptied of the selectbox and replaced with a textbox displaying the selected number (prints "2" and "value of num outside is 2" in cmd)
what happens is:
start button -> on clicked -> selectbox element (prints "0" and "value of num outside is 0" in cmd as it is the default selected option) -> on selecting any number except 0,example 2, the selectbox is emptied from the container but no text box is displayed. And "2" or "value of num outside is 2" is not shows on cmd as well. Instead the start button is displayed again.


text:
Q: Deduplicating Laravel events / jobs I have an app that processes product and order updates and use a mixture of events and jobs to respond to changes in either.
Having worked on this for almost 2 years and watching it in action Ive found the biggest bottleneck is when duplicate events (which can then lead to duplicate jobs etc.) are sent by any of the other interconnected systems.
Under normal operation this is fine, we have plenty of slack to accommodate a spike but when it gets really busy it can snowball and lead to backlog of unprocessed events and jobs.
The setup Im using is a standard install of Laravel 4.2 with MySQL (mariadb) a redis backed queue for jobs and events with multiple queues to handle different kinds of events (product stock updates, order dispatch etc).
I was wondering if anyone could suggest a way to prevent laravel from adding events and/or jobs that relate to the same action.
An example of a job would be :
{
"job": "Illuminate\\Queue\\CallQueuedHandler@call",
"data": {
    "commandName": "Staw\\Magento\\Jobs\\AddTrackingNumber",
    "command": "O:40:\"Staw\\Magento\\Jobs\\AddTrackingNumber\":6:{s:17:\"\u0000*\u0000trackingNumber\";s:14:\"[Tracking Number]\";s:14:\"\u0000*\u0000orderNumber\";s:19:\"[Order NUmber]\";s:10:\"connection\";N;s:5:\"queue\";s:8:\"despatch\";s:5:\"delay\";N;s:6:\"\u0000*\u0000job\";N;}"
},
"id": "xGmsi6vo458cYGeJHDfpGCZG8QuAJXB7",
"attempts": 1
}

And an event listener (from event)
{
"job": "Illuminate\\Events\\CallQueuedHandler@call",
"data": {
    "class": "Staw\\Magento\\Listeners\\OrderEventListener",
    "method": "onOrderChangeAlert",
    "data": "a:1:{i:0;O:49:\"Staw\\HiveEvent\\Events\\Order\\OrderChangeAlert\":6:{s:10:\"eventstart\";O:13:\"Carbon\\Carbon\":3:{s:4:\"date\";s:26:\"2017-12-14 11:20:04.000000\";s:13:\"timezone_type\";i:3;s:8:\"timezone\";s:13:\"Europe/London\";}s:8:\"chain_id\";s:13:\"5a325e64510ce\";s:10:\"channel_id\";i:1;s:11:\"channel_key\";N;s:9:\"entity_id\";s:19:\"[Order Number]\";s:5:\"queue\";s:5:\"event\";}}"
},
"id": "0GLUt1O9y6jaZ56yHKA8Vn9si1QNnmlf",
"attempts": 1
}

I'm aware that I can search redis using the predis/predis package but this seems really cumbersome, I've considered making my own queue/stack perhaps on the DB to have more control of things but this seems like a big task and feel I'd be missing out on some of the features I'd get from using the stock Laravel setup.

A: The workaround is, it may involve the application structure changed. You should make a table to log the job information such as the job id, the job name, the job data and etc before push into queue. When the queue worker handling the job, the job handler should look up the table and see if there was duplicating job. If so, terminate the job immediately. It should do the same to the event.
There are numerous implementations:

*

*For Laravel 4, modify the fire event of all job handlers, or inherit an abstract class, that logs and lookups if this tuple($job, $data) already exists. If already exists, terminate the job immediately.

*For laravel 5, there is a handy way to implement. We can use Queues Job Events, Queue::before to log the job. Modify each job handlers to lookup if the duplicating job already exists. If already exists, terminate the job immediately.


text:
Q: Как получить случайное изображение с сайта через Aiogram Много кто ищет я сам искал пока не подсмотрел в документации ...
Если кому надо
случайные фото с bing
@dp.message_handler(commands=['image'])  # Получаем случайное изображение
async def cmd_image(message: types.Message):
    await bot.send_photo(message.chat.id, types.InputFile.from_url('https://bing.ioliu.cn/v1/rand'))


text:
Q: Spring-batch Entity Manager becomes null after init I'm currently implementing a Spring-batch that reads and writes to files BUT also needs to do CRUD operations on a database.
I've tried to simply define an Entity manager in my xml configuration, and use it in my DAO class. However, right after the init, the EntityManager becomes null.
Can anyone help me with this ? (a solution or a link via something usable would be perfect).
My batchContext.xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${batch.datasource.driverClassName}"/>
    <property name="url" value="${batch.datasource.url}"/>
    <property name="username" value="${batch.datasource.username}"/>
    <property name="password" value="${batch.datasource.password}"/>
    <property name="testOnBorrow" value="true"/>
    <property name="testOnReturn" value="true"/>
    <property name="testWhileIdle" value="true"/>
    <property name="timeBetweenEvictionRunsMillis" value="1800000"/>
    <property name="numTestsPerEvictionRun" value="3"/>
    <property name="minEvictableIdleTimeMillis" value="1800000"/>
</bean>

<bean id="entityManagerFactory" name="entTransactionMgr" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <!-- <property name="persistenceXmlLocation" value="classpath:/META-INF/spring/persistence.xml" /> -->
    <property name="persistenceUnitName" value="persistenceUnit"/>
    <property name="packagesToScan" value="${jpa.scan.packages}"/>
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
    </property>
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
    </property>

    <!-- Custom jpaDialect pour le deuxieme batch:job-repository-->
<property name="jpaDialect">
    <bean class="fr.mma.soecm.batchfacade.util.CustomHibernateJpaDialect" />
</property>
    <property name="jpaProperties">
        <props>
            <!-- multiple props here-->
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<!-- mode="aspectj" -->
<tx:annotation-driven  transaction-manager="transactionManager"/>

<batch:job-repository id="jobRepository" data-source="dataSource" transaction-manager="transactionManager"/>

<!-- Jobs held separatelly -->
<import resource="batchContext-job.xml"/>

My DAO
@Repository("batchJobDao")
@Transactional
public class BatchJobDaoImpl implements BatchJobDao{

@PersistenceContext(unitName="persistenceUnit")
@Autowired
private EntityManager entityManager;

//    @PersistenceContext(unitName="persistenceUnit", type=PersistenceContextType.EXTENDED)
//    public void setEntityManager(EntityManager entityManager) {
//        System.out.println("Setting Entity Manager :" + entityManager);
//        this. entityManager = entityManager;
//    }

@PostConstruct
public void init(){
    if (entityManager == null){
        System.out.println(" Entity Manager is null");
    } else {
        System.out.println(" Entity Manager is not null");
        getAllJobExecutions();
    }
}

private static final String RECHERCHER_JOB_EXECUTION = "Select bje from BatchJobExecution bje";

@SuppressWarnings("unchecked")
@Override
@Transactional("transactionManager")
public List<BatchJobExecution> getAllJobExecutions(){

//      EntityManagerFactory emf=Persistence.createEntityManagerFactory("entTransactionMgr");
//      EntityManager em=emf.createEntityManager();

    Query query = entityManager.createQuery(RECHERCHER_JOB_EXECUTION, BatchJobExecution.class);
    List<BatchJobExecution> executions = (List<BatchJobExecution>) query.getResultList();
    System.out.println("EXES : " + executions);
    return executions;
}
}

There is some code commented out because I've tried multiple aproaches (changing the persistence context type, recovering the entity manager "manually", having a persistence.xml file for the entityManager) without succes.
My output when running the job is (without all the extra lines..):
Entity Manager is not null
EXES : [fr.mma.soecm.batchfacade.domain.BatchJobExecution@10e6c33,...]
[BatchService] - Synchronous job launch
[AbstractStep] - Encountered an error executing the step
Caused by: java.lang.NullPointerException

And the null pointer, on debug, is throws by the EntityManager being null when I call the "createQuery" in my DAO.
Thanks for your help.
I'll keep searching on my end.. God Speed!

A: As mentioned in the comment above, my aparent problem was due to the fact that I was trying to call the Service or the DAO in the Constructor of the Step.
After moving the Service call in the "doRead()" method, I could perform all CRUD operations with the EntityManager.
Please let me know if anyone has questions about this/and how to make it work otherwise, as I've not found any explanation on the internet, since I've began searching last week.


text:
Q: Does AsReadOnly make sense if you cast it in an IEnumerable eventually? I saw some code in this project that got my attention.
There is a simple method that calls AsReadOnly on a List. Instead of doing something with the ReadOnlyCollection the method returns it immediately and implicitly casts it into an IEnumerable.
What is the point of using AsReadOnly if you only need an Enumerable?
Would  AsEnumerable be a better option?
private List<PaymentMethod> _paymentMethods = new List<PaymentMethod>();

public IEnumerable<PaymentMethod> PaymentMethods =>
        _paymentMethods.AsReadOnly();

A:
What is the point of using AsReadOnly if you only need an enumerable?

The point is that AsReadOnly ensures that a low-trust hostile or buggy caller cannot cast back to a mutable collection.

Would AsEnumerable be a better option?

No. Try this:
List<int> list = new List<int>{ 10, 20, 30 };
...
IEnumerable<int> seq = list.AsEnumerable();
// Or (IEnumerable<int>)list, or whatever.
...
List<int> list2 = (List<int>)seq;
list2[0] = 40;

And now we have changed list[0].
But AsReadOnly prevents this, as the read-only wrapper cannot be cast back to List<int>.
Remember, AsEnumerable is just a visually nicer way to write a cast, and casts that are reference conversions are reference conversions.  The reference is not changed and it can be changed back to its actual type!
Of course, a hostile or buggy caller that has full trust can arbitrarily break the safety system, because full trust means full trust. A read only collection maintains a reference to the original collection, and that reference can be retrieved via reflection.
Also, remember that read-only means read-only, not unchanging.  A read-only wrapper around a mutable collection can still be observed to change; you just cannot change it via the read-only wrapper.


text:
Q: TreeNode ForeColor change SelectedNode.ForeColor I set the ForeColor on a TreeNode object. And later when I click this nodes the SelectedNode.ForeColor isn't changed until after I release the mouse.
TreeNode.ForeColor = Color.Red;

All TreeNodes with ForeColor == Color.Empty get the proper SelectedNode.ForeColor immediately on mouse click.
If I move selection using the keyboard it work as expected. But not on mouse click. How do I set the ForeColor of nodes to e.g. Color.Black and get the correct SelectedNode.ForeColor on the first mouse click?
I fill the TreeView like this. On all TreeNode object with "color" appended I get the ForeColor (Red) on mouse down.. until I release the left mouse button and get the proper white ForeColor..
private void Form1_Load(object sender, EventArgs e)
{
  for (int i = 0; i < 3; i++)
  {
    TreeNode node = new TreeNode("node_" + i);

    for (int j = 0; j < 3; j++)
    {
      TreeNode childNode = new TreeNode("childNode_" + i + j);

      if (j==0)
      {
        childNode.Text += "color";
        childNode.ForeColor = Color.Red;
      }

      node.Nodes.Add(childNode);
    }
    treeView1.Nodes.Add(node);
  }
}

If I do this..
treeView1.FullRowSelect = false; //if this is true it don't work.. hm!
treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;
treeView1.DrawNode += new DrawTreeNodeEventHandler(treeView1_DrawNode);

void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
  e.DrawDefault = true;
}

It works! Hm. Is this a bug in the default behavior of .NET TreeView?
And of course..
//treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;
//treeView1.DrawNode += new DrawTreeNodeEventHandler(treeView1_DrawNode);

.. now it's back to normal.. And don't work!! Can anyone explain why!?!
Here I get the blue background and Node ForeColor when I click the Left button on a node. Above it waits until I release the mouse button and then paint the selection background- and fore color correct (in my opinion).
Note! If FullRowSelect is true. The DrawNode code above don't work. It will paint the blue background color on all the row except for the node part (it's painted white).

A: set the mouse click event to trigger on mouse down.

A: Have you tried with NodeMouseClick or BeforeSelect events ?
Hope this helps,

A: make HideSelection property of treeview as false.


text:
Q: scalar function for date formatting I have a column which contains time in minutes. What I am looking to do is create a function that returns the following formats:
0 = NULL
>0 and <60 mins = '##min'
between 60 mins & 1440 mins = '##hr,##min'
>1440mins = '##days,##hr,##min'

I've managed to get some of this done using the function below however I'm struggling with how to split days, hours and minutes:
CREATE FUNCTION dbo.udf_Format_Date_Friendly
(
    -- Add the parameters for the function here
    @minutes int
)
RETURNS nvarchar(100)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @Result nvarchar(100)

    -- Add the T-SQL statements to compute the return value here
    SELECT @Result = CASE WHEN @minutes = 0 THEN ''
            WHEN @minutes <= 60 THEN CAST(@minutes AS nvarchar(100)) + ' min'
          WHEN @minutes BETWEEN 60 AND 1440 THEN CAST(CAST(@minutes/60 AS INT) AS nvarchar(100)) + ' hr'
           ELSE NULL end

    -- Return the result of the function
    RETURN @Result

END
GO

A: Try;
CREATE FUNCTION dbo.udf_Format_Date_Friendly (@minutes int)
RETURNS nvarchar(100)
AS
BEGIN
   return CASE
    when @minutes < 60 then cast( @minutes as varchar(10)) + 'min'
    when @minutes < 1400 then cast(@minutes/60 as varchar(10)) + 'hr, ' + cast(@minutes%60 as varchar(10)) + 'min'
    else cast(@minutes/(1400) as varchar(10)) + 'days, ' + cast((@minutes%1400)/60 as varchar(10)) + 'hr, ' + cast(((@minutes%1400)%60) as varchar(10)) + 'min'
    end
end
go

Demo
;with data(d) as (
    select 0 d union all
    select 45 d union all
    select 80 union all
    select 1800
)
select d, dbo.udf_Format_Date_Friendly(d) val
from data

OutPut
0   0min
45  45min
80  1hr, 20min
1800    1days, 6hr, 40min

A: A piece-by-piece approach might be a bit more readable than the current "one expression to do everything" format - the code below will build up the expression one piece at a time, starting with the largest (days) and going down to the minute level.
CREATE FUNCTION dbo.udf_Format_Date_Friendly
(
    -- Add the parameters for the function here
    @minutes int
)
RETURNS nvarchar(100)
AS
BEGIN

    -- Declare the return variable here
    DECLARE @Result nvarchar(10) = ''

    IF @minutes > 1440
      BEGIN
        SET @Result = @Result + CAST(@minutes/1440 AS NVARCHAR(10)) + ' days, '
      END

    IF @minutes > 60
      BEGIN
        SET @Result = @Result + CAST((@minutes%1440) /60 AS NVARCHAR(10)) + ' hr, '
      END

    IF @minutes > 0
      BEGIN
        SET @Result = @Result + CAST(@minutes % 60 AS NVARCHAR(10)) + ' min'
      END

    -- Return the result of the function
    RETURN @Result

END
GO


text:
Q: Unzip an archive in memory in PHP Is possible to unzip an archive in PHP in memory, i.e. without writing to disk? I am using curl to get the .zip file from GitHub, and want to extract it without dealing with disk permissions.
 $zip_file = Curl::get_request("https://github.com/user/repo/archive/v1.0.zip");

A: Have a look at the ZIP functions http://php.net/manual/en/book.zip.php
You can access a ZIP file with the zip_open and zip_read functions. You can also access files in a ZIP with the zip:// protocol
file_get_contents('zip://test.zip#test.txt');


text:
Q: Angular Directive selector by variable attribute value is it possible to create a custom directive based on a variable attribute value?
something like that:
@Directive({
    selector: 'input:[inputmode=numeric], input:[inputmode=decimal]',
})
export class NumericDirective{
// Dom manipulation and huge implementation to let that input accept only numbers and handle spin up and down and format the display value on blur and parse value on focus ..... etc.
}

@Directive({
    selector: 'input:[inputmode=XXX]',
})
export class XXXDirective{
// a total implementation and constructor DI to achieve different job
}

and then in component HTML
<input inputmode="decimal" />
<input inputmode="XXX" />

it works fine, the first input will be handled by NumericDirective and the second will be handled by XXXDirective.
I can achieve my goal like this
<ng-container [ngSwitch] ="currentMode">
<input *ngSwitchCase="numeric" inputmode="numeric" /> // apply different directive based on selector = input[numeric]
<input *ngSwitchCase="decimal" inputmode="decimal" /> // apply different directive based on selector = input[decimal]
<input *ngSwitchCase="XXX" inputmode="XXX" /> // apply different directive based on selector is input[XXX]
....
</ng-container>

my question is there is any way to shorthand this switch to be something like the following line and angular can do the same behavior?
<input [inputmode]="currentMode" />

when I do that:
None of the directives will be applied to the input!
by setting currentMode value in ts code it seems that Angular did not support build directive by dynamic selector attribute value.
I think it creates a directive initially by selector attribute value and since it is not set yet it did not detect the proper directive and just ignore it.
any solution or workaround to achieve this.
the main purpose is to set currentMode at runtime and expects to apply the proper directive behaviors.

A: Ok i have managed to get this working.
First you have to set your directive selector to 'input:[inputMode]'.
Then you have to create an @Input() named inputMode which will listen for the injected value.
@Directive({
  selector: 'input:[inputMode]'
})
export class NumericDirective implements AfterViewInit{

  @Input() inputMode?: string;

  constructor(private elRef: ElementRef<HTMLInputElement>) {}

  ngAfterViewInit(): void { alert(this.inputMode); }

}


text:
Q: Look rotation 2d equivalent Quaternion targetRotation = Quaternion.LookRotation(path.lookPoints[pathIndex] - transform.position);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, turnSpeed);
transform.Translate(Vector3.right * speed * Time.deltaTime,Space.Self)

I want to replace the piece of code above with a 2d equivalent but everything i found on the internet seems to not help me at all. Any help?

A: Once you know your front vector, you can use Quaternion.FromToRotation to get the targetRotation you need to point the front at the next point in your path.
Vector3 frontVector = Vector3.right; // Set your front vector here

Quaternion targetRotation = Quaternion.FromToRotation(frontVector,
        path.lookPoints[pathIndex] - transform.position);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, turnSpeed);
transform.Translate(Vector3.right * speed * Time.deltaTime,Space.Self)


text:
Q: Adding and Removing fields to the user profile Is it possible to add and remove fields from the user profile? For example I want to add a field for LinkedIn profile and remove the Schools field.

A: For adding and removing field to the User Profile you can do that via Central Administration ->Application Management -> Manage Service Application -> and click on the User Profile Service Application -> Manage User properties.
I strongly advise against removing any ootb user properties cause it might break your SharePoint 2010.
Hope this helps.


text:
Q: Why doesn't my local WCF service resolve metadata, when I have configured it for mex? Why doesn't my WCF service provide metadata locally, when I think I have set it up exactly as it is in the test environment?
Environment
My development machine has Windows Server 2003, SP2 with IIS. I have built my service locally and then set up the CSPROJ's directory as a Web site.
IIS Configuration

Web Site    Description MyService
    IP Address  (All Unassigned)
    TCP port    5001
    Enable HTTP Keep-Alives true
HomeDirectory   Directory located on this computer
    Local Path  Project directory with .svc and Web.config
    Application Name    Default Application
    Execute Permissions Scripts and Executables
    Application Pool    Default
ASP.NET Version 2.0.50727
    Virtual Path    MyService
    File location   Path of Web.config

I modeled my IIS settings on a UAT instance that I can get proxy information from.
However when I try to get proxy information on my instance with
C:\Program Files\Microsoft Visual Studio 10.0\VC>svcutil http://localhost:5001/P
mdgService.svc

I get the following error messages.

Error: Cannot obtain Metadata from
  http://localhost:5001/MyService.svc
  ...
Metadata contains a reference that cannot be resolved:
  'http://localhost:5001/MyService.svc'.
There was no endpoint listening at http://localhost:5001/MyService.svc
  ...
      The remote server returned an error: (404) Not Found.
  ...

I cannot browse to the URL.
I have tried suggestions

*

*Verified that metadata behavior is used. (It's identical to working instances.)

*Allowing full control access to C:\Windows\temp to IWAM_, IUSER_, ASPNET    (suggested here: WCF Metadata reference cannot be resolved) did not help.

Here is a look at my Web.config
<configuration>
<!-...-->
<system.serviceModel>
    <services>
      <service behaviorConfiguration="MyService.Service1Behavior" name="MyService.MyService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="MyBasicHttpBinding"
  contract="MyService.MyService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="MyBasicHttpBinding" maxBufferPoolSize="2147483647"  maxReceivedMessageSize="2147483647"
            maxBufferSize="2147483647">
        <readerQuotas maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="2147483647"
            maxNameTableCharCount="2147483647" maxStringContentLength="2147483647" />
        </binding>
      </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyService.Service1Behavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

A: I suspect that the issue is because of the missing base address.
The base address should be either assigned by the iis (if not manually placed in the config), or your visual studio, if you are in the development phase, or your self host where you are expected to provide the baseaddress yourself.
Based on your host method the base address would be resolved.
If you are using a IIS to host it, the path you have hosted should give you a clue.
From your statement, I can understand you are trying to use the similar configuration as another working service. In this case your port number may not be the same (http://localhost:5000).
Try to create a .svc file and use the visual studio's option, "View in browser". This should provide you an idea of the port number being assigned.

A: The problem was that of permissions.

The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'.

Once I granted these permissions to NETWORK SERVICE on the machine, I was able to create proxies and configure that service in my Silverlight client.
I would like to thank razlebe for pointing me in the right direction.


text:
Q: Send data from my C# application to browser My question is.. how am I able to send 2 data parameters to the browser within my C# application? I have a command line application which is a server for my game and on a certain message from the client I have to activate JavaScript on the webpage the client is playing on. What do I use to achieve this?

A: Wow is this a wide-open question. If the request from the browser is for a full HTML page, then embed the call to the JavaScript function within an inline script tag on the page. If the request from the browser will be via ajax, it's totally up to you how you send that data, but JSON is a common mechanism.


text:
Q: Why is only the last element added to list stored/printed in the following program in Kotlin? A Kotlin beginner here. Why is it that only the last element of my list printed when I loop through the list? My code is fairly straightforward.
class Person {

    var personName:String = "Guest"
    var personAge:Int = 20
    var personHobby:String = "Default"
}

fun main()
{
    val obj = Person()
    val listofPeople = mutableListOf<Person>()
    val namesList = arrayOf("ABC", "DEF", "GHI")
    val hobbyList = arrayOf("Swimming", "Reading","Music")

    for (loop in 0..2) {
        obj.personName = namesList[loop%3]
        obj.personHobby = hobbyList[loop%3]
        obj.personAge = loop * 20
        listofPeople.add(obj)
    }
    println("The size of the list is: ${listofPeople.size}")
    println("The details are:")
    for (person in listofPeople)
        println("Name: ${person.personName}, Age: ${person.personAge}, Hobby: ${person.personHobby}")

}

The output after running the above code is:
The size of the list is: 3
The details are:
Name: GHI, Age: 40, Hobby: Music
Name: GHI, Age: 40, Hobby: Music
Name: GHI, Age: 40, Hobby: Music

I am confused about what is happening here, is the obj not added each time the loop runs? Or, adding the object to the list happens after the loop executes and only the last element is added to the list?

A: That's because you reuse Person object within a loop and your result list consists of multiple references to the same object. To make it work you should move val obj = Person() inside the loop:
for (loop in 0..2) {
    val obj = Person()
    obj.personName = namesList[loop%3]
    obj.personHobby = hobbyList[loop%3]
    obj.personAge = loop * 20
    listofPeople.add(obj)
}


text:
Q: Installing PIL to use with Django on Mac OS X I'm really annoyed by installation of PIL (Python Imaging Library) on Mac OS X 10.6. Does anyone have it installed and could post the recipe here? I've tried a lot of them posted here on this site and a lot from google, but always anding with missing some part and can't work normally with PIL...
Thanks in advance.
Ignas

A: Yes, I have issues with PIL on 10.6.6 too, homebrew and easy_install.
The easiest solution for me was to easy_install PIL / pip install PIL, navigate to /Library/Python/2.6/site-packages/, and symlink the PIL-1.1.7-.....egg file to PIL
ln -s PIL-................egg PIL

>>> import PIL
>>> from PIL import Image
# no more problems.

Edit: These days, I try to use Pillow, a library built to help install PIL. Try pip install pillow - can't hurt!

A: It might be easier to pinpoint your issue if you can elaborate on what you tried and what error messages were generated with those attempts. Here's some probable solutions that you may or may not have attempted:
pip install pil

if you dont have pip, try
easy_install pil

Since you're on the Mac, you can also get HomeBrew (a package manager) and then try
brew install pil

or Macports has a PIL package here.
Or build from source?
More importantly, the PIL README states,
*--------------------------------------------------------------------
Additional notes for Mac OS X
On Mac OS X you will usually install additional software such as
libjpeg or freetype with the "fink" tool, and then it ends up in
"/sw".  If you have installed the libraries elsewhere, you may have
to tweak the "setup.py" file before building.*
That could be your issue. Good luck!

A: After fresh OS installation tried these steps:

*

*Installed homebrew

*brew install libjpeg

*brew install pil

*easy_install pil

*cd /Library/Python/2.6/site-packages

*ln -s /usr/local/Cellar/pil/1.1.7/lib/python2.6/site-packages/PIL PIL

After that I was able to load and save jpeg files... I know that this issue has a lot of different solutions and I'm not 100% my way will work for other, but it's worth to try if you just bumping your head in to the wall :)

A: I'm using OS X 10.5.8, gcc 4.2.1, python 2.7.5, libjpegv9 and Pillow 2.1.0 (which is based on PIL).
My problem apparently (but it's just a guess) was caused by architecture incompatibilities of the libjpeg and python (and Pillow) builds.
Building python and libjpeg from source using only 32bit arch solved it. I installed all the other python libraries, Pillow included, just by using
pip install xxxxx

and it worked fine.
Details
First I tried both a dmg from the python.org site and a universal build installed via macports. I had not specified universal when installing but macports installed both i386 and ppc architectures anyways.
That caused me problems because libjpeg compiles only to i386 by default.
To check the build of the binaries, I did:
file /usr/bin/python

/usr/bin/python: Mach-O universal binary with 2 architectures
/usr/bin/python: Mach-O executable i386
/usr/bin/python: Mach-O executable ppc
file /usr/local/lib/libjpeg.dylib

/usr/local/lib/libjpeg.dylib: Mach-O dynamically linked shared library i386
When building PIL (or Pillow), it seemed to use the same build options as python "-gcc i386 -gcc ppc" (which seems logical).
All went well until it built the "_imaging" module. There, it showed a warning that libjpeg.dylib was not of the right architecture but in the end it showed that JPEG was available just the same.

A: Following steps worked for me:
$ brew install pip
$ export ARCHFLAGS="-arch i386 -arch x86_64"
$ pip install pil

A: EDIT: This answer has been getting voted up recently, and I want to modify it to reflect what I'm doing now.
Firstly, I've switched from MacPorts to Homebrew for package management on Mac OS X. Secondly, I've switched from using my package manager to using pip and virtualenvwrapper to manage my Python libraries.
Why I switched:
At first, with just a few Django projects, it was very easy to keep everything up to date using MacPorts. It was also fairly easy to have multiple versions of Python using python_select. What I didn't realize was that I was doing a pretty terrible job of keeping multiple libraries working side-by-side. It became obvious as I upgraded my packages that sometimes I really didn't want a project's Django version to change. After a couple of Django 1.1 projects (now running Django 1.3) started exhibiting weird behaviour (forms failing to submit because of CSRF middleware changes, small differences in Django libraries, admin app assets changing, and so on) it became clear that I should look into a better solution.
What I do now:
On Mac OS X I'm moved over to using pip and virtualenvwrapper. First off, I install virtualenvwrapper:
pip install virtualenvwrapper

This will grab virtualenv and virtualenvwrapper. You then need to add the following to your .bashrc or .profile and source it or open a new shell.
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh # where Homebrew places it
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS='--no-site-packages' # optional

Line 1 sets up the variable workon needs to find its files. Line 2 points to the main shell script (the path here is where Homebrew places the file, it might be different if you're using another package manager). Line 3 is optional, but I really like it: it makes sure that no currently installed libraries in the "main" site-packages repository will leak into your newly created virtual environment. I find this keeps things clean and leads to fewer surprises down the road as things are upgraded.
The next step is to create a new virtual environment:
mkvirtualenv testEnvironmentName

After making the environment, you'll be placed into it. If you kept the --no-site-packages flag, you can type pip freeze to see that your Python library slate is now blank. To escape from the virtual environment, use the deactivate command. To get into your virtualenv again, use workon testEnvironmentName. Note that you can use tab completion on the name of the environment. Also note that typing workon by itself will give you a list of available environments. From here you can pip install any libraries you want, including PIL.
To learn more about virtualenvwrapper, I recommend checking out the documentation.
Here's another great resource which taught me a lot about using virtualenvwrapper (or just view the screencast)

ORIGINAL:
You can also instal PIL using MacPorts. The package name is py-pil. Here's more information on the package. I'm pretty fond of MacPorts over pip, as I find it gives me a bit more configurability when it comes to keeping several versions of python and several libraries installed.
Here are the installation instructions for MacPorts: http://www.macports.org/install.php
See also: What is the most compatible way to install python modules on a Mac?

A: There is a packaging fork of PIL that attempts to make it easier to install and support on many modern platforms, including OS X:

*

*http://pypi.python.org/pypi/Pillow/1.6
You should be able to install it on OS X with pip or easy_install (assuming you have XCode). If you have any trouble, please open a ticket here:

*

*https://github.com/collective/Pillow/issues

A: Hey check out this article, worked wonders for me on Snow Leopard.
I'd also recommend using libjpeg 0.6 instead of 0.7 noted in the article.
Good luck.

A: I have issues installing PIL with brew and easy_install on my Mac too. My solution is to download source code from http://www.pythonware.com/products/pil/, extract the tar ball and use
python setup.py install

to compile and install the package.


text:
Q: incompatible types boolean cannot be converted to Usuarios Estou criando uma função para inserir novos usuarios no banco, porem apresente essa erro: "incompatible types: boolean cannot be converted to Usuarios". Alguém sabe uma forma de solucionar esse caso:
public String InsertUserCpf(@PathParam("nome")String nome,
        @QueryParam("email") String email,
        @QueryParam("senha") String senha,
        @QueryParam("dtnasc") Date dtnasc,
        @QueryParam("fone") String fone,
        @QueryParam("oab") String oab,
        @QueryParam("cep") String cep,
        @QueryParam("cpf") String cpf)
{
    Usuarios u = new Usuarios();
    u.setNome(nome);
    u.setEmail(email);
    u.setSenha(senha);
    u.setDtnasc(dtnasc);
    u.setFone(fone);
    u.setOab(oab);
    u.setCep(cep);
    u.setCpf(cpf);

    UsuarioDAO dao = new UsuarioDAO();
    u = dao.inserir(u);

    Gson g = new Gson();
    return g.toJson(u);
}

UsuarioDao.java:
public boolean inserir(Usuarios usuario)
    {
        String sql = "INSERT INTO usuarios(nome,email,senha,dtnasc,fone,oab,cep,cpf) VALUES(?,?,?,?,?,?,?,?)";
        Boolean retorno = false;
        PreparedStatement pst = Conexao.getPreparedStatement(sql);
        try {
            pst.setString(1, usuario.getNome());
            pst.setString(2, usuario.getEmail());
            pst.setString(3, usuario.getSenha());
            pst.setDate(4, usuario.getDtnasc());
            pst.setString(5, usuario.getFone());
            pst.setString(6, usuario.getOab());
            pst.setString(7, usuario.getCep());
            pst.setString(8, usuario.getCpf());

            if(pst.executeUpdate()>0)
            {
                retorno = true;
            }

        } catch (SQLException ex) {
            Logger.getLogger(UsuarioDAO.class.getName()).log(Level.SEVERE, null, ex);
            retorno = false;
        }

        return retorno;

    }

A: Note que você declara um Usuario u e depois o faz receber o método inserir() que retorna um boolean e não um usuário. Ou seja, são tipos diferentes. Observe:
Usuarios u = new Usuarios(); // aqui você instancia
u.setNome(nome);
u.setEmail(email);
u.setSenha(senha);
u.setDtnasc(dtnasc);
u.setFone(fone);
u.setOab(oab);
u.setCep(cep);
u.setCpf(cpf);

UsuarioDAO dao = new UsuarioDAO();
u = dao.inserir(u); // aqui tenta receber em "u" o retorno de dao.inserir()
                    //que no caso é um boolean (true ou false) e não um Usuario
Gson g = new Gson();
return g.toJson(u);

Pelo que entendi, o método inserir retorna um boolean que refere-se ao sucesso da inserção. Logo sua lógica ficaria algo assim:
boolean sucesso = false;
sucesso = dao.inserir(u);

if (sucesso) { // sucesso ao inserir
    Gson g = new Gson();
    return g.toJson(u);
    //...
}

Porém, como o @Victor Stafusa mencionou, utilizar boolean para retornar erros é uma má prática de programação, ao invés disso utilize Exceptions


text:
Q: PySpark ReduceByKey I have been trying to make it work for a while, but failed every time. I have 2 files. One has a list of names:
Name1
Name2
Name3
Name4

The other is list of values associated with names for each day in the year over several years:
['0.1,0.2,0.3,0.4',
 '0.5,0.6,0.7,0.8',
 '10,1000,0.2,5000'
  ...]

The goal is to have the output like:
Name1: [0.1,0.5,10]
Name2: [0.2,0.6,1000]
Name3:[0.3,0.7,0.2]
Name4:[0.4,0.8,5000]

And then plot histogram for each. I wrote a mapper that creates a list of tuples that produces the following output (this is an RDD object):
[[('Name1', [0.1]),('Name2', [0,2]),('Name3', [0.3]),('Name4', [0.4])],
[('Name1', [0.5]),('Name2', [0,6]),('Name3', [0.7]),('Name4', [0.8])],
[('Name1', [10]),('Name2', [1000]),('Name3', [0.8]),('Name4', [5000])]]

Now I need to concatenate all values for each name in a single list, but each map by key, value that I attempted returns a wrong result.

A: You can simply loop through each and create a dictionary from it using dict.setdefault() . Example -
>>> ll = [[('Name1', [0.1]),('Name2', [0,2]),('Name3', [0.3]),('Name4', [0.4])],
... [('Name1', [0.5]),('Name2', [0,6]),('Name3', [0.7]),('Name4', [0.8])],
... [('Name1', [10]),('Name2', [1000]),('Name3', [0.8]),('Name4', [5000])]]
>>> d = {}
>>> for i in ll:
...     for tup in i:
...             d.setdefault(tup[0],[]).extend(tup[1])
...
>>> pprint.pprint(d)
{'Name1': [0.1, 0.5, 10],
 'Name2': [0, 2, 0, 6, 1000],
 'Name3': [0.3, 0.7, 0.8],
 'Name4': [0.4, 0.8, 5000]}

For Pyspark RDD Object, try a simple reduce function such as -
func = lambda x,y: x+y

Then send this in to reduceByKey method -
object.reduceByKey(func)

Per comments, actually the OP has a list of RDD Objects (not a single RDD Objects) , in that case you can convert the RDD objects to a list by calling .collect() and then do the logic , and then you can decide whether you want the resultant as a python dictionary or an RDD object, if you want first. You can call dict.items() to get the key-value pairs and call sc.parrallelize . Example -
d = {}
for i in ll:
    c = i.collect()
    for tup in i:
            d.setdefault(tup[0],[]).extend(tup[1])

rddobj = sc.parallelize(d.items())


text:
Q: ImageMapster - how to highlight specific area ( one or two ) on load I'm new to ImageMapster, I'm trying to figure out how to highlight one or two of areas onload. How do you do that?
Using the states as reference:
<map id="MapUSA" name="MapUSA">
  <area href="#" state="NH" full="New Hampshire" shape="rect" coords="102,36,149,83">
  <area href="#" state="VT" full="Vermont" shape="rect" coords="150,34,181,85">
</map>

How can I make state NH selected on load and if I have staticState: false would it be affected?