问:
Connect to Kubernetes mongo db in different namespace
Can anyone point out how to connect to the mongo db instance using mongo client using either command line client or from .net core programs with connection strings?

We have created a sample cluster in digitalocean with a namespace, let's say mongodatabase.

We installed the mongo statefulset with 3 replicas. We are able to successfully connect with the below command
 kubectl --kubeconfig=configfile.yaml -n mongodatabase exec -ti mongo-0 mongo
But when we connect from a different namespace or from default namespace with the pod names in the below format, it doesn't work.

```<code> kubectl --kubeconfig=configfile.yaml  exec -ti mongo-0.mongo.mongodatabase.cluster.svc.local mongo
</code>```

where mongo-0.mongo.mongodatabase.cluster.svc.local is in pod-0.service_name.namespace.cluster.svc.local (also tried pod-0.statfulset_name.namespace.cluster.svc.local and pod-0.service_name.statefulsetname.namespace.cluster.svc.local) etc.,

Can any one help with the correct dns name/connection string to be used while connecting with mongo client in command line and also from the programs like java/.net core etc.,?

Also should we use kubernetes deployment instead of statefulsets here?

答:
I think you are looking for this DNS for Services and Pods.

You can have a fully qualified domain name (FQDN) for a Services or for a Pod.

Also please have a look at this kubernetes: Service located in another namespace, as I think it will provide you with answer on how to access it from different namespace.

An example would look like this:

```<code>apiVersion: v1
kind: Service
metadata:
  name: default-subdomain
spec:
  selector:
    name: busybox
  clusterIP: None
  ports:
  - name: foo # Actually, no port is needed.
    port: 1234
    targetPort: 1234
---
apiVersion: v1
kind: Pod
metadata:
  name: busybox1
  labels:
    name: busybox
spec:
  hostname: busybox-1
  subdomain: default-subdomain
  containers:
  - image: busybox:1.28
    command:
      - sleep
      - "3600"
    name: busybox
---
apiVersion: v1
kind: Pod
metadata:
  name: busybox2
  labels:
    name: busybox
spec:
  hostname: busybox-2
  subdomain: default-subdomain
  containers:
  - image: busybox:1.28
    command:
      - sleep
      - "3600"
    name: busybox
</code>```

If there exists a headless service in the same namespace as the pod and with the same name as the subdomain, the cluster’s KubeDNS Server also returns an A record for the Pod’s fully qualified hostname. For example, given a Pod with the hostname set to “busybox-1” and the subdomain set to “default-subdomain”, and a headless Service named “default-subdomain” in the same namespace, the pod will see its own FQDN as “busybox-1.default-subdomain.my-namespace.svc.cluster.local”. DNS serves an A record at that name, pointing to the Pod’s IP. Both pods “busybox1” and “busybox2” can have their distinct A records.

The Endpoints object can specify the  hostname  for any endpoint addresses, along with its IP.

Note:  Because A records are not created for Pod names,  hostname  is required for the Pod’s A record to be created. A Pod with no  hostname  but with  subdomain  will only create the A record for the headless service (default-subdomain.my-namespace.svc.cluster.local), pointing to the Pod’s IP address. Also, Pod needs to become ready in order to have a record unless  publishNotReadyAddresses=True  is set on the Service.

Body:
Can anyone point out how to connect to the mongo db instance using mongo client using either command line client or from .net core programs with connection strings?

We have created a sample cluster in digitalocean with a namespace, let's say mongodatabase.

We installed the mongo statefulset with 3 replicas. We are able to successfully connect with the below command
 kubectl --kubeconfig=configfile.yaml -n mongodatabase exec -ti mongo-0 mongo
But when we connect from a different namespace or from default namespace with the pod names in the below format, it doesn't work.

 kubectl --kubeconfig=configfile.yaml  exec -ti mongo-0.mongo.mongodatabase.cluster.svc.local mongo

where mongo-0.mongo.mongodatabase.cluster.svc.local is in pod-0.service_name.namespace.cluster.svc.local (also tried pod-0.statfulset_name.namespace.cluster.svc.local and pod-0.service_name.statefulsetname.namespace.cluster.svc.local) etc.,

Can any one help with the correct dns name/connection string to be used while connecting with mongo client in command line and also from the programs like java/.net core etc.,?

Also should we use kubernetes deployment instead of statefulsets here?

Body:
I think you are looking for this DNS for Services and Pods.

You can have a fully qualified domain name (FQDN) for a Services or for a Pod.

Also please have a look at this kubernetes: Service located in another namespace, as I think it will provide you with answer on how to access it from different namespace.

An example would look like this:

apiVersion: v1
kind: Service
metadata:
  name: default-subdomain
spec:
  selector:
    name: busybox
  clusterIP: None
  ports:
  - name: foo # Actually, no port is needed.
    port: 1234
    targetPort: 1234
---
apiVersion: v1
kind: Pod
metadata:
  name: busybox1
  labels:
    name: busybox
spec:
  hostname: busybox-1
  subdomain: default-subdomain
  containers:
  - image: busybox:1.28
    command:
      - sleep
      - "3600"
    name: busybox
---
apiVersion: v1
kind: Pod
metadata:
  name: busybox2
  labels:
    name: busybox
spec:
  hostname: busybox-2
  subdomain: default-subdomain
  containers:
  - image: busybox:1.28
    command:
      - sleep
      - "3600"
    name: busybox

If there exists a headless service in the same namespace as the pod and with the same name as the subdomain, the cluster’s KubeDNS Server also returns an A record for the Pod’s fully qualified hostname. For example, given a Pod with the hostname set to “busybox-1” and the subdomain set to “default-subdomain”, and a headless Service named “default-subdomain” in the same namespace, the pod will see its own FQDN as “busybox-1.default-subdomain.my-namespace.svc.cluster.local”. DNS serves an A record at that name, pointing to the Pod’s IP. Both pods “busybox1” and “busybox2” can have their distinct A records.

The Endpoints object can specify the  hostname  for any endpoint addresses, along with its IP.

Note:  Because A records are not created for Pod names,  hostname  is required for the Pod’s A record to be created. A Pod with no  hostname  but with  subdomain  will only create the A record for the headless service (default-subdomain.my-namespace.svc.cluster.local), pointing to the Pod’s IP address. Also, Pod needs to become ready in order to have a record unless  publishNotReadyAddresses=True  is set on the Service.


来源: stackexchange

问:
I would like to check if an incoming file (the imported file) is a .csv or .xls or .xlxs in python
My problem statement is to find if the imported file is a CSV or EXCEL file in pandas. The input will be given from the command line as sys.argv[1] where sys.argv[1] is 'D:/Users/abc'

When the path along with file name is given in command line as a parameter, I have to check inside my script if sys.argv[1] is a CSV or EXCEL file

eg: python myscript.py D:/Users/abc [abc is the file name]

This should say if the file is CSV or EXCEL

I tried referring the answers from below link, but could not find exactly what I am looking for!

How to check the uploaded file is csv or xls in python?

Any help would be highly appreciated

答:
Since you give the filename "abc" as an example, I assume that you cannot decide on the file type based on extension. There are ways to look for the magic string in the header of the file, but that would be hard to get foolproof.

However, it is easier to ask for forgiveness than permission. So why don't you just assume it is an excel file, try to read it with pd.read_excel and if that fails, read it with pd.read_csv:

```<code>import pandas as pd
import sys
try:
    df = pd.read_excel(sys.argv[1])
    filetype = 'EXCEL'
except Exception:
    df = pd.read_csv(sys.argv[1])
    filetype = 'CSV'
print(filetype)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Since you give the filename "abc" as an example, I assume that you cannot decide on the file type based on extension. There are ways to look for the magic string in the header of the file, but that would be hard to get foolproof.

However, it is easier to ask for forgiveness than permission. So why don't you just assume it is an excel file, try to read it with pd.read_excel and if that fails, read it with pd.read_csv:

import pandas as pd
import sys
try:
    df = pd.read_excel(sys.argv[1])
    filetype = 'EXCEL'
except Exception:
    df = pd.read_csv(sys.argv[1])
    filetype = 'CSV'
print(filetype)


问:
Regular expression to replace content between parentheses ()
I tried this code:

```<code>string.replaceAll("\\(.*?)","");
</code>```

But it returns null. What am I missing?

答: Try string.replaceAll("\\(.*?\\)","").

ContentLicense: CC BY-SA 3.0

Body:
I tried this code:

string.replaceAll("\\(.*?)","");

But it returns null. What am I missing?

Body: Try string.replaceAll("\\(.*?\\)","").


问:
How to check whether response JSON of an API is empty or has an error?
I am new to reactjs and I am stuck in one problem. I am calling an Update API which is of PUT type. I use the fetch function to call the API in reactjs and I check the response of the API. If Response is 200 OK, then I return the response.json() and then check whether the json object has error in it or not. If it has error, then I print the error else I update it.

But when there is no Error present in the response, then I get a syntax-error in return response.json() statement and If there is actually a Error present in the response then there is no syntax-error shown. So is there a method to check whether the response is empty or not so that accordingly I can return response.json().

I have tried by putting a condition as if(response.json() != '') but it shows error in response.json() statement.

```<code>fetch( API + name , {
      method: 'PUT',
      headers: {
         'Accept' : 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      body: JSON.stringify({
        name: name,
        description: updateDesc
      }),
    }).then(function(response) {
      if(response.status == '200'){
        flag=true;
        return response.json();
      }
      else {
        flag=false
      }
    })
    .then(json => {
    if(flag)
    {
        if(json.Error != "")
        {
          that.createNotification('error','update');
        }
        else {
          this.createNotification('success','update');
        }
    }
});
</code>```

Unhandled Rejection (SyntaxError): Unexpected end of JSON input

答:
There are multiple issues with this imo:

The callback should be refactored to avoid the use of the flag variable. The code in the function supplied to handlers like then, catch and finally of promises is executed asynchronously. Therefore you cannot be sure / (should not assume) when this value will be assigned and in which state your context is at that time.

.then(json => { if there is an error this will actually use the promise returned by fetch aka response and not the promise returned by response.json() (Currently return response.json() is only executed in the success case)

Note that this happens (currently works in the error case) because you can chain promises. You can find more info and examples about this here

I would refactor the handling of the fetch promise like this:

You can shorten the following example and avoid assigning the promises, but it makes the example better readable

More information about the response object

const fetchPromise = fetch(url, { method: 'PUT', ...yourParams });

fetchPromise.then(response => {
  if (response.ok()){
    //Your request was successful
    const jsonPromise = response.json();
    jsonPromise.then(data => {
      console.log("Successful request, parsed json body", data);
    }).catch(error => {
      //error handling for json parsing errors (empty body etc.)
      console.log("Successful request, Could not parse body as json", error);
    })
  } else {
    //Your request was not successful
    /*
     You can check the body of the response here anyways. Maybe your api does return a json error?
    */
  }
}).catch(error => {
  //error handling for fetch errors
}))

```

Body:
I am new to reactjs and I am stuck in one problem. I am calling an Update API which is of PUT type. I use the fetch function to call the API in reactjs and I check the response of the API. If Response is 200 OK, then I return the response.json() and then check whether the json object has error in it or not. If it has error, then I print the error else I update it.

But when there is no Error present in the response, then I get a syntax-error in return response.json() statement and If there is actually a Error present in the response then there is no syntax-error shown. So is there a method to check whether the response is empty or not so that accordingly I can return response.json().

I have tried by putting a condition as if(response.json() != '') but it shows error in response.json() statement.

fetch( API + name , {
      method: 'PUT',
      headers: {
         'Accept' : 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      body: JSON.stringify({
        name: name,
        description: updateDesc
      }),
    }).then(function(response) {
      if(response.status == '200'){
        flag=true;
        return response.json();
      }
      else {
        flag=false
      }
    })
    .then(json => {
    if(flag)
    {
        if(json.Error != "")
        {
          that.createNotification('error','update');
        }
        else {
          this.createNotification('success','update');
        }
    }
});

Unhandled Rejection (SyntaxError): Unexpected end of JSON input


问:
RecyclerView generic adapter
Trying to create a generic adapter for the RecyclerView.

Already explored other solutions:
RecyclerView generic adapter with DataBinding

Add click listener to Generic RecyclerView Adapter

https://github.com/ravirupareliya/Recyclerview-Generic-Adapter/blob/master/app/src/main/java/com/rrr/genericrecyclerview/adapter/RecyclerAdapter.java

However want to implement it in a bit different way.

Here is how my adapter looks like:

```<code>public abstract class GenericAdapter<T> extends RecyclerView.Adapter<BaseHolder<T>> {

    private OnRecyclerItemClickListener mListener;
    private List<T> mItems;
    private final LayoutInflater mLayoutInflater;

    public GenericAdapter(Context context) {
        mLayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mItems = Collections.emptyList();
    }

    @Override
    public BaseHolder<T> onCreateViewHolder(ViewGroup parent, int viewType) {
        // assume that viewType is a resource id returned by getItemViewType
        // also other solutions are welcome
        View view = mLayoutInflater.inflate(viewType, parent, false);

        // TODO: how to create the view holder ??
    }

    @Override
    public void onBindViewHolder(BaseHolder<T> holder, int position) {
        T item = mItems.get(position);
        holder.onBind(item, mListener);
    }

    @Override
    public int getItemCount() {
        return mItems != null ? mItems.size() : 0;
    }

    public void setItems(List<T> items) {
        mItems = items;
        notifyDataSetChanged();
    }

    public void setItemClickListener(OnRecyclerItemClickListener listener) {
        mListener = listener;
    }
}
</code>```

This is a base view holder from which I want to extend all other holders:

```<code>public abstract class BaseHolder<T> extends RecyclerView.ViewHolder {

    public BaseHolder(View itemView) {
        super(itemView);
    }

    public abstract void onBind(T item, OnRecyclerItemClickListener listener);
}
</code>```

The problem is in onCreateViewHolder method.

How do I create the view holder?

Should I somehow implement abstract BaseHolder or should I somehow change the adapter class declaration extends i.e. instead BaseHolder here RecyclerView.Adapter> should be some generic implementation of BaseHolder? I tried > but it doesn't work

Thanks in advance for any piece of advice

答:
P.S. It's been a long time, but if someone is interested,

at the time I solved it and published in a Generic RecyclerView Adapter library.

It finally makes it quite easy to create adapters.

I am still using it in multiple production projects.

EDIT:
So the adapter finally looks like:

```<code>public abstract class GenericRecyclerViewAdapter<T, L extends BaseRecyclerListener, VH extends BaseViewHolder<T, L>> extends RecyclerView.Adapter<VH> {

    @Override
    public abstract VH onCreateViewHolder(ViewGroup parent, int viewType);

    // ...
}
</code>```

Thus, ViewHolder creation is delegated to the adapter implementation, i.e.:

```<code>public class SimpleAdapter extends GenericRecyclerViewAdapter<User, OnRecyclerItemClickListener, UserViewHolder> {

    // ...

    @Override
    public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // or return here any specific ViewHolder according to the viewType
        return new UserViewHolder(inflate(R.layout.item_user, parent), getListener());
    }
}
</code>```

And the ViewHolder is a:

```<code>public abstract class BaseViewHolder<T, L extends BaseRecyclerListener> extends RecyclerView.ViewHolder {
   // ...
}
</code>```

Title: RecyclerView generic adapter

Body:
Trying to create a generic adapter for the RecyclerView.

Already explored other solutions:
RecyclerView generic adapter with DataBinding

Add click listener to Generic RecyclerView Adapter

https://github.com/ravirupareliya/Recyclerview-Generic-Adapter/blob/master/app/src/main/java/com/rrr/genericrecyclerview/adapter/RecyclerAdapter.java

However want to implement it in a bit different way.

Here is how my adapter looks like:

public abstract class GenericAdapter<T> extends RecyclerView.Adapter<BaseHolder<T>> {

    private OnRecyclerItemClickListener mListener;
    private List<T> mItems;
    private final LayoutInflater mLayoutInflater;

    public GenericAdapter(Context context) {
        mLayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mItems = Collections.emptyList();
    }

    @Override
    public BaseHolder<T> onCreateViewHolder(ViewGroup parent, int viewType) {
        // assume that viewType is a resource id returned by getItemViewType
        // also other solutions are welcome
        View view = mLayoutInflater.inflate(viewType, parent, false);

        // TODO: how to create the view holder ??
    }

    @Override
    public void onBindViewHolder(BaseHolder<T> holder, int position) {
        T item = mItems.get(position);
        holder.onBind(item, mListener);
    }

    @Override
    public int getItemCount() {
        return mItems != null ? mItems.size() : 0;
    }

    public void setItems(List<T> items) {
        mItems = items;
        notifyDataSetChanged();
    }

    public void setItemClickListener(OnRecyclerItemClickListener listener) {
        mListener = listener;
    }
}

This is a base view holder from which I want to extend all other holders:

public abstract class BaseHolder<T> extends RecyclerView.ViewHolder {

    public BaseHolder(View itemView) {
        super(itemView);
    }

    public abstract void onBind(T item, OnRecyclerItemClickListener listener);
}

The problem is in onCreateViewHolder method.

How do I create the view holder?

Should I somehow implement abstract BaseHolder or should I somehow change the adapter class declaration extends i.e. instead BaseHolder here RecyclerView.Adapter> should be some generic implementation of BaseHolder? I tried > but it doesn't work

Thanks in advance for any piece of advice

Body:
P.S. It's been a long time, but if someone is interested,

at the time I solved it and published in a Generic RecyclerView Adapter library.

It finally makes it quite easy to create adapters.

I am still using it in multiple production projects.

EDIT:
So the adapter finally looks like:

public abstract class GenericRecyclerViewAdapter<T, L extends BaseRecyclerListener, VH extends BaseViewHolder<T, L>> extends RecyclerView.Adapter<VH> {

    @Override
    public abstract VH onCreateViewHolder(ViewGroup parent, int viewType);

    // ...
}

Thus, ViewHolder creation is delegated to the adapter implementation, i.e.:

public class SimpleAdapter extends GenericRecyclerViewAdapter<User, OnRecyclerItemClickListener, UserViewHolder> {

    // ...

    @Override
    public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // or return here any specific ViewHolder according to the viewType
        return new UserViewHolder(inflate(R.layout.item_user, parent), getListener());
    }
}

And the ViewHolder is a:

public abstract class BaseViewHolder<T, L extends BaseRecyclerListener> extends RecyclerView.ViewHolder {
   // ...
}


问:
Fetch previous rows based on if condition and Shift function - Python dataframe
I have data as shown below. I would like to select rows based on two conditions.

1) rows that start with digits (1,2,3 etc)

2) previous row of the records that satisfy 1st condition

Please find the how the input data looks like

Please find how I expect the output to be

I tried using the shift(-1) function but it seems to be throwing error. I am sure I messed up with the logic/syntax. Please find the code below that I tried

```<code> # i get the index of all records that start with number.
 s=df1.loc[df1['VARIABLE'].str.contains('^\d')==True].index
 # now I need to get the previous record of each group but this is
                                                         #incorrect
 df1.loc[((df1['VARIABLE'].shift(-1).str.contains('^\d')==False) &
 (df1['VARIABLE'].str.contains('^\d')==True))].index
</code>```

答:
Use:</p>

```<code>df1 = pd.DataFrame({'VARIABLE':['studyid',np.nan,'age_interview','Gender','1.Male',
                                '2.Female',np.nan, 'dob', 'eth',
                                'Ethnicity','1.Chinese','2.Indian','3.Malay']})

#first remove missing rows by column VARIABLE
df1 = df1.dropna(subset=['VARIABLE'])
#test startinf numbers
s = (df1['VARIABLE'].str.contains('^\d'))
#chain shifted values by | for OR
mask  = s | s.shift(-1)
#filtering by boolean indexing
df1 = df1[mask]
print (df1)
     VARIABLE
3      Gender
4      1.Male
5    2.Female
9   Ethnicity
10  1.Chinese
11   2.Indian
12    3.Malay
</code>```

Body:
I have data as shown below. I would like to select rows based on two conditions.

1) rows that start with digits (1,2,3 etc)

2) previous row of the records that satisfy 1st condition

Please find the how the input data looks like

Please find how I expect the output to be

I tried using the shift(-1) function but it seems to be throwing error. I am sure I messed up with the logic/syntax. Please find the code below that I tried

 # i get the index of all records that start with number.
 s=df1.loc[df1['VARIABLE'].str.contains('^\d')==True].index
 # now I need to get the previous record of each group but this is
                                                         #incorrect
 df1.loc[((df1['VARIABLE'].shift(-1).str.contains('^\d')==False) &
 (df1['VARIABLE'].str.contains('^\d')==True))].index

Body:
Use:

df1 = pd.DataFrame({'VARIABLE':['studyid',np.nan,'age_interview','Gender','1.Male',
                                '2.Female',np.nan, 'dob', 'eth',
                                'Ethnicity','1.Chinese','2.Indian','3.Malay']})

#first remove missing rows by column VARIABLE
df1 = df1.dropna(subset=['VARIABLE'])
#test startinf numbers
s = (df1['VARIABLE'].str.contains('^\d'))
#chain shifted values by | for OR
mask  = s | s.shift(-1)
#filtering by boolean indexing
df1 = df1[mask]
print (df1)
     VARIABLE
3      Gender
4      1.Male
5    2.Female
9   Ethnicity
10  1.Chinese
11   2.Indian
12    3.Malay


问:
Using Ant with Flex
I'm having problems setting up Ant to use with Flex. I install it fine but I get this error when I try and check the install: Unable to locate tools.jar.

From what I've read, I just need to point JAVA_HOME to the directory that contains the jdk. Unfortunately, I'm not sure I know which jre I'm using in Eclipse and also, I do a search for tools.jar on my machine and it's not there???

I have a C:\Program Files\Java directory and there is this in there:

j2re1.4.2_05

jdk1.6.0_03

jre1.6.0.23

In Eclipse --> Windows --> Preferences --Java --> Installed JREs, it's pointing to here:

eclipse-host-distro, C:\Program Files\Adobe\Adobe Flash Builder Plug-in\eclipse-host-distro

Am I not working with a full JRE?

Any tips are greatly appreciated. Thank you in advance.

答: Just specify your JAVA_HOME path as C:\Program Files\Java\jdk1.6.0_03\ and everything should be good as long as the JDK was properly installed.  If that doesn't work, get the latest and try again.

Title: Using Ant with Flex


问:
bootstrap accordion - don't collapse if clicking on open panel
I have set up bootstrap to hide currently open panels when opening a new panel using:

```<code>$('.collapse').on('show.bs.collapse', function () {
   $('.in').collapse('hide');
});
</code>```

I would like to extend this so that nothing happens if you click on a currently open panel, i.e. the open panel should stay open when clicking on it. It should only collapse when clicking on other collapsed panels.

I tried it like this, but it doesn't work:

```<code>$('.collapse').on('show.bs.collapse', function () {
  $('.in').not(this).collapse('hide');
});
</code>```

Is this possible somehow?

JSFiddle

答:
According to @Sammy answer - for the Bootstrap 4.x you have to change

```<code>    if ($(target).hasClass('in'))
</code>```

to

```<code>    if ($(target).hasClass('show'))
</code>```

Body:
I have set up bootstrap to hide currently open panels when opening a new panel using:

$('.collapse').on('show.bs.collapse', function () {
   $('.in').collapse('hide');
});

I would like to extend this so that nothing happens if you click on a currently open panel, i.e. the open panel should stay open when clicking on it. It should only collapse when clicking on other collapsed panels.

I tried it like this, but it doesn't work:

$('.collapse').on('show.bs.collapse', function () {
  $('.in').not(this).collapse('hide');
});

Is this possible somehow?

JSFiddle

Body:
According to @Sammy answer - for the Bootstrap 4.x you have to change

    if ($(target).hasClass('in'))

to

    if ($(target).hasClass('show'))


问:
Why different string is matching to the pattern?
I am using java 1.7.

I expect:

```<code>Pattern ddmmyyyyPattern = Pattern.compile("(\\d{1,2}[- /.]\\d{1,2}[- /.]\\d{4})");
</code>```

should match strings with atleast 2 occurences of seperators -/.
But, the following are matching

```<code>07 2.3180, 45 3.3183, 19 4.3183, 77 5.3025, 25 6.3023.
</code>```

Also, 9507 2.31 is matching to

```<code>Pattern yyyymmddPattern = Pattern.compile("(\\d{4}[- /.]\\d{1,2}[- /.]\\d{1,2})");
</code>```

Please help me in rectifying the pattern!

答:
Try this pattern:

```<code>\d{1,2}([-\/.])\d{1,2}([-\/.])\d{4}
</code>```

Of course the blank space should be removed from the regex, and the character "/" needs to have a backslash before it in order it to be recognized.

Body:
I am using java 1.7.

I expect:

Pattern ddmmyyyyPattern = Pattern.compile("(\\d{1,2}[- /.]\\d{1,2}[- /.]\\d{4})");

should match strings with atleast 2 occurences of seperators -/.
But, the following are matching

07 2.3180, 45 3.3183, 19 4.3183, 77 5.3025, 25 6.3023.

Also, 9507 2.31 is matching to

Pattern yyyymmddPattern = Pattern.compile("(\\d{4}[- /.]\\d{1,2}[- /.]\\d{1,2})");

Please help me in rectifying the pattern!

Body:
Try this pattern:

\d{1,2}([-\/.])\d{1,2}([-\/.])\d{4}

Of course the blank space should be removed from the regex, and the character "/" needs to have a backslash before it in order it to be recognized.


问:
How to Reference Model in Reportlab
My goal is to create a pdf report using ReportLab where some of the text is dynamic based on a primary key.

I have a dropdown listing each primary key currently created in the program (#1 - 5 at present) and as more "shipments" are created, the primary key is added to the dropdown.

When I select the primary key and then click the "submit" button I would like for my pdf to generate where the dynamic text is related specifically to that pk.

Below is the view for the PDF I currently have with static text (pulled from a source on reportlab) where I would like values such as "JOHN DOE" and "Name goes here" to be replaced dynamically based on the pk selected.

views.py

```<code>def write_pdf_view(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="mypdf.pdf"'

    buffer = BytesIO()
    p = canvas.Canvas(buffer)

    # Start writing the PDF here
    p.setLineWidth(.3)
    p.setFont('Helvetica', 12)

    p.drawString(30,750,'Name goes here')
    p.drawString(30,735,'OF ACME INDUSTRIES')
    p.drawString(500,750,"12/12/2010")
    p.line(480,747,580,747)

    p.drawString(275,725,'AMOUNT OWED:')
    p.drawString(500,725,"$1,000.00")
    p.line(378,723,580,723)

    p.drawString(30,703,'RECEIVED BY:')
    p.line(120,700,580,700)
    p.drawString(120,703,"JOHN DOE")
    # End writing

    p.showPage()
    p.save()

    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)

    return response
</code>```

Here is the dropdown being created

ViEWS.py

```<code>def reference_view(request):
    query_results = Orders.objects.all()
    reference_list = DropDownMenuReferences()

    context = {
        'query_results': query_results,
        'reference_list': reference_list
    }
    return render(request, 'proforma_select.html', context)
</code>```

Forms.py

```<code>class DropDownMenuReferences(forms.Form):
    Reference_IDs = forms.ModelChoiceField(queryset=Orders.objects.values_list('reference', flat=True).distinct(),
    empty_label=None)
</code>```

TEMPLATE

```<code>{% extends 'base.html' %}

{% block body %}

<div class="container">

  <br>

  <form method=POST action="">
    {{ reference_list }}

    <button type="submit" class="btn btn-primary" name="button">Add Order</button>
  </form>

</div>

{% endblock %}
</code>```

I am presently completely unsure how to approach this problem.  I have the dropdown and I understand how to create a pdf I just don't know where to tie them together.

答:
You can include the related primary key of the desired person in the form the form area of your program. When the user clicks Submit button, that primary key will included in your request object.

Then in your write_pdf_view function, you can pull the related person from the database by such as:

```<code>def write_pdf_view(request):

    if request.method == 'POST':
        primary_key = request.POST.get('primary_key')
        person = models.Person.objects.get(pk=primary_key)

        ...

        p.drawString(120, 703, person.full_name)

    ...

    return response

</code>```

Title: How to Reference Model in Reportlab

Body:
My goal is to create a pdf report using ReportLab where some of the text is dynamic based on a primary key.

I have a dropdown listing each primary key currently created in the program (#1 - 5 at present) and as more "shipments" are created, the primary key is added to the dropdown.

When I select the primary key and then click the "submit" button I would like for my pdf to generate where the dynamic text is related specifically to that pk.

Below is the view for the PDF I currently have with static text (pulled from a source on reportlab) where I would like values such as "JOHN DOE" and "Name goes here" to be replaced dynamically based on the pk selected.

views.py

def write_pdf_view(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'inline; filename="mypdf.pdf"'

    buffer = BytesIO()
    p = canvas.Canvas(buffer)

    # Start writing the PDF here
    p.setLineWidth(.3)
    p.setFont('Helvetica', 12)

    p.drawString(30,750,'Name goes here')
    p.drawString(30,735,'OF ACME INDUSTRIES')
    p.drawString(500,750,"12/12/2010")
    p.line(480,747,580,747)

    p.drawString(275,725,'AMOUNT OWED:')
    p.drawString(500,725,"$1,000.00")
    p.line(378,723,580,723)

    p.drawString(30,703,'RECEIVED BY:')
    p.line(120,700,580,700)
    p.drawString(120,703,"JOHN DOE")
    # End writing

    p.showPage()
    p.save()

    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)

    return response

Here is the dropdown being created

ViEWS.py

def reference_view(request):
    query_results = Orders.objects.all()
    reference_list = DropDownMenuReferences()

    context = {
        'query_results': query_results,
        'reference_list': reference_list
    }
    return render(request, 'proforma_select.html', context)

Forms.py

class DropDownMenuReferences(forms.Form):
    Reference_IDs = forms.ModelChoiceField(queryset=Orders.objects.values_list('reference', flat=True).distinct(),
    empty_label=None)

TEMPLATE

{% extends 'base.html' %}

{% block body %}

  <form method=POST action="">
    {{ reference_list }}

    <button type="submit" class="btn btn-primary" name="button">Add Order</button>
  </form>

{% endblock %}

I am presently completely unsure how to approach this problem.  I have the dropdown and I understand how to create a pdf I just don't know where to tie them together.

Body:
You can include the related primary key of the desired person in the form the form area of your program. When the user clicks Submit button, that primary key will included in your request object.

Then in your write_pdf_view function, you can pull the related person from the database by such as:

def write_pdf_view(request):

    if request.method == 'POST':
        primary_key = request.POST.get('primary_key')
        person = models.Person.objects.get(pk=primary_key)

        ...

        p.drawString(120, 703, person.full_name)

    ...

    return response


问:
In using JWKS with Auth0 what is the audience and issuer if I'm using localhost?
I've implemented JWT in my Node Koa app:

```<code>import Router from 'koa-router-middleware';
import { ApplicationState, ApplicationContext } from './types';
import configure from './configure';
import swagger from './swagger';
import healthcheck from './healthcheck';
import helloworld from './helloworld';
const jwt = require('jsonwebtoken');
// import * as jwt from 'jsonwebtoken'; << TODO
import * as koajwt from 'koa-jwt';

export default new Router<ApplicationState, ApplicationContext>()
  .use(configure)
  .use('/openapi.json', swagger)
  .use('/', helloworld)
  .use('/healthcheck', healthcheck)
  .use('/token', (ctx) => {
    const token = jwt.sign({ data: 'tokenData' }, 'secret');
    ctx.response.body = token;
  })
  // Secure routes
  .use(koajwt({ secret: 'secret' }))
  .use('/secure', helloworld)
  .middleware();
</code>```

This works ^ and now I'm trying to get it working with Auth0 so I looked into JWKS and here's what I have:

```<code>import Router from 'koa-router-middleware';
import { ApplicationState, ApplicationContext } from './types';
import configure from './configure';
import swagger from './swagger';
import healthcheck from './healthcheck';
import helloworld from './helloworld';
// const jsonwebtoken = require('jsonwebtoken');
// import * as jwt from 'jsonwebtoken'; << TODO
import * as jwt from 'koa-jwt';
const jwksRsa = require('jwks-rsa');

const jwksHost = 'omitted'
const audience = 'http://localhost:8080'
const issuer = '??'

export default new Router<ApplicationState, ApplicationContext>()
  .use(configure)
  .use('/openapi.json', swagger)
  .use('/', helloworld)
  .use('/healthcheck', healthcheck)
  .use(jwt({
    secret: jwksRsa.koaJwtSecret({
      cache: true,
      rateLimit: true,
      jwksRequestsPerMinute: 2,
      jwksUri: `${jwksHost}/.well-known/jwks.json`
    }),
    audience,
    issuer,
    algorithms: [ 'RS256' ]
  }))

  // Secure routes. Anything below this comment needs a jwt token
  .use('/secure', helloworld)
  .middleware();
</code>```

First question: Can I do this from localhost or do I have to upload my code for it to work?

Second question: I am using the JWKS endpoint that Auth0 assigned to me when I created an account, am I right to assume that there's only one JWKS endpoint per account even if that account has multiple APIs? (on this website it says that there's one per tenant which I assume means account but I want to confirm)

Third question: Aside from the audience and issuer, does this code look right or is it missing something?

答:
Look at the answer to this

Seems like it should be:

```<code>audience: 'http://localhost:3000', // With your port
issuer: `https://${process.env.AUTH0_DOMAIN}/` // Your Auth0 domain
</code>```

Body:
I've implemented JWT in my Node Koa app:

import Router from 'koa-router-middleware';
import { ApplicationState, ApplicationContext } from './types';
import configure from './configure';
import swagger from './swagger';
import healthcheck from './healthcheck';
import helloworld from './helloworld';
const jwt = require('jsonwebtoken');
// import * as jwt from 'jsonwebtoken'; << TODO
import * as koajwt from 'koa-jwt';

export default new Router<ApplicationState, ApplicationContext>()
  .use(configure)
  .use('/openapi.json', swagger)
  .use('/', helloworld)
  .use('/healthcheck', healthcheck)
  .use('/token', (ctx) => {
    const token = jwt.sign({ data: 'tokenData' }, 'secret');
    ctx.response.body = token;
  })
  // Secure routes
  .use(koajwt({ secret: 'secret' }))
  .use('/secure', helloworld)
  .middleware();

This works ^ and now I'm trying to get it working with Auth0 so I looked into JWKS and here's what I have:

import Router from 'koa-router-middleware';
import { ApplicationState, ApplicationContext } from './types';
import configure from './configure';
import swagger from './swagger';
import healthcheck from './healthcheck';
import helloworld from './helloworld';
// const jsonwebtoken = require('jsonwebtoken');
// import * as jwt from 'jsonwebtoken'; << TODO
import * as jwt from 'koa-jwt';
const jwksRsa = require('jwks-rsa');

const jwksHost = 'omitted'
const audience = 'http://localhost:8080'
const issuer = '??'

export default new Router<ApplicationState, ApplicationContext>()
  .use(configure)
  .use('/openapi.json', swagger)
  .use('/', helloworld)
  .use('/healthcheck', healthcheck)
  .use(jwt({
    secret: jwksRsa.koaJwtSecret({
      cache: true,
      rateLimit: true,
      jwksRequestsPerMinute: 2,
      jwksUri: `${jwksHost}/.well-known/jwks.json`
    }),
    audience,
    issuer,
    algorithms: [ 'RS256' ]
  }))

  // Secure routes. Anything below this comment needs a jwt token
  .use('/secure', helloworld)
  .middleware();

First question: Can I do this from localhost or do I have to upload my code for it to work?

Second question: I am using the JWKS endpoint that Auth0 assigned to me when I created an account, am I right to assume that there's only one JWKS endpoint per account even if that account has multiple APIs? (on this website it says that there's one per tenant which I assume means account but I want to confirm)

Third question: Aside from the audience and issuer, does this code look right or is it missing something?

Body:
Look at the answer to this

Seems like it should be:

audience: 'http://localhost:3000', // With your port
issuer: `https://${process.env.AUTH0_DOMAIN}/` // Your Auth0 domain


问:
Ruby SSO, CAS, oauth, userstore. What options do I have?
Q: How would you create a SSO? What would you do about authentication (separate app or same as sso) and user store?

Background info:

We have 40+ php apps, java apps and
  Ruby apps.

Currently, we have a custom
  SSO+authentication solution. It's an
  app written in php that is now used as
  SSO, while supporting
  email/username/phone-number + password
  as authentication. It works, but was
  built for a few apps only, not
  originally meant to be the SSO -
  solution. It doesn't have a usable view, every app create their own login/register forms and use the API. They share context and we'd like a more universal design.

Now we know want to support Oauth and
  openid solutions, as facebook connect,
  google and more, (or do we really?), in addition to
  existing authentications. We can
  expand existing php-solution, but we
  are considering alternatives.

If you were to do all this in Ruby, what would you do?

Some additional info:

All users exist in SSO, today.

The company does aquire other companies/systems at times, having their own users. Would you migrate or create some kind of mapper?

Customers in a Microsoft CRM, but I consider this unrelated. Or do I?

I've shallowly looked at RubyCAS and ClassyCAS, and don't know if they are suitable. Is CAS the way to go?

Would you keep going with php? What would you use?

As you see, I have a lot of questions. What would you suggest?

答:
I a previous job we used Jasig CAS for SSO (several apps in Java and Python). After getting over some quirks in the configuration and my dislike of all things Java, it actually worked pretty well. At the time I found the wiki to be a valuable resource, but things might have changed in the last year.

Authentication was handled via a separate app (custom) using an OpenLDAP directory that was preinitialized with a script that got user info out of an AD server.

Regarding the actual server you might actually want to use the Jasig one, IIRC it's the reference implementation and is easy to customize via a Maven overlay.


问:
Read only indicator in Shiny?
I have an existing Shiny script with standard widgets from the Shiny library. Now I wish to add something to show temperature on a graphical scale?  This would be a read-only value, so it wouldn't make sense to use a slider unless the slider can be locked and only changed programatically. Is that possible? If not, what are other suggestions?

To clarify:

Is it possible to have a Shiny slider as read only. The user can not slide it but it can be programmatically changed. Here is a Shiny slider:

```<code>library(shiny)

ui <- fluidPage(

  sliderInput("aa", "Temp",
              min = -20, max = 20,
              value = 10, step = 10)
)

server <- function(input, output) { }

shinyApp(ui, server)
</code>```

I'm not familiar with Shiny Dashboard but I saw taskItem. Can these be "dropped in" and used with a normal Shiny app that uses fluidPage, sidebarPanel, mainPanel? How does one remove the bullet point and the percentage? Here is an example of a taskItem.

```<code>library(shiny)
library(shinydashboard)

ui <- dashboardPage(

  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    taskItem(value = temp <- 89, color = "red",
                                      "Temp"
                             ))
)

server <- function(input, output) { }

  temp <- 89

shinyApp(ui, server)
</code>```

答:
You can use updateSliderInput to achieve such an behaviour. Couple this with shinyjs::disabled and you get what you want. I would however look for a less hackish solution:

```<code>library(shiny)
library(shinyjs)

ui <- fluidPage(
  ## add style to remove the opacity effect of disabled elements
  tags$head(
    tags$style(HTML("
                    .irs-disabled {
                       opacity: 1
                    }")
              )
  ),
  useShinyjs(),
  disabled(sliderInput("aa", "Temp",
                       min = -20, max = 20,
                       value = 10, step = 10)),
  actionButton("Change", "Change")
)

server <- function(input, output, session) {
  observeEvent(input$Change, {
    new_temp <- sample(seq(-20, 20, 10), 1)
    updateSliderInput(session, "aa", value = new_temp)
  })
}

shinyApp(ui, server)
</code>```

Title: Read only indicator in Shiny?

Body:
I have an existing Shiny script with standard widgets from the Shiny library. Now I wish to add something to show temperature on a graphical scale?  This would be a read-only value, so it wouldn't make sense to use a slider unless the slider can be locked and only changed programatically. Is that possible? If not, what are other suggestions?

To clarify:

Is it possible to have a Shiny slider as read only. The user can not slide it but it can be programmatically changed. Here is a Shiny slider:

library(shiny)

ui <- fluidPage(

  sliderInput("aa", "Temp",
              min = -20, max = 20,
              value = 10, step = 10)
)

server <- function(input, output) { }

shinyApp(ui, server)

I'm not familiar with Shiny Dashboard but I saw taskItem. Can these be "dropped in" and used with a normal Shiny app that uses fluidPage, sidebarPanel, mainPanel? How does one remove the bullet point and the percentage? Here is an example of a taskItem.

library(shiny)
library(shinydashboard)

ui <- dashboardPage(

  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    taskItem(value = temp <- 89, color = "red",
                                      "Temp"
                             ))
)

server <- function(input, output) { }

  temp <- 89

shinyApp(ui, server)

Body:
You can use updateSliderInput to achieve such an behaviour. Couple this with shinyjs::disabled and you get what you want. I would however look for a less hackish solution:

library(shiny)
library(shinyjs)

ui <- fluidPage(
  ## add style to remove the opacity effect of disabled elements
  tags$head(
    tags$style(HTML("
                    .irs-disabled {
                       opacity: 1
                    }")
              )
  ),
  useShinyjs(),
  disabled(sliderInput("aa", "Temp",
                       min = -20, max = 20,
                       value = 10, step = 10)),
  actionButton("Change", "Change")
)

server <- function(input, output, session) {
  observeEvent(input$Change, {
    new_temp <- sample(seq(-20, 20, 10), 1)
    updateSliderInput(session, "aa", value = new_temp)
  })
}

shinyApp(ui, server)


问:
Call Method that inside Another Component - React Js
i need to know how to fetch state of component from other component by calling the seconed component method inside of first component ?
like :

class General extends Component {

  state = {
    input:"
   }

   fetchState() {
    return this.state;
   }

  handleChange () {
    this.setState({[e.target.name]: e.traget.value});
  }

  render() {
    return <input type="text" name="input" onChange={this.handleChange.bind(this}>
  }

}

class Car extends Component {

  render() {
    console.log( General.fetchState() );
    return null;
  }

}```

i know i can use static method but i don't have access to this keyword.

答:
In your current code, the only way to do it is to use new General.

```<code>console.log(new General().fetchState());
</code>```

Body:
i need to know how to fetch state of component from other component by calling the seconed component method inside of first component ?
like :

class General extends Component {

  state = {
    input:"
   }

   fetchState() {
    return this.state;
   }

  handleChange () {
    this.setState({[e.target.name]: e.traget.value});
  }

  render() {
    return <input type="text" name="input" onChange={this.handleChange.bind(this}>
  }

}

class Car extends Component {

  render() {
    console.log( General.fetchState() );
    return null;
  }

}

i know i can use static method but i don't have access to this keyword.

Body:
In your current code, the only way to do it is to use new General.

console.log(new General().fetchState());


问:
How to execute one function whether it normal or carried and yield the same result?
What would be the body of a the multiply function that if executed in both ways below would give the same result. So either calling multiply(2,4) or multiply(2)(4) would output 8?

答:
You can check if second arg is passed or not.

function multiply(a,b){
  if(b === undefined){
    return function(b){
      return a * b;
    }
  }
  return a * b
}

console.log(multiply(2,4))
console.log(multiply(2)(4))```


问:
change :hover to click/tap function on mobile/touch devices not working
So, I'm trying to change the :hover function to a click function using Modernizr's no-touch/touch class for specific elements (captions) on a page. And in theory, this should work, but somehow it's only clickable once on a mobile/touch device, meaning that if I click/tap it again, it won't "un-hover". I can "un-hover" by tapping at another element on the page, but would very much like the caption to disappear when
 clicked/tapped again.

If I change the js so that it's the no-touch devices having to click, it works fine. What am I missing here?

Fiddle: https://fiddle.jshell.net/bh3aLkcL/3/

I'm afraid my js skills are quite poor to say the least (read: non-existing), and I've been using a snippet from another post: Change hover interaction to click for touch screen devices

The rest works, so it's just that one thing. Any help is greatly appreciated!

Javascript:

```<code>// For hovering becoming click via Modernizr
//$('body').hasClass('no-touch') ? event = 'mouseenter mouseleave' : event = 'click';
!$('body').hasClass('no-touch') ? event = 'mouseenter mouseleave' : event = 'click';

$('.design-section figure').on(event, function () {
$(this).toggleClass('open');
});
</code>```

HTML:

```<code><section id="work" class="content-section text-left" data-offset="100px">
<div class="design-section">
    <div class="container">
        <div class="col-lg-8 col-lg-offset-2">
            <img src="http://cutepuppyclub.com/wp-content/uploads/2015/05/White-Cute-Puppy-.jpg" width="100%" class="img-responsive" alt="Playing the dilemma game">
            <figure>
                <figcaption>
                    <p>test text</p>
                </figcaption>
            </figure>
       </div>
    </div>
</div>
</section>
</code>```

CSS:

```<code>figure {
    padding: 0;
    margin-top: 0;
    position: relative;
    display: block;
    overflow: hidden;
}

figcaption {
    position: absolute;
    background: rgba(0,0,0,.3);
    color: #fff;
}

figure.open figcaption {
    -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
    filter: alpha(opacity=100);
    opacity: 1;
}

.design-section figcaption {
  opacity: 0;
  bottom: -30%;
  left: 0;
  -webkit-transition: all 0.6s ease;
  -moz-transition:    all 0.6s ease;
  -o-transition:      all 0.6s ease;
  padding: 0;
  width:100%;
  display:block;
}

.design-section figure {
    height:120px;
    margin-top:-120px;
    z-index:1;
}

.design-section img {
    padding-top:0;
    margin-top:14px;
    z-index:0;
}

.design-section figcaption p {
    margin:0;
    padding: 1.5% 2.5%;
    font-size:15px;
}

.design-section figure.open figcaption{
    bottom: 0;
}
</code>```

P.S. I'm using Bootstrap, but that shouldn't have anything to say in this matter.

答:
you can specify multiple events as a parameter so just include the touchstart to add an action when a user clicks on mobile.</p>

```<code>$('.design-section figure').on('mouseover mouseout touchstart', function () {
    $(this).toggleClass('open');
});
</code>```

Body:
So, I'm trying to change the :hover function to a click function using Modernizr's no-touch/touch class for specific elements (captions) on a page. And in theory, this should work, but somehow it's only clickable once on a mobile/touch device, meaning that if I click/tap it again, it won't "un-hover". I can "un-hover" by tapping at another element on the page, but would very much like the caption to disappear when
 clicked/tapped again.

If I change the js so that it's the no-touch devices having to click, it works fine. What am I missing here?

Fiddle: https://fiddle.jshell.net/bh3aLkcL/3/

I'm afraid my js skills are quite poor to say the least (read: non-existing), and I've been using a snippet from another post: Change hover interaction to click for touch screen devices

The rest works, so it's just that one thing. Any help is greatly appreciated!

Javascript:

// For hovering becoming click via Modernizr
//$('body').hasClass('no-touch') ? event = 'mouseenter mouseleave' : event = 'click';
!$('body').hasClass('no-touch') ? event = 'mouseenter mouseleave' : event = 'click';

$('.design-section figure').on(event, function () {
$(this).toggleClass('open');
});

HTML:

test text

CSS:

figure {
    padding: 0;
    margin-top: 0;
    position: relative;
    display: block;
    overflow: hidden;
}

figcaption {
    position: absolute;
    background: rgba(0,0,0,.3);
    color: #fff;
}

figure.open figcaption {
    -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
    filter: alpha(opacity=100);
    opacity: 1;
}

.design-section figcaption {
  opacity: 0;
  bottom: -30%;
  left: 0;
  -webkit-transition: all 0.6s ease;
  -moz-transition:    all 0.6s ease;
  -o-transition:      all 0.6s ease;
  padding: 0;
  width:100%;
  display:block;
}

.design-section figure {
    height:120px;
    margin-top:-120px;
    z-index:1;
}

.design-section img {
    padding-top:0;
    margin-top:14px;
    z-index:0;
}

.design-section figcaption p {
    margin:0;
    padding: 1.5% 2.5%;
    font-size:15px;
}

.design-section figure.open figcaption{
    bottom: 0;
}

P.S. I'm using Bootstrap, but that shouldn't have anything to say in this matter.

Body:
you can specify multiple events as a parameter so just include the touchstart to add an action when a user clicks on mobile.

$('.design-section figure').on('mouseover mouseout touchstart', function () {
    $(this).toggleClass('open');
});


问:
Same Adapter obj shown multiple times, but why?
I Made a custom Listview and Listviewadapter. Somehow the same Data is shown multiple times in my Listview, but I don't know why.

I tried to debug it, but it didn't seem to be double added.

As you can see, I controll the input of the adapter, by using .contains, but this isn't helping.

BrodcastReceiver

```<code>   private BroadcastReceiver BR_BT_Device= new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
           String action_BR_BT_Device= intent.getAction();

            if(action_BR_BT_Device.equals(BluetoothDevice.ACTION_FOUND))
            {
                BluetoothDevice device =
      intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (!device.equals(null)) {
                    String sDevice_Address = device.getAddress();
                    if (!(sDevice_Address == null)) {
                        if (device.getName() == null){
                            mDeviceName = "Kein Name";
                        }
                        else {
                            mDeviceName = device.getName();
                        }
                        cBT_DeviceList mDevice = new
       cBT_DeviceList(mDeviceName, sDevice_Address);

                        if (!(cBT_popup.mBTDevice.contains(mDevice))) {
                            cBT_popup.mBTDevice.add(mDevice);

       cBT_popup.cBTDeviceListAdapter.notifyDataSetChanged();
                        }
                    }
                }
                Log.d("Resiver", "onReceive: "+device.getAddress());
            }
        }
    };
</code>```

Activity for Listview obj

```<code>    public class cBT_popup extends MainActivity {
        public static ArrayList<cBT_DeviceList> mBTDevice = new
                ArrayList<cBT_DeviceList>();
        public ListView lv_devices;
        public static cBT_DeviceList_Adapter cBTDeviceListAdapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.bt_popup);
            lv_devices = findViewById(R.id.lv_devices);
            cBTDeviceListAdapter = new cBT_DeviceList_Adapter(this,
                    R.layout.lrv_bt_listview, mBTDevice);
            lv_devices.setAdapter(cBTDeviceListAdapter);
            lv_devices.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }
</code>```

If you need more Information let me know.

If this is important: to highlight a selected item isn't possible, don't know why at the moment.

IntentFilter for Broadcast

´´´
    IntentFilter BT_Device_filter = new

    IntentFilter(BluetoothDevice.ACTION_FOUND);

´´´

答:
May be onRecieve is called multiple times for same BluetoothDevice.

Try this... Replace

```<code>if (!(cBT_popup.mBTDevice.contains(mDevice))) {
        cBT_popup.mBTDevice.add(mDevice);

        cBT_popup.cBTDeviceListAdapter.notifyDataSetChanged();
    }
</code>```

with

```<code>boolean alreadyExist = false;
    for(cBT_DeviceList mBTDeviceObj : mBTDevice){
        if(mDevice.getName().equals(mBTDeviceObj.getName())){
            alreadyExist = true;
        }
    }
    if (!alreadyExist) {
        cBT_popup.mBTDevice.add(mDevice);
        cBT_popup.cBTDeviceListAdapter.notifyDataSetChanged();
    }
</code>```

Body:
I Made a custom Listview and Listviewadapter. Somehow the same Data is shown multiple times in my Listview, but I don't know why.

I tried to debug it, but it didn't seem to be double added.

As you can see, I controll the input of the adapter, by using .contains, but this isn't helping.

BrodcastReceiver

   private BroadcastReceiver BR_BT_Device= new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
           String action_BR_BT_Device= intent.getAction();

            if(action_BR_BT_Device.equals(BluetoothDevice.ACTION_FOUND))
            {
                BluetoothDevice device =
      intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (!device.equals(null)) {
                    String sDevice_Address = device.getAddress();
                    if (!(sDevice_Address == null)) {
                        if (device.getName() == null){
                            mDeviceName = "Kein Name";
                        }
                        else {
                            mDeviceName = device.getName();
                        }
                        cBT_DeviceList mDevice = new
       cBT_DeviceList(mDeviceName, sDevice_Address);

                        if (!(cBT_popup.mBTDevice.contains(mDevice))) {
                            cBT_popup.mBTDevice.add(mDevice);

       cBT_popup.cBTDeviceListAdapter.notifyDataSetChanged();
                        }
                    }
                }
                Log.d("Resiver", "onReceive: "+device.getAddress());
            }
        }
    };

Activity for Listview obj

    public class cBT_popup extends MainActivity {
        public static ArrayList<cBT_DeviceList> mBTDevice = new
                ArrayList<cBT_DeviceList>();
        public ListView lv_devices;
        public static cBT_DeviceList_Adapter cBTDeviceListAdapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.bt_popup);
            lv_devices = findViewById(R.id.lv_devices);
            cBTDeviceListAdapter = new cBT_DeviceList_Adapter(this,
                    R.layout.lrv_bt_listview, mBTDevice);
            lv_devices.setAdapter(cBTDeviceListAdapter);
            lv_devices.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }

If you need more Information let me know.

If this is important: to highlight a selected item isn't possible, don't know why at the moment.

IntentFilter for Broadcast

´´´
    IntentFilter BT_Device_filter = new

    IntentFilter(BluetoothDevice.ACTION_FOUND);

´´´

Body:
May be onRecieve is called multiple times for same BluetoothDevice.

Try this... Replace

if (!(cBT_popup.mBTDevice.contains(mDevice))) {
        cBT_popup.mBTDevice.add(mDevice);

        cBT_popup.cBTDeviceListAdapter.notifyDataSetChanged();
    }

with

boolean alreadyExist = false;
    for(cBT_DeviceList mBTDeviceObj : mBTDevice){
        if(mDevice.getName().equals(mBTDeviceObj.getName())){
            alreadyExist = true;
        }
    }
    if (!alreadyExist) {
        cBT_popup.mBTDevice.add(mDevice);
        cBT_popup.cBTDeviceListAdapter.notifyDataSetChanged();
    }


问:
How to input multiple variables of different type in one line? For example -> string string int string int
Using a hash table implemented in Java and I need to take 5 input values, 3 of which are String and 2 are Integers. The user must be able to write all input values IN ONE LINE. I tried many different ways mostly using arrays and i couldn't find the right answer online. If anyone could help provide a sample code or idea i would be thankful :)

```<code>Scanner input = new Scanner(System.in);
        Scanner input1 = new Scanner(System.in);

        System.out.println("Enter number of people:");
        int n = input1.nextInt();

        HTable table = new HTable(100);

        String a[] = new String[5];
        for(int i=0; i<n; i++)
        {
            a = input.nextLine().split(" ");
            table.Insert(a[0], a[1], Integer.parseInt(a[2]), a[3], Integer.parseInt(a[4]));
        }
</code>```

This is the most recent example i tried but it keeps taking inputs and the FOR() loop doesn't seem to end.

答:
You Can try like this : </p>

```<code>public class Name{
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println( "Enter Your Input ");
    while (scanner.hasNext())
    {
        if (scanner.hasNextInt()) {
            System.out.println(" Your Value (Int) : " + scanner.nextInt());
        } else if (scanner.hasNextFloat()) {
            System.out.println(" Your Value (Float) " + scanner.nextFloat());
        }
        else {
            System.out.println( " String Value(String) " + scanner.next());
        }
    }
}
}
</code>```

Body:
Using a hash table implemented in Java and I need to take 5 input values, 3 of which are String and 2 are Integers. The user must be able to write all input values IN ONE LINE. I tried many different ways mostly using arrays and i couldn't find the right answer online. If anyone could help provide a sample code or idea i would be thankful :)

Scanner input = new Scanner(System.in);
        Scanner input1 = new Scanner(System.in);

        System.out.println("Enter number of people:");
        int n = input1.nextInt();

        HTable table = new HTable(100);

        String a[] = new String[5];
        for(int i=0; i<n; i++)
        {
            a = input.nextLine().split(" ");
            table.Insert(a[0], a[1], Integer.parseInt(a[2]), a[3], Integer.parseInt(a[4]));
        }

This is the most recent example i tried but it keeps taking inputs and the FOR() loop doesn't seem to end.

Body:
You Can try like this :

public class Name{
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println( "Enter Your Input ");
    while (scanner.hasNext())
    {
        if (scanner.hasNextInt()) {
            System.out.println(" Your Value (Int) : " + scanner.nextInt());
        } else if (scanner.hasNextFloat()) {
            System.out.println(" Your Value (Float) " + scanner.nextFloat());
        }
        else {
            System.out.println( " String Value(String) " + scanner.next());
        }
    }
}
}


问:
How to delete edittext dynamically everytime I click a button
I'm trying to add a new food with some add ons, basically everytime the add field button is press it will create two edittext which is the name and price of the add on, there will be a scenario whereby users wants to delete the edittext name and price. I've successfully created two edittexts also setting them with the IDs that i'm giving them in integer. But I'm having problem with deleting the two edittext with a button whenever i click the delete field button.

```<code>
// Add On
        addOnLayout.removeAllViews();
        addFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddOnCounters++;

                etFoodName = new EditText(addfoodAddOn.this);
                etFoodName.setId(ETFoodID);

                etFoodName.setHint("Enter your AddOn Name");

                etPrice = new EditText(addfoodAddOn.this);
                etPrice.setId(ETPriceID);
                etPrice.setHint("Enter your AddOn Price");

                Log.d("-------","-------------------what is edittext name id " + ETFoodID);
                Log.d("-------","-------------------what is edittext price id " + ETPriceID);

                ETFoodID++;
                ETPriceID++;

                addOnLayout.addView(etFoodName);
                addOnLayout.addView(etPrice);

            }
        });

        removeFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AddOnCounters>=1 && ETFoodID > 0 && ETPriceID > 10){

                    addOnLayout.removeViewAt(ETFoodID);
                    addOnLayout.removeViewAt(ETPriceID);
                    ETFoodID--;
                    ETPriceID--;

                }
            }
        });
</code>```

I'm expecting the result to be whenever i click the delete field button, it will delete the very bottom last two edittexts which is the name and price.

答:
After the button click just do this: </p>

```<code>addFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              etPrice.setText("")
              etFoodName.setText("");
     }
}
</code>```

Body:
I'm trying to add a new food with some add ons, basically everytime the add field button is press it will create two edittext which is the name and price of the add on, there will be a scenario whereby users wants to delete the edittext name and price. I've successfully created two edittexts also setting them with the IDs that i'm giving them in integer. But I'm having problem with deleting the two edittext with a button whenever i click the delete field button.

// Add On
        addOnLayout.removeAllViews();
        addFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddOnCounters++;

                etFoodName = new EditText(addfoodAddOn.this);
                etFoodName.setId(ETFoodID);

                etFoodName.setHint("Enter your AddOn Name");

                etPrice = new EditText(addfoodAddOn.this);
                etPrice.setId(ETPriceID);
                etPrice.setHint("Enter your AddOn Price");

                Log.d("-------","-------------------what is edittext name id " + ETFoodID);
                Log.d("-------","-------------------what is edittext price id " + ETPriceID);

                ETFoodID++;
                ETPriceID++;

                addOnLayout.addView(etFoodName);
                addOnLayout.addView(etPrice);

            }
        });

        removeFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(AddOnCounters>=1 && ETFoodID > 0 && ETPriceID > 10){

                    addOnLayout.removeViewAt(ETFoodID);
                    addOnLayout.removeViewAt(ETPriceID);
                    ETFoodID--;
                    ETPriceID--;

                }
            }
        });

I'm expecting the result to be whenever i click the delete field button, it will delete the very bottom last two edittexts which is the name and price.

Body:
After the button click just do this:

addFields.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              etPrice.setText("")
              etFoodName.setText("");
     }
}


问:
Display all item which is created in 2013
I have a table Policy, and I want to display all policy which is created in 2013.

```<code>select DAT_IZD from AUTO.KPOL   WHERE DAT_IZD='2013'
</code>```

But the problem is that this format of date can not be represent like this.
Any idea how to figure out this ?

答: You could extract year value (something like WHERE YEAR(DAT_IZD) = 2013) from date before you compare.</p>

Body:
I have a table Policy, and I want to display all policy which is created in 2013.

select DAT_IZD from AUTO.KPOL   WHERE DAT_IZD='2013'

But the problem is that this format of date can not be represent like this.
Any idea how to figure out this ?


问:
how return to top button works
I have looked around many places  return to top  button .when i click on that that takes me to top of the page.

some time some links taking me to particular place how does this works

is this html tack ticks or javascript..can i do this without page loading ?

答:
```
<a href="#top">return to top</a>
```

The #top bit refers to the id of an element that resides at the top of your page. In most cases this will be something like #header where you have:

```
<div id="header"></div>
```

at the top of the page. I'd suggest not using name as I believe the attribute is now deprecated.

Of course, to make it a little more fancy you could use something like:
http://webdesignerwall.com/tutorials/animated-scroll-to-top

Title: how return to top button works

Body:
<a href="#top">return to top</a>

The #top bit refers to the id of an element that resides at the top of your page. In most cases this will be something like #header where you have:

<div id="header"></div>

at the top of the page. I'd suggest not using name as I believe the attribute is now deprecated.

Of course, to make it a little more fancy you could use something like:
http://webdesignerwall.com/tutorials/animated-scroll-to-top


问:
How do I parse Array within Array
I am trying to parse information that is inside an Array. The array comes from an RSS feed that I have converted into a json. The array is:

```<code><channel>
<item>
    <title> Title A </title>
    <description> Description A </description>
    <stuff url="google.com" type="search engine">
</item>

<item>
    <title> Title B </title>
    <description> Description B </description>
    <stuff url="yahoo.com" type="old stuff">
</item>
....

</channel>
</code>```

I am parsing using something like:

```<code>$newsoutput = json_decode(json_encode($the_RSS_Link), TRUE);

foreach ($newsoutput['channel']['item'] as $item) {
   echo $item['title'];
   echo "<br>";
   echo $item['description'];
   echo "<br>";
   echo $item['stuff']['url'];
   echo "<br>";
}
</code>```

I can get both "title" and "description"; but I cannot extract the "url" values inside "stuff". I have tried various combinations without luck

Please advise.

Thank you,

H.

答:
If the RSS content is like the one you posted on the example you should parse RSS feed using XML parser instead of using json_* functions.

Here are some simple examples using SimpleXML https://www.php.net/manual/en/simplexml.examples-basic.php

Title: How do I parse Array within Array

Body:
I am trying to parse information that is inside an Array. The array comes from an RSS feed that I have converted into a json. The array is:

<channel>
<item>
    <title> Title A </title>
    <description> Description A </description>
    <stuff url="google.com" type="search engine">
</item>

<item>
    <title> Title B </title>
    <description> Description B </description>
    <stuff url="yahoo.com" type="old stuff">
</item>
....

</channel>

I am parsing using something like:

$newsoutput = json_decode(json_encode($the_RSS_Link), TRUE);

foreach ($newsoutput['channel']['item'] as $item) {
   echo $item['title'];
   echo "
";
   echo $item['description'];
   echo "
";
   echo $item['stuff']['url'];
   echo "
";
}

I can get both "title" and "description"; but I cannot extract the "url" values inside "stuff". I have tried various combinations without luck

Please advise.

Thank you,

H.


问:
Spring Boot - Firebase Admin SDK - Notification
I was trying to initialize the Admin SDK, but facing 400 bad request in service account initialization. It was working perfectly in my development windows environment, but when I deploy the same in linux, am facing this issue.

```<code>        SpringApplication.run(OrderApplication.class, args);

        FileInputStream serviceAccount = new FileInputStream(GlobalValue.serviceAccount);

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .setDatabaseUrl("https://xxxxxxx.firebaseio.com").build();

        FirebaseApp.initializeApp(options);

    }
</code>```

I am reading the file path from property file.

service.account=/home/service-account.json

I was trying to send push notification, am facing issue at that time.

```<code>
        try {
            MulticastMessage multicastMessage = MulticastMessage.builder().addAllTokens(lDeviceTokens)
                    .setNotification(new Notification(title, message)).build();

            BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(multicastMessage);
            // See the BatchResponse reference documentation // for the contents of
            // response.
            System.out.println(response.getSuccessCount() + " messages were sent successfully");
        } catch (FirebaseMessagingException e) {
            e.printStackTrace();
            System.out.println(e.getLocalizedMessage());
        }
    }
</code>```

Trace

```<code>. java: 141 S)
at org . apache . tomcat . util .neC . Socket ProcessorBase . run (Socket ProcessorBas
e . java : 49)
at java . concurrent . ThreadPooIExecuCor . runWorker (ThreadPooIExecuC01 .
java : 1149)
at java . concurrent . ThreadPooIExecucor$Worker . run (ThreadPooIExecuC01
. java : 624)
at org . apache . ComcaC . util . Chreads . TaskThread$WrappingRunnabIe . run (TaskTh
read . java : 61)
at java. lang . Thread. run (Thread. java : 7 48)
Caused by: java.io. IOExcepCion: Error getting access token for service account :
400 Bad Request
"error" • "invalid grant"
"error description" • "Invalid JWT: Token must be a short—lived token (60 minut
es) and in a reasonable timeframe. Check Y2ur iat and exp values and use a clock
with skew to account for clock differences between systems . "
at com.google . auth . oauCh2 . ServiceAccounCCredenCiaIs . refreshAccessToken ( S
erviceAccounCCredenCiaIs . java : 401)
at com.google . auth . oauCh2 . OAuth2CredenCiaIs . refresh (OAuth2CredenCiaIs . j a
va:181)
at com.google . auth . oauCh2 . OAuth2CredenCiaIs . geCRequesCMeCadaCa (OAuth2Cre
dentials . java : 167)
</code>```

答:
Please see these links if they help, looks to be a server time issue as you move to linux

Google Client Invalid JWT: Token must be a short-lived token

Token must be a short-lived token and in a reasonable timeframe

Body:
I was trying to initialize the Admin SDK, but facing 400 bad request in service account initialization. It was working perfectly in my development windows environment, but when I deploy the same in linux, am facing this issue.

        SpringApplication.run(OrderApplication.class, args);

        FileInputStream serviceAccount = new FileInputStream(GlobalValue.serviceAccount);

        FirebaseOptions options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .setDatabaseUrl("https://xxxxxxx.firebaseio.com").build();

        FirebaseApp.initializeApp(options);

    }

I am reading the file path from property file.

service.account=/home/service-account.json

I was trying to send push notification, am facing issue at that time.

        try {
            MulticastMessage multicastMessage = MulticastMessage.builder().addAllTokens(lDeviceTokens)
                    .setNotification(new Notification(title, message)).build();

            BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(multicastMessage);
            // See the BatchResponse reference documentation // for the contents of
            // response.
            System.out.println(response.getSuccessCount() + " messages were sent successfully");
        } catch (FirebaseMessagingException e) {
            e.printStackTrace();
            System.out.println(e.getLocalizedMessage());
        }
    }

Trace

. java: 141 S)
at org . apache . tomcat . util .neC . Socket ProcessorBase . run (Socket ProcessorBas
e . java : 49)
at java . concurrent . ThreadPooIExecuCor . runWorker (ThreadPooIExecuC01 .
java : 1149)
at java . concurrent . ThreadPooIExecucor$Worker . run (ThreadPooIExecuC01
. java : 624)
at org . apache . ComcaC . util . Chreads . TaskThread$WrappingRunnabIe . run (TaskTh
read . java : 61)
at java. lang . Thread. run (Thread. java : 7 48)
Caused by: java.io. IOExcepCion: Error getting access token for service account :
400 Bad Request
"error" • "invalid grant"
"error description" • "Invalid JWT: Token must be a short—lived token (60 minut
es) and in a reasonable timeframe. Check Y2ur iat and exp values and use a clock
with skew to account for clock differences between systems . "
at com.google . auth . oauCh2 . ServiceAccounCCredenCiaIs . refreshAccessToken ( S
erviceAccounCCredenCiaIs . java : 401)
at com.google . auth . oauCh2 . OAuth2CredenCiaIs . refresh (OAuth2CredenCiaIs . j a
va:181)
at com.google . auth . oauCh2 . OAuth2CredenCiaIs . geCRequesCMeCadaCa (OAuth2Cre
dentials . java : 167)


问:
How to send the element object as parameter to javascript function without ID
In function ClickedRow, i want to use the "a" which is being clicked. So i want to receive it as a parameter.

```<code><td ...... >
<span class="......>
  <span onmousedown="event.cancelBubble = true">
      <a class="GridLinkRenderer" href="javascript:ClickedRow(this)"  onclicklink="javascript:ClickedRow(this)" urlText="XXXX">

<td ......
<span class="......>
  <span onmousedown="event.cancelBubble = true">
      <a class="GridLinkRenderer" href="javascript:ClickedRow(this)"  onclicklink="javascript:ClickedRow(this)" urlText="XXXXX">
</code>```

Based on clicked ....> I would like to hide/show it (or to show/hide next class= "GridLinkRenderer" in other )   by function ClickedRow(this).
How can I do it ?

I've tried to send the clicked $(row).next().eq(0).tagName and row.style.display = 'none' , it says that it is "undefined".

```<code>function ClickedRow(row){

$(row).next().eq(0).hide();
$(row).hide();

}
</code>```

答:
have you looked at closest(),find() and next() ?

https://api.jquery.com/closest/

https://api.jquery.com/next/

https://api.jquery.com/find/

$(row).closest('td').next('td').find('.GridLinkRenderer')

haven't tested this.. but if I'm thinking right this should be at least the point to right direction.

Body:
In function ClickedRow, i want to use the "a" which is being clicked. So i want to receive it as a parameter.

<td ......

Based on clicked  I would like to hide/show it (or to show/hide next <a class= "GridLinkRenderer" in other )   by function ClickedRow(this).
How can I do it ?

I've tried to send the clicked $(row).next().eq(0).tagName and row.style.display = 'none' , it says that it is "undefined".

function ClickedRow(row){

$(row).next().eq(0).hide();
$(row).hide();

}


问:
How can I numerate list items using State monad in Haskell?
Problem:

I am trying to understand state-monad.

A bit stuck to understand how can I use it, and I am looking for some example.

Let's say I want to implement a function [()] -> [Int]:

```<code>numerate :: [()] -> [Int]
</code>```

Should I map each element of the list to state and then fold it?

How can I do it using State?

Expected behavior:

```<code>numerate [(), (), (), (), ()]
-- [1, 2, 3, 4, 5]
</code>```

Thanks!

答:
We can implement a State object that will increment the state and return it, like:

```<code>incState :: State Int Int
incState = modify (1+) >> get
</code>```

Then we can run this State Int Int over the list, like:

```<code>numerate :: (Traversable t) => t a -> t Int
numerate = flip evalState 0 . traverse (const incState)
</code>```

For example:

```<code>Prelude Control.Monad.State> numerate Nothing
Nothing
Prelude Control.Monad.State> numerate (Just 'a')
Just 1
Prelude Control.Monad.State> numerate (Just 0)
Just 1
Prelude Control.Monad.State> numerate [1,4,2,5]
[1,2,3,4]
Prelude Control.Monad.State> numerate [(), (), ()]
[1,2,3]
</code>```

We can also work with other traversable structures, like a Tree for example:

```<code>Prelude Control.Monad.State Data.Tree> numerate (Node 'a' [Node 'b' [], Node 'c' []])
Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []},Node {rootLabel = 3, subForest = []}]}
</code>```

Body:
Problem:

I am trying to understand state-monad.

A bit stuck to understand how can I use it, and I am looking for some example.

Let's say I want to implement a function [()] -> [Int]:

numerate :: [()] -> [Int]

Should I map each element of the list to state and then fold it?

How can I do it using State?

Expected behavior:

numerate [(), (), (), (), ()]
-- [1, 2, 3, 4, 5]

Thanks!

Body:
We can implement a State object that will increment the state and return it, like:

incState :: State Int Int
incState = modify (1+) >> get

Then we can run this State Int Int over the list, like:

numerate :: (Traversable t) => t a -> t Int
numerate = flip evalState 0 . traverse (const incState)

For example:

Prelude Control.Monad.State> numerate Nothing
Nothing
Prelude Control.Monad.State> numerate (Just 'a')
Just 1
Prelude Control.Monad.State> numerate (Just 0)
Just 1
Prelude Control.Monad.State> numerate [1,4,2,5]
[1,2,3,4]
Prelude Control.Monad.State> numerate [(), (), ()]
[1,2,3]

We can also work with other traversable structures, like a Tree for example:

Prelude Control.Monad.State Data.Tree> numerate (Node 'a' [Node 'b' [], Node 'c' []])
Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []},Node {rootLabel = 3, subForest = []}]}


问:
Check if a week of dates sits between two specific dates SQL ORACLE
I have two dates and want to only keep rows where a certain week falls in between those two dates. I need to run this for 67+ different weeks so I'd like to change my below code to run quicker and not have to type out the 7 days of the week each time. </p>

```<code>SELECT * FROM MY_DATA
WHERE  ('05-JUNE-2017' BETWEEN start_date AND end_date
OR      '06-JUNE-2017' BETWEEN start_date AND end_date
OR      '07-JUNE-2017' BETWEEN start_date AND end_date
OR      '08-JUNE-2017' BETWEEN start_date AND end_date
OR      '09-JUNE-2017' BETWEEN start_date AND end_date
OR      '10-JUNE-2017' BETWEEN start_date AND end_date
OR      '11-JUNE-2017' BETWEEN start_date AND end_date);
</code>```

答:
I think your query is equivalent to

```<code>SELECT * FROM MY_DATA WHERE  ('05-JUNE-2017' BETWEEN start_date - 6 AND end_date );
</code>```

where '05-JUNE-2017' is the initial day of the week you are looking for.

Now you have to do this for all the initial week days...

Is that what you are looking for?

Body:
I have two dates and want to only keep rows where a certain week falls in between those two dates. I need to run this for 67+ different weeks so I'd like to change my below code to run quicker and not have to type out the 7 days of the week each time.

SELECT * FROM MY_DATA
WHERE  ('05-JUNE-2017' BETWEEN start_date AND end_date
OR      '06-JUNE-2017' BETWEEN start_date AND end_date
OR      '07-JUNE-2017' BETWEEN start_date AND end_date
OR      '08-JUNE-2017' BETWEEN start_date AND end_date
OR      '09-JUNE-2017' BETWEEN start_date AND end_date
OR      '10-JUNE-2017' BETWEEN start_date AND end_date
OR      '11-JUNE-2017' BETWEEN start_date AND end_date);

Body:
I think your query is equivalent to

SELECT * FROM MY_DATA WHERE  ('05-JUNE-2017' BETWEEN start_date - 6 AND end_date );

where '05-JUNE-2017' is the initial day of the week you are looking for.

Now you have to do this for all the initial week days...

Is that what you are looking for?


问:
Commercial round with comma and point
I have used this code :

```<code>$result = number_format(round(15.5, 1), 2);
</code>```

Written in my old post :
PHP - Commercial round

I have now problems with the values like : 1,597.30

I get the price as 1.00

How can I do to get the make the round and get the good price format with the prices that have number with thousands.

答:
You could solve this issue using the following code:</p>

```<code>$price       = '1,597.30';
$new_price   = floatval(str_replace(',', '', $price));
$result      = number_format(round($new_price, 1), 2);
</code>```

Title: Commercial round with comma and point

Body:
I have used this code :

$result = number_format(round(15.5, 1), 2);

Written in my old post :
PHP - Commercial round

I have now problems with the values like : 1,597.30

I get the price as 1.00

How can I do to get the make the round and get the good price format with the prices that have number with thousands.

Body:
You could solve this issue using the following code:

$price       = '1,597.30';
$new_price   = floatval(str_replace(',', '', $price));
$result      = number_format(round($new_price, 1), 2);


问:
Why is Overload Resolution favoring unconstrained template function over a more specific one?
I have this minimal expression template library with a multiplication, i.e.

```<code>template <typename T, typename U>
struct mul {
    const T &v1;
    const U &v2;
};

template <typename T, typename U>
mul<T, U> operator*(const T &one, const U &two) {
    std::cout << " called: mul<T, U> operator*(const T &one, const T &two)\n";
    return mul<T, U>{one, two};
}
</code>```

and transpose, i.e.

```<code>template <typename T>
struct transpose {
    const T &t;
};

template <typename T>
transpose<T> tran(const T &one) {
    return transpose<T>{one};
}
</code>```

I will introduce some types A and B, where the latter is a subclass of the former:

```<code>template <typename T>
struct A {
    T elem;
};

template <typename T>
struct B : A<T> {
    B(T val) : A<T>{val} {}
};
</code>```

Then, I can call my expression template library as follows (with an overload for printing to std::cout):

```<code>template <typename T, typename U>
std::ostream &operator<<(std::ostream &os, const mul<T, U> &m) {
    os << " unconstrained template \n";
}

int main(int argc, char const *argv[]) {
    B<double> a{2};
    B<double> b{3};
    std::cout << tran(a) * b << "\n";
    return 0;
}
</code>```

This gives me the output :

```<code>called: mul<T, U> operator*(const T &one, const T &two)
unconstrained template
</code>```

So far so good. Suppose now that I want a specialized treatment for 'transpose of a variable of type A<T> times a variable of type A<T> for some type T', as I had in my main. To this end, I will introduce

```<code>template <typename T>
T operator*(const transpose<A<T>> &one, const A<T> &two) {
    std::cout << " called: T operator*(const A<T> &one, const A<T> &two)\n";
    return one.t.elem * two.elem;
}
</code>```

I run the same main function as above, and I still get the same output as above (unconstrained template). This is to be expected, since transpose<B<double>> is a completely different type compared to transpose<A<double>>, so overload resolution picks the unconstrained template version of operator*.

(Of course, if I change my variable definitions in main to A instead of B, ADL calls the specialized function and output is called: T operator*(const A<T> &one, const A<T> &two) and 6).

I recently learned about SFINAE, so I expected the following change to the more specific multiplication operator would cause overload resulution to select the specialized function:

```<code>template <typename T, typename V>
std::enable_if_t<std::is_base_of<A<T>, V>::value, T> operator*(const transpose<V> &one,
                                                               const V &two) {
    std::cout << " called: std::enable_if_t<std::is_base_of<A<T>, V>::value, T> operator*(const "
                 "transpose<V> &one, const V &two)\n";
    return one.t.elem * two.elem;
}
</code>```

Even using the SFINAE'd operator* I still get the unconstrained template version. How come? What changes should I make to call the more specialized template function?

答:
The problem is that in the SFINAE overload, T is used in a non-deduced context. You're effectively asking the compiler: "Enable this if there exists a T such that A<T> is a base class of V." Existential quantification is a good indicator that what you're asking for cannot be SFINAEd.

You can see this yourself if you disable the unconstrained template, as I did here. This forces the compiler to spell out why the other function is not admissible.

You can solve this by making T available through your A (and thus B) classes, like this:

```<code>template <typename T>
struct A {
    using Type = T;
    T elem;
};

template <typename V>
std::enable_if_t<std::is_base_of<A<typename V::Type>, V>::value, typename V::Type> operator*(const transpose<V> &one,
                                                               const V &two) {
    std::cout << " called: std::enable_if_t<std::is_base_of<A<T>, V>::value, T> operator*(const "
                 "transpose<V> &one, const V &two)\n";
    return one.t.elem * two.elem;
}
</code>```

[Live example]

Body:
I have this minimal expression template library with a multiplication, i.e.

template <typename T, typename U>
struct mul {
    const T &v1;
    const U &v2;
};

template <typename T, typename U>
mul<T, U> operator*(const T &one, const U &two) {
    std::cout << " called: mul<T, U> operator*(const T &one, const T &two)\n";
    return mul<T, U>{one, two};
}

and transpose, i.e.

template <typename T>
struct transpose {
    const T &t;
};

template <typename T>
transpose<T> tran(const T &one) {
    return transpose<T>{one};
}

I will introduce some types A and B, where the latter is a subclass of the former:

template <typename T>
struct A {
    T elem;
};

template <typename T>
struct B : A<T> {
    B(T val) : A<T>{val} {}
};

Then, I can call my expression template library as follows (with an overload for printing to std::cout):

template <typename T, typename U>
std::ostream &operator<<(std::ostream &os, const mul<T, U> &m) {
    os << " unconstrained template \n";
}

int main(int argc, char const *argv[]) {
    B<double> a{2};
    B<double> b{3};
    std::cout << tran(a) * b << "\n";
    return 0;
}

This gives me the output :

called: mul<T, U> operator*(const T &one, const T &two)
unconstrained template

So far so good. Suppose now that I want a specialized treatment for 'transpose of a variable of type A<T> times a variable of type A<T> for some type T', as I had in my main. To this end, I will introduce

template <typename T>
T operator*(const transpose<A<T>> &one, const A<T> &two) {
    std::cout << " called: T operator*(const A<T> &one, const A<T> &two)\n";
    return one.t.elem * two.elem;
}

I run the same main function as above, and I still get the same output as above (unconstrained template). This is to be expected, since transpose<B<double>> is a completely different type compared to transpose<A<double>>, so overload resolution picks the unconstrained template version of operator*.

(Of course, if I change my variable definitions in main to A instead of B, ADL calls the specialized function and output is called: T operator*(const A<T> &one, const A<T> &two) and 6).

I recently learned about SFINAE, so I expected the following change to the more specific multiplication operator would cause overload resulution to select the specialized function:

template <typename T, typename V>
std::enable_if_t<std::is_base_of<A<T>, V>::value, T> operator*(const transpose<V> &one,
                                                               const V &two) {
    std::cout << " called: std::enable_if_t<std::is_base_of<A<T>, V>::value, T> operator*(const "
                 "transpose<V> &one, const V &two)\n";
    return one.t.elem * two.elem;
}

Even using the SFINAE'd operator* I still get the unconstrained template version. How come? What changes should I make to call the more specialized template function?

Body:
The problem is that in the SFINAE overload, T is used in a non-deduced context. You're effectively asking the compiler: "Enable this if there exists a T such that A<T> is a base class of V." Existential quantification is a good indicator that what you're asking for cannot be SFINAEd.

You can see this yourself if you disable the unconstrained template, as I did here. This forces the compiler to spell out why the other function is not admissible.

You can solve this by making T available through your A (and thus B) classes, like this:

template <typename T>
struct A {
    using Type = T;
    T elem;
};

template <typename V>
std::enable_if_t<std::is_base_of<A<typename V::Type>, V>::value, typename V::Type> operator*(const transpose<V> &one,
                                                               const V &two) {
    std::cout << " called: std::enable_if_t<std::is_base_of<A<T>, V>::value, T> operator*(const "
                 "transpose<V> &one, const V &two)\n";
    return one.t.elem * two.elem;
}

[Live example]