问:
SQL Server - find absence date occurrences
I have the following dataset:

enter image description here

Here is script for this data:

;with dataset AS (
    select 'EMP01' AS EMP_ID,CAST('2018-01-01' AS DATE) AS PERIOD_START,CAST('2018-01-31' AS DATE) AS PERIOD_END,CAST('2018-01-07' AS DATE) AS CUT_DATE
    UNION
    select 'EMP01' AS EMP_ID,CAST('2018-01-01' AS DATE) AS PERIOD_START,CAST('2018-01-31' AS DATE) AS PERIOD_END,CAST('2018-01-15' AS DATE) AS CUT_DATE
    UNION
    select 'EMP02' AS EMP_ID,CAST('2018-01-01' AS DATE) AS PERIOD_START,CAST('2018-01-31' AS DATE) AS PERIOD_END,CAST('2018-01-09' AS DATE) AS CUT_DATE
)
select *
from dataset
I need to divide these periods (PERIOD_START and PERIOD_END) by CUT_DATE (exclude cut dates from that periods) The number of cut dates could be any (3,5,8 etc).

Expecting result for the dataset above is:

答:
If your version of SQL Server supports LAG, you can use this.

```<code>SELECT EMPLOYEE_ID,
       ITEM_TYPE,
       MIN(APPLY_DATE) AS STARTDATE,
       MAX(APPLY_DATE) AS ENDDATE
FROM
 (SELECT T.*,
         SUM(CASE WHEN PREV_TYPE=ITEM_TYPE THEN 0 ELSE 1 END)
         OVER(PARTITION BY EMPLOYEE_ID ORDER BY APPLY_DATE) AS GRP
  FROM (SELECT D.*,
        LAG(ITEM_TYPE) OVER(PARTITION BY EMPLOYEE_ID ORDER BY APPLY_DATE) AS PREV_TYPE
        FROM DATA D
       ) T
  ) T
WHERE ITEM_TYPE IN ('Sickness','Vacation')
GROUP BY EMPLOYEE_ID,ITEM_TYPE,GRP
</code>```

The logic is to get the previous row's item_type (based on ascending order of apply_date) and compare it with the current row's value. If they are equal, they belong to the same group. Else you start a new group. This is done in the sum window function. After groups are assigned, you just need to get the max and min date for an employee_id,item_type.

Sample Demo

Body:
If your version of SQL Server supports LAG, you can use this.

SELECT EMPLOYEE_ID,
       ITEM_TYPE,
       MIN(APPLY_DATE) AS STARTDATE,
       MAX(APPLY_DATE) AS ENDDATE
FROM
 (SELECT T.*,
         SUM(CASE WHEN PREV_TYPE=ITEM_TYPE THEN 0 ELSE 1 END)
         OVER(PARTITION BY EMPLOYEE_ID ORDER BY APPLY_DATE) AS GRP
  FROM (SELECT D.*,
        LAG(ITEM_TYPE) OVER(PARTITION BY EMPLOYEE_ID ORDER BY APPLY_DATE) AS PREV_TYPE
        FROM DATA D
       ) T
  ) T
WHERE ITEM_TYPE IN ('Sickness','Vacation')
GROUP BY EMPLOYEE_ID,ITEM_TYPE,GRP

The logic is to get the previous row's item_type (based on ascending order of apply_date) and compare it with the current row's value. If they are equal, they belong to the same group. Else you start a new group. This is done in the sum window function. After groups are assigned, you just need to get the max and min date for an employee_id,item_type.

Sample Demo


来源: stackexchange

问:
Find string in list within list of objects
I have a list of objects with lists:

```<code>ls = [
    {'id': 1, 'content': ['lorem', 'ipsum']},
    {'id': 1, 'content': ['dolor', 'sit', 'amet']},
]
</code>```

i want to get the index of the object with e.g. 'lorem'

So far i tried:

```<code>'lorem' in [x['content'] for x in ls]
</code>```

This does not return true nor does it return an index.

答:
ls.index([x for x in ls if 'lorem' in x['content']][0])

This oneline style has the same result as follows:

```<code>t = []
for x in ls:
    if 'lorem' in x['content']:
        t.append(x)
ls.index(t[0])
</code>```

On my machine, the output is:

```<code>>>> ls.index([x for x in ls if 'lorem' in x['content']][0])
0
>>> ls.index([x for x in ls if 'ipsum' in x['content']][0])
0
>>> ls.index([x for x in ls if 'dolor' in x['content']][0])
1
>>> ls.index([x for x in ls if 'sit' in x['content']][0])
1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a list of objects with lists:

ls = [
    {'id': 1, 'content': ['lorem', 'ipsum']},
    {'id': 1, 'content': ['dolor', 'sit', 'amet']},
]

i want to get the index of the object with e.g. 'lorem'

So far i tried:

'lorem' in [x['content'] for x in ls]

This does not return true nor does it return an index.

Body:
ls.index([x for x in ls if 'lorem' in x['content']][0])

This oneline style has the same result as follows:

t = []
for x in ls:
    if 'lorem' in x['content']:
        t.append(x)
ls.index(t[0])

On my machine, the output is:

>>> ls.index([x for x in ls if 'lorem' in x['content']][0])
0
>>> ls.index([x for x in ls if 'ipsum' in x['content']][0])
0
>>> ls.index([x for x in ls if 'dolor' in x['content']][0])
1
>>> ls.index([x for x in ls if 'sit' in x['content']][0])
1


问:
How to configure MassTransit to retry context.Publish() in case of failure?
How to configure MassTransit to retry context.Publish() before failing, for example when RabbitMQ server is temporary unavailable?

答:
The problem with retry in this context is that the only real reason a Publish call would fail is if the broker connection was lost (for any reason: network, etc.).

In that case, the connection which was used to receive the message is also lost, meaning that another node connected to the broker may have already picked up the message. So a retry in this case would be bad, since it would reconnect to the broker and send, but then the message could not be acknowledged (since it was likely picked up on another thread/worker).

The usual course of action here is to let it fail, and when the receive endpoint reconnects, the message will be redelivered to a consumer which will then call Publish and reach the desired outcome.

You should make sure that your consumer can handle this (search for idempotent) properly to avoid a failure causing a break in your business logic.

Updated Jan 2022: Since v7, MassTransit retries all publish/send calls until the cancellationToken is canceled.

ContentLicense: CC BY-SA 4.0


问:
Java Style / Best Practice - passing fields to methods vs accessing directly
In Java, given the following class:

```<code>public class MyClass {
   private final Dependency dependency;
   public MyClass(Dependency dependency)
   {
       this.dependency = dependency;
   }

   public void doWork()
   {
       // validate dependency...
   }
</code>```

The doWork method needs to invoke a method that uses dependency.

Which of the following two variations is considered "best practice", and why?

```<code>   // Access dependency directly
   void validateDependency()
   {
        this.dependency.something();
   }

   // access dependency as passed to the method
   void validateDependency(Dependency dependency)
   {
       dependency.something();
   }
</code>```

I find myself favouring the latter, passing the dependency directly to the method, as it makes the method easier to test in isolation (albeit, marginally).

However, I'm interested in the java convention / best practice here.

答:
A class exists because you have state and operations that are coupled to that state. There's no good reason to pass part of that state as a parameter to a class method.

In fact, it would indicate to me that that piece of state should not actually belong to the class. Or that the method doesn't belong to the class.

Using a parameter "so that it's easier to unit test" is a good indication that the latter holds (the method should not be in the class).

ContentLicense: CC BY-SA 2.5

Body:
In Java, given the following class:

public class MyClass {
   private final Dependency dependency;
   public MyClass(Dependency dependency)
   {
       this.dependency = dependency;
   }

   public void doWork()
   {
       // validate dependency...
   }

The doWork method needs to invoke a method that uses dependency.

Which of the following two variations is considered "best practice", and why?

   // Access dependency directly
   void validateDependency()
   {
        this.dependency.something();
   }

   // access dependency as passed to the method
   void validateDependency(Dependency dependency)
   {
       dependency.something();
   }

I find myself favouring the latter, passing the dependency directly to the method, as it makes the method easier to test in isolation (albeit, marginally).

However, I'm interested in the java convention / best practice here.


问:
Remote true for a
To define my ajax functions, I normally use a <%= link_to %> to add a remote:true method. But I have a  tag line

```<code><a href="/posts/<%= post.id %>/undone" data-method="patch"><i class="fa fa-close" aria-hidden="true" style="margin-right: 10px;"></i>Cancel</a>
</code>```

that I want to run with ajax.

And I cannot change it into a link_to because it's crashing all my design.
So do you know a method to achieve that ?

答:
remote: true is just a shortcut for adding the attribute data-remote="true". Add this to your anchor tag and it should have the same effect. E.g.

```<code><a href="/posts/<%= post.id %>/undone" data-method="patch" data-remote="true">
</code>```

That said - what's stopping you from using link_to? You can use it with a block e.g.:

```<code><%= link_to undone_posts_path(post.id), remote: true, method: :patch do %>
  <i class="fa fa-close" aria-hidden="true" style="margin-right: 10px;"></i>
  Cancel
<% end %>
</code>```

Title: Remote true for a <a>

Body:
To define my ajax functions, I normally use a <%= link_to %> to add a remote:true method. But I have a  tag line

<a href="/posts/<%= post.id %>/undone" data-method="patch">Cancel

that I want to run with ajax.

And I cannot change it into a link_to because it's crashing all my design.
So do you know a method to achieve that ?

Body:
remote: true is just a shortcut for adding the attribute data-remote="true". Add this to your anchor tag and it should have the same effect. E.g.

<a href="/posts/<%= post.id %>/undone" data-method="patch" data-remote="true">

That said - what's stopping you from using link_to? You can use it with a block e.g.:

<%= link_to undone_posts_path(post.id), remote: true, method: :patch do %>
  <i class="fa fa-close" aria-hidden="true" style="margin-right: 10px;"></i>
  Cancel
<% end %>


问:
Vagrant: How to sync folder from guest back to host?
Why, because it is difficult to work and edit code via legacy editors in the guest. The whole purpose of vagrant is to be more easily for the developer, right:)?

As such I please someone to guide me in this situation:

Need to work on a project. It is git repo. Requires mysql, php, etc, etc.

VM works great(provided)

But editing files in this repo not so easy via ssh and "legacy" editors. Want to use favorite IDE.

On the VM repo is in /home/vagrant/src.
I want it to be visible/editable in ../src in the host.

I read the docs and putted this in the Vagranfile:

config.vm.synced_folder '../src', '/home/vagrant/src'

This "works" except that it overwrites all contents from /home/vagrant/src with those from ../src which is empty.

Any workaround?
I considered the possibility to clone the repo via git(publicly available via github) and sync the folder to the VM but this does not feel right and lose production configs too.

Body:
It sounds like you want to share a folder from the guest machine with the host machine which is kind of the opposite of what the normal shared folders do.

Have you thought about provisioning NFS on the guest, and then using vagrant-triggers to mount the share from the guest onto the host.

First start by installing vagrant-triggers:

vagrant plugin install vagrant-triggers

Then have a Vagrantfile like this:

# where you want to mount the guest's shared folder on the host
host_mount_dir = "/home/david/vagrant-home"

Vagrant.configure(2) do |config|
    config.vm.box = "debian/jessie64"

    # forward the NFS port
    config.vm.network "forwarded_port", guest: 2049, host: 8049

    # configure NFS on guest
    config.vm.provision "shell", inline: <<SCRIPT
apt-get install -y nfs-kernel-server nfs-common
host_ip="$(netstat -rn | grep "^0.0.0.0 " | cut -d " " -f10)"
echo "/home/vagrant       $host_ip(rw,sync,no_subtree_check)" > /etc/exports
exportfs -a
SCRIPT

    # after the machine is up, mount the NFS share
    config.trigger.after :up do
        # mkake the dir if it doesnt exist
        run "mkdir -p " + host_mount_dir
        # we need the users pass to mount (make sure you are a sudoer!)'
        puts "Please enter your password so that we can run mount"
        run "sudo mount -t nfs -o port=8049 localhost:/home/vagrant #{host_mount_dir}"
    end

    # before halting, unmount the share
    config.trigger.before :halt do
        # we need the users pass again
        puts "Please enter your password so that we can run mount"
        run "sudo umount #{host_mount_dir}"
    end

end

This is an unusual setup, but I tested it now with an Ubuntu host and a Debian guest and it seems to be working - YMMV.


问:
Display unique array entries and sum of related entry from separate array
I'm trying to take two arrays that are related, filter one to retrieve the unique values and the other needs to have the sums for the unique values. The indexes for Array 1 match the index for Array 2 that I need to add all the values together to get the sum. For example:

Array 1:

```<code>var arr1 = [7012, 7013, 7015, 7012];
</code>```

Array 2:

```<code>var arr2 = [10, 20, 25, 10];
</code>```

Expected Output:

(first explanation was not great, changing this)

```<code>newArray1 = [7012, 7013, 7015];
newArray2 = [20, 20, 25];
</code>```

Note: I am using Firebase to retrieve the values into the arrays, these are not going to be set indexes.

I'm using Set() to retrieve the unique values:

```<code>var newArr = [...new Set(arr1)];
</code>```

which works perfectly fine.

The trouble I'm having is getting the related values from Array 2 and making a sum. I can create the sum fine by using .reduce() but I'm having trouble figuring out how to get the Array 2 values into a new array based on what they're related to in Array 1.

答:
As far as i understand you, you want to group and sum up arr2, based on equal values at the arr1. So you may create a hash table:

```<code>var arr1 = [7012, 7013, 7015, 7012];
var arr2 = [10, 20, 25, 10];

var obj={};
arr1.forEach(function(el,i){//el is a value of arr1 at index i, e.g. 7012,0
  obj[el]=obj[el]||0;//initialise obj[7012]
  obj[el]+=arr2[i]||0;//increase obj[7012] by arr2[0] so 10
});

console.log(obj);
</code>```

Will create:

```<code>{
7012:20,
7013:20,
7015:25
}
</code>```

Body:
I'm trying to take two arrays that are related, filter one to retrieve the unique values and the other needs to have the sums for the unique values. The indexes for Array 1 match the index for Array 2 that I need to add all the values together to get the sum. For example:

Array 1:

var arr1 = [7012, 7013, 7015, 7012];

Array 2:

var arr2 = [10, 20, 25, 10];

Expected Output:

(first explanation was not great, changing this)

newArray1 = [7012, 7013, 7015];
newArray2 = [20, 20, 25];

Note: I am using Firebase to retrieve the values into the arrays, these are not going to be set indexes.

I'm using Set() to retrieve the unique values:

var newArr = [...new Set(arr1)];

which works perfectly fine.

The trouble I'm having is getting the related values from Array 2 and making a sum. I can create the sum fine by using .reduce() but I'm having trouble figuring out how to get the Array 2 values into a new array based on what they're related to in Array 1.

Body:
As far as i understand you, you want to group and sum up arr2, based on equal values at the arr1. So you may create a hash table:

var arr1 = [7012, 7013, 7015, 7012];
var arr2 = [10, 20, 25, 10];

var obj={};
arr1.forEach(function(el,i){//el is a value of arr1 at index i, e.g. 7012,0
  obj[el]=obj[el]||0;//initialise obj[7012]
  obj[el]+=arr2[i]||0;//increase obj[7012] by arr2[0] so 10
});

console.log(obj);

Will create:

{
7012:20,
7013:20,
7015:25
}


问:
How to remove default border of UITextView
Hi I want to remove Default gray border of tHe View. so by doing this we can not find the textview on view. How we can do this?</p>

答:
Swift 3

```<code>textView.borderStyle = .none
</code>```

Body:
Swift 3

textView.borderStyle = .none


问:
mongodb most efficient way to store gps tracking data
I need to store gps points (timestamp, lon, lat) from different users.

should I have a separate users collection and a gps data collection:

users

```<code>{_id: 1, name: 'A'}
</code>```

gps

```<code>{_id: 1, userId: 1, timestamp: ..., lon: ..., lat: ...}
{_id: 2, userId: 1, timestamp: ..., lon: ..., lat: ...}
</code>```

or can I just save the gps data as an array into the corresponding user document:

users

```<code>{_id: 1, name: 'A', gps: [
     {timestamp: ..., lon: ..., lat: ...}
     {timestamp: ..., lon: ..., lat: ...}
]}
</code>```

I know that option 2 would be crazy for SQL DBs, but I am not sure about the performance implications with MongoDB

答:
You must design your MongoDB collections based on the access strategy of your application.

In general, you should go for embedding points into user doc if:

embedded data (points) are always retrieved when user info are
retrieved. If you are always retrieving user info but rarely you need also GPS data then embedding cannot be so good.

embedded data are not subject to modifications (or at least rarely)

the cardinality is not too big (remember MongoDB document max size
is 16MB). If you have 100K points per user split the collections

Furthermore, having points embedded into user docs, you can take advantage of
document level locking (if you are using Wired Tiger storage engine). Otherwise, if you're in a concurrent system, with the two collections design you have to handle locking mechanism by yourself at application level.

Body:
I need to store gps points (timestamp, lon, lat) from different users.

should I have a separate users collection and a gps data collection:

users

{_id: 1, name: 'A'}

gps

{_id: 1, userId: 1, timestamp: ..., lon: ..., lat: ...}
{_id: 2, userId: 1, timestamp: ..., lon: ..., lat: ...}

or can I just save the gps data as an array into the corresponding user document:

users

{_id: 1, name: 'A', gps: [
     {timestamp: ..., lon: ..., lat: ...}
     {timestamp: ..., lon: ..., lat: ...}
]}

I know that option 2 would be crazy for SQL DBs, but I am not sure about the performance implications with MongoDB


问:
How to escape a NULL byte as an argument to a shell command inside a Makefile
Inside a Makefile I run a shell command which I want to pass a NULL byte as argument. The following attempt fails:

```<code>echo $(shell /bin/echo -n $$'\x00' | ruby -e "puts STDIN.read.inspect")
</code>```

It generates:

```<code>echo "$\\x00"
</code>```

Instead I expected:

```<code>echo "\u0000"
</code>```

How do I properly escape such a NULL byte?

答:
If anyone else came here looking how to escape a null via a shell command in ruby backticks:</p>

```<code>irb(main):024:0> `curl --silent http://some-website-or-stream.com | sed 's/\\x0//g' 1>&2`
=> ""
</code>```

Body:
Inside a Makefile I run a shell command which I want to pass a NULL byte as argument. The following attempt fails:

echo $(shell /bin/echo -n $$'\x00' | ruby -e "puts STDIN.read.inspect")

It generates:

echo "$\\x00"

Instead I expected:

echo "\u0000"

How do I properly escape such a NULL byte?

Body:
If anyone else came here looking how to escape a null via a shell command in ruby backticks:

irb(main):024:0> `curl --silent http://some-website-or-stream.com | sed 's/\\x0//g' 1>&2`
=> ""


问:
Calling a service on input change and update view
I'm writing a simple component which takes as input an Id and calls a service method to return an entity to display:

```<code>@Input() id: string;

ngOnInit(): void {
    if (this.id != undefined && this.id != "") {
        this.detailSubscription=this.service.load(this.id)
            .subscribe(result => {

                    this.detail$ = result;
                    this.cd.detectChanges();
            });
    }
}

ngOnDestroy() {
   this.cd.detach();
   this.detailSubscription.unsubscribe();
}
</code>```

This componet works only the first time. If input Id changes it doesen't update the view.

I also tried to put service call inside onChanges method, but it won't works due to unsubscribe that is called only once on onDestroy method.

How to achieve this?

答:
You need use ngOnChanges instead of ngOnInit like below. As ngOnInit will fire only once, where as ngOnChanges will fire every time the input value changes.

And also try unsubscribing before calling service.

```<code> ngOnChanges(changes: SimpleChanges) {

   if (changes['id']) {
      if(this.detailSubscription) {
         this.detailSubscription.unsubscribe();
      }
      //call your service here
   }
}
</code>```

Body:
I'm writing a simple component which takes as input an Id and calls a service method to return an entity to display:

@Input() id: string;

ngOnInit(): void {
    if (this.id != undefined && this.id != "") {
        this.detailSubscription=this.service.load(this.id)
            .subscribe(result => {

                    this.detail$ = result;
                    this.cd.detectChanges();
            });
    }
}

ngOnDestroy() {
   this.cd.detach();
   this.detailSubscription.unsubscribe();
}

This componet works only the first time. If input Id changes it doesen't update the view.

I also tried to put service call inside onChanges method, but it won't works due to unsubscribe that is called only once on onDestroy method.

How to achieve this?

Body:
You need use ngOnChanges instead of ngOnInit like below. As ngOnInit will fire only once, where as ngOnChanges will fire every time the input value changes.

And also try unsubscribing before calling service.

 ngOnChanges(changes: SimpleChanges) {

   if (changes['id']) {
      if(this.detailSubscription) {
         this.detailSubscription.unsubscribe();
      }
      //call your service here
   }
}


问:
JavaScript - Form validation loop through specific fields
I'm wondering, what would be a short/good way of performing form validation in JavaScript by looping through all input-text as well as <select>, however, the condition on the select is that out of the 2 selects, ONLY one needs to be selected.

```<code><form id="daform">
<input type="text" value="" name="name" id="name" />
<input type="text" value="" name="last" id="last" />

<select id="choice1" name="choice1">
 <option>Bye</option>
 <option>Hello</option>
</select>

<select id="choice2" name="choice2">
 <option>Bye</option>
 <option>Hello</option>
</select>

<input type="submit" />
</form>
</code>```

Body:
I'm wondering, what would be a short/good way of performing form validation in JavaScript by looping through all input-text as well as <select>, however, the condition on the select is that out of the 2 selects, ONLY one needs to be selected.

<form id="daform">
<input type="text" value="" name="name" id="name" />
<input type="text" value="" name="last" id="last" />

<select id="choice1" name="choice1">
 <option>Bye</option>
 <option>Hello</option>
</select>

<select id="choice2" name="choice2">
 <option>Bye</option>
 <option>Hello</option>
</select>

<input type="submit" />
</form>

Body: Look into,document.getElementsByTagName().


问:
Can I specify Git URLs as dependencies in Buck?
I am using Buck to build a C++ project.

I would like to add a Git URL (e.g. git@github.com:owner/project.git) as a dependency so that a build can automatically pull down a library from GitHub. I took a look at remote_file, but that only seems to work for HTTP, HTTPS and Maven.

Does Buck provide this functionality out-of-the-box?

If so, is it possible to specify a specific commit hash or tag?

答:
Buck does not support remote Git URLs.

Your options are:

Copy the code manually into your project

Use an equivalent .zip URL (GitHub gives you these)

Use submodules, such as in this example

Use a package manager that supports Buck, such as Buckaroo


问:
ArrayList not able to add elements due to the function call
While running the below snippet the loop executes properly, but the elements are not added for some reason.</p>

```<code>for(i=5;i<=500;i++) {
    x.add(i);
    check(x,i);
}

public static void check(ArrayList<Integer> x,Integer i){
    for(int j=0;j<x.size();j++){
        for(int k=0;k<x.size();k++){
            if(x.get(j)!=i&& x.get(k)!=i){
                if(x.contains(x.get(k)+x.get(j)))
                    x.remove(Integer.valueOf(i));
            }
        }
    }
}
</code>```

答: You are removing the int i from the list instead of the computed value.  You do your contains method, you should remove that part.  Every time this is run it will remove whatever you plug in for i in the parameters.  So every time you add something you then just the method and delete what you just added.  </p>

Body:
While running the below snippet the loop executes properly, but the elements are not added for some reason.

for(i=5;i<=500;i++) {
    x.add(i);
    check(x,i);
}

public static void check(ArrayList<Integer> x,Integer i){
    for(int j=0;j<x.size();j++){
        for(int k=0;k<x.size();k++){
            if(x.get(j)!=i&& x.get(k)!=i){
                if(x.contains(x.get(k)+x.get(j)))
                    x.remove(Integer.valueOf(i));
            }
        }
    }
}


问:
why awk not working at ssh -V?
command1:

ssh -V

output1:

```<code>OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013
</code>```

command2:

ssh -V|awk -F, '{print $1}'

output2:

```<code>OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013
</code>```

In Command2, why awk is not breaking  the output with comma (',') delimiter

答:
Because the output of ssh -V goes to stderr. If you want to process that output, you need to redirect it to stdout:

ssh -V 2>&1 | cut -d, -f1
# .....^^^^
```

Title: why awk not working at ssh -V?

Body:
command1:

ssh -V

output1:

OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013

command2:

ssh -V|awk -F, '{print $1}'

output2:

OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013

In Command2, why awk is not breaking  the output with comma (',') delimiter


问:
Template variables based on calculations using fields from Django Model
I am using Django 1.10.7 and Python 3.6.1. First my code, then my questions.

My model looks like this:

```<code>class Thing(models.Model):
    user = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    start_date = models.DateTimeField(
        default=timezone.now)
    cost_per_day = models.DecimalField(max_digits=6, decimal_places=2)
</code>```

Here are my views:

```<code>def something_list(request):
    things =Thing.objects.filter(start_date__lte=timezone.now()).order_by('start_date')
    return render(request, 'myApp/something_list.html', {'things': things})

def thing_detail(request, pk):
    thing = get_object_or_404(Thing, pk=pk)
    return render(request, 'myApp/thing_detail.html', {'thing': thing})
</code>```

I have two template blocks for each of these views, where I am using template tags to display variables. For example:

```<code><h2 class="title"><a href="{% url 'thing_detail' pk=thing.pk %}">{{ thing.title }}</a></h2>
<p>User: {{ thing.user }}</p>
<div class="date">
    <p>Start Date: {{ thing.start_date }}</p>
</div>
<p>Cost per day: ${{ thing.cost_per_day }}</p>
</code>```

So what is happening here?

Web users can enter what I am calling any number of "Things" with 4 fields: User, Title, Start Date, and Cost per Day. I have TWO calculations that I would like to make, and render them in the template.

Problem 1) The user needs to see how many days have elapsed since they originally entered a Start Date. The calculation will be a subtraction of the current time/date (Now) and the Start Date. I was able to accomplish this by using the Django timesince feature shown here:

```<code><button type="button" class="btn btn-info">{{ thing.quit_date|timesince }}</button>
</code>```

This renders how many days and hours have elapsed - lets call it 'time elapsed' - perfectly. The problem lies in my next calculation.

Problem 2) I need to display a calculation of 'time elapsed' (shown above) multiplied by the Cost per Day variable in the current Model instance. Just for clarity, let's say the start date was 30.5 days ago, and the cost per day is $5.00. I need to multiply 30.5 by $5.00. I would love to simply multiply template tags but I understand that's not how it works. For example:

```<code>{{ thing.quit_date|timesince }} * {{ thing.cost_per_day }}
</code>```

Is there a way to capture the result of this timesince calculation... {{ thing.quit_date|timesince }}... as a variable? I may not be able to use the timesince feature for this calculation.

Once again, what I ultimately need to do here is to multiply the "time elapsed" by the cost per day, like this: (Time Now - Start Date) * (Cost Per Day).

I don't know how to do this in models.py or views.py. I'm looking for the best practice way to do this using Django and Python 3.6. I'm a newbie and I have searched all day for an answer to my particular problem.

Thanks in advance and please let me know if I need to provide more information!

UPDATE

Here is my updated model based on suggestions, albeit not working (the timesince property needs work):

```<code>from django.db import models
from django.utils import timezone
from datetime import datetime

class Thing(models.Model):
quitter = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
quit_date = models.DateTimeField(default=timezone.now)
cost_per_day = models.DecimalField(max_digits=6, decimal_places=2)
notes = models.TextField()

@property
def timesince(self):
    "Time since quit date"
    now = datetime.now()
    then = self.quit_date
    return (now - then)

@property
def savings(self):
    "Savings since quitting"
    return self.timesince * self.cost_per_day
</code>```

Here is my updated template:

```<code><h4>Here are some calculations for this information...</h4>
    <p>Days since you quit:</p>
    <button type="button" class="btn btn-info">{{ thing.timesince }}</button>
    <hr>
    <p>How much money you have saved:</p>
    <button type="button" class="btn btn-info">{{ thing.savings }}</button>
</code>```

I'm certain the problem lies in the subtraction of the dates. Any insight into that would be very helpful. The template variables {{ }} are working, but there is a missing piece in the model.

By the way, when I concatenated "days" to any datetime variable, it game me errors saying .days it gave me errors. Perhaps there is an issue using both a DateTimeField and a datetime.now() instance?

答:
Here is an answer that works. I think the problem was that I was using "datetime.now()" instead of "timezone.now()". This might not be the best way of approaching this in Django/Python. I'd appreciate comments on how to make it "best practice". I really appreciate the assistance on this one!</p>

```<code>@property
def timesince(self):
    "Time since quit date"
    now = timezone.now()
    then = self.quit_date
    return  (now - then).days

@property
def savings(self):
    "Savings since quitting"
    return self.timesince * self.cost_per_day
</code>```

Body:
I am using Django 1.10.7 and Python 3.6.1. First my code, then my questions.

My model looks like this:

class Thing(models.Model):
    user = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    start_date = models.DateTimeField(
        default=timezone.now)
    cost_per_day = models.DecimalField(max_digits=6, decimal_places=2)

Here are my views:

def something_list(request):
    things =Thing.objects.filter(start_date__lte=timezone.now()).order_by('start_date')
    return render(request, 'myApp/something_list.html', {'things': things})

def thing_detail(request, pk):
    thing = get_object_or_404(Thing, pk=pk)
    return render(request, 'myApp/thing_detail.html', {'thing': thing})

I have two template blocks for each of these views, where I am using template tags to display variables. For example:

{{ thing.title }}

User: {{ thing.user }}

Start Date: {{ thing.start_date }}

Cost per day: ${{ thing.cost_per_day }}

So what is happening here?

Web users can enter what I am calling any number of "Things" with 4 fields: User, Title, Start Date, and Cost per Day. I have TWO calculations that I would like to make, and render them in the template.

Problem 1) The user needs to see how many days have elapsed since they originally entered a Start Date. The calculation will be a subtraction of the current time/date (Now) and the Start Date. I was able to accomplish this by using the Django timesince feature shown here:

<button type="button" class="btn btn-info">{{ thing.quit_date|timesince }}</button>

This renders how many days and hours have elapsed - lets call it 'time elapsed' - perfectly. The problem lies in my next calculation.

Problem 2) I need to display a calculation of 'time elapsed' (shown above) multiplied by the Cost per Day variable in the current Model instance. Just for clarity, let's say the start date was 30.5 days ago, and the cost per day is $5.00. I need to multiply 30.5 by $5.00. I would love to simply multiply template tags but I understand that's not how it works. For example:

{{ thing.quit_date|timesince }} * {{ thing.cost_per_day }}

Is there a way to capture the result of this timesince calculation... {{ thing.quit_date|timesince }}... as a variable? I may not be able to use the timesince feature for this calculation.

Once again, what I ultimately need to do here is to multiply the "time elapsed" by the cost per day, like this: (Time Now - Start Date) * (Cost Per Day).

I don't know how to do this in models.py or views.py. I'm looking for the best practice way to do this using Django and Python 3.6. I'm a newbie and I have searched all day for an answer to my particular problem.

Thanks in advance and please let me know if I need to provide more information!

UPDATE

Here is my updated model based on suggestions, albeit not working (the timesince property needs work):

from django.db import models
from django.utils import timezone
from datetime import datetime

class Thing(models.Model):
quitter = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
quit_date = models.DateTimeField(default=timezone.now)
cost_per_day = models.DecimalField(max_digits=6, decimal_places=2)
notes = models.TextField()

@property
def timesince(self):
    "Time since quit date"
    now = datetime.now()
    then = self.quit_date
    return (now - then)

@property
def savings(self):
    "Savings since quitting"
    return self.timesince * self.cost_per_day

Here is my updated template:

Here are some calculations for this information...

Days since you quit:

    <button type="button" class="btn btn-info">{{ thing.timesince }}</button>

How much money you have saved:

    <button type="button" class="btn btn-info">{{ thing.savings }}</button>

I'm certain the problem lies in the subtraction of the dates. Any insight into that would be very helpful. The template variables {{ }} are working, but there is a missing piece in the model.

By the way, when I concatenated "days" to any datetime variable, it game me errors saying .days it gave me errors. Perhaps there is an issue using both a DateTimeField and a datetime.now() instance?

Body:
Here is an answer that works. I think the problem was that I was using "datetime.now()" instead of "timezone.now()". This might not be the best way of approaching this in Django/Python. I'd appreciate comments on how to make it "best practice". I really appreciate the assistance on this one!

@property
def timesince(self):
    "Time since quit date"
    now = timezone.now()
    then = self.quit_date
    return  (now - then).days

@property
def savings(self):
    "Savings since quitting"
    return self.timesince * self.cost_per_day


问:
How would you Unitest this code?
Need some help in Unitestsing.
(Assume I don't have a TypeMock)

Would you change the code in order to inject mocks to substitute EndpointAddress, DiscoveryEndpoint, DiscoveryClient ?

What kind of tests would you write? I can think of

GetService_ServiceExist_ResultShouldBeAnInstance

GetService_ServiceIsNotExist_ResultShouldNull

```<code>static public T GetService<T>(Binding binding, string address)
  {
      Contract.Requires(binding != null);
      Contract.Requires(!string.IsNullOrWhiteSpace(address));

      var endpointAddress= new EndpointAddress(address);
      var discoveryEndpoint = new DiscoveryEndpoint(binding, endpointAddress);

      var discoveryClient = new DiscoveryClient(discoveryEndpoint);

      try
      {
          // Find ICalculatorService endpoints
          FindResponse findResponse = discoveryClient.Find(new FindCriteria(typeof(T)));

          Contract.Assume(findResponse != null);
          Contract.Assume(findResponse.Endpoints != null);

          // Check to see if endpoints were found, if so then invoke the service.););
          if (findResponse.Endpoints.Count > 0)
          {
              Contract.Assume(findResponse.Endpoints[0] != null);

              return ChannelFactory<T>.CreateChannel(new BasicHttpBinding(),
                                                                     findResponse.Endpoints[0].Address);
          }
      }
      catch (TargetInvocationException ex)
      {
          Console.WriteLine("This client was unable to connect to and query the proxy. Ensure that the proxy is up and running: " + ex);
      }
      return default(T);
  }
</code>```

Appreciate any of your help.
Thanks!

Ariel

答:
You have a dependency on EndpointAddress, DiscoveryEndpoint and DiscoveryClient in your method.

First off is I'd put this code into something resembling a factory. I'd also put the above dependencies into factories if necessary and then inject those factories into the class using
IOC.

Then that lets me put fake objects (or mocks) into the system for unit testing and I don't have to rely on a concrete discoveryclient (for example). But if that isn't an issue, I'd still factory it.

You're also looking at finding an endpoint and creating a channel on that or throwing an exception. Well if you stick with the above then do you need to be returning default(T).

Choice here is to either keep the code in there and then throw the exception rather than return null, return null and test for it, make this method only do one thing which is to attempt to create a channel based on a configured DiscoveryClient.

If I was doing it, I'd remove all those dependencies, make it a factory (and the others from factories as necessary) then pass in a configured DiscoveryClient and either return null or return a NullChannel instance.

Then I can do an assert on the instance returned in my test and the creation method only has one responsibility.

HTH

Title: How would you Unitest this code?

Body:
Need some help in Unitestsing.
(Assume I don't have a TypeMock)

Would you change the code in order to inject mocks to substitute EndpointAddress, DiscoveryEndpoint, DiscoveryClient ?

What kind of tests would you write? I can think of

GetService_ServiceExist_ResultShouldBeAnInstance

GetService_ServiceIsNotExist_ResultShouldNull

static public T GetService<T>(Binding binding, string address)
  {
      Contract.Requires(binding != null);
      Contract.Requires(!string.IsNullOrWhiteSpace(address));

      var endpointAddress= new EndpointAddress(address);
      var discoveryEndpoint = new DiscoveryEndpoint(binding, endpointAddress);

      var discoveryClient = new DiscoveryClient(discoveryEndpoint);

      try
      {
          // Find ICalculatorService endpoints
          FindResponse findResponse = discoveryClient.Find(new FindCriteria(typeof(T)));

          Contract.Assume(findResponse != null);
          Contract.Assume(findResponse.Endpoints != null);

          // Check to see if endpoints were found, if so then invoke the service.););
          if (findResponse.Endpoints.Count > 0)
          {
              Contract.Assume(findResponse.Endpoints[0] != null);

              return ChannelFactory<T>.CreateChannel(new BasicHttpBinding(),
                                                                     findResponse.Endpoints[0].Address);
          }
      }
      catch (TargetInvocationException ex)
      {
          Console.WriteLine("This client was unable to connect to and query the proxy. Ensure that the proxy is up and running: " + ex);
      }
      return default(T);
  }

Appreciate any of your help.
Thanks!

Ariel


问:
how can i achieve FibonacciSecret in php
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

```<code><?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>
</code>```

Output

```<code>h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-
</code>```

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

答:
The shortest possible way would be just using the preg_replace and echo string position;</p>

```<code><?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan     Brown';
$message = preg_replace('/\s+/', '', $message);
$strlenggth = strlen($message);
echo $message[$x];
$x = 0;
$y = 1;

for($i=0;$x<=$strlenggth;$i++)
{
$z = $x + $y;
$farray[] = $z;
$x=$y;
$y=$z;
echo "-".$message[$x];
}
?>
</code>```

Body:
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

<?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>

Output

h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

Body:
The shortest possible way would be just using the preg_replace and echo string position;

<?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan     Brown';
$message = preg_replace('/\s+/', '', $message);
$strlenggth = strlen($message);
echo $message[$x];
$x = 0;
$y = 1;

for($i=0;$x<=$strlenggth;$i++)
{
$z = $x + $y;
$farray[] = $z;
$x=$y;
$y=$z;
echo "-".$message[$x];
}
?>


问:
dicom header personal information conversion to a .txt file
I have a series of DICOM Images which I want to anonymize, I found few Matlab codes and some programs which do the job, but none of them export a .txt file of removed personal information. I was wondering if there is a function which can also save removed personal information of a DICOM images in .txt format for features uses. Also, I am trying to create a table which shows the corresponding new images ID to their real name.(subjects real name = personal-information-removed image ID)

Any thoughts?

Thanks for considering my request!

答:
I'm guessing you only want to output to your text file the fields that are changed by anonymization (either modified, removed, or added). First, you may want to modify some dicomanon options to reduce the number of changes, in particular passing the arguments 'WritePrivate', true to ensure private extensions are kept.

First, you can perform the anonymization, saving structures of pre- and post-anonymization metadata using dicominfo:

```<code>preAnonData = dicominfo('input_file.dcm');
dicomanon('input_file.dcm', 'output_file.dcm', 'WritePrivate', true);
postAnonData = dicominfo('output_file.dcm');
</code>```

Then you can use fieldnames and setdiff to find fields that are removed or added by anonymization, and add them to the post-anonymization or pre-anonymization data, respectively, with a nan value as a place holder:

```<code>preFields = fieldnames(preAnonData);
postFields = fieldnames(postAnonData);

removedFields = setdiff(preFields, postFields);
for iField = 1:numel(removedFields)
  postAnonData.(removedFields{iField}) = nan;
end

addedFields = setdiff(postFields, preFields);
for iField = 1:numel(addedFields)
  preAnonData.(addedFields{iField}) = nan;
end
</code>```

It will also be helpful to use orderfields so that both data structures have the same ordering for their field names:

```<code>postAnonData = orderfields(postAnonData, preAnonData);
</code>```

Finally, now that each structure has the same fields in the same order we can use struct2cell to convert their field data to a cell array and use cellfun and isequal to find any fields that have been modified by the anonymization:

```<code>allFields = fieldnames(preAnonData);
preAnonCell = struct2cell(preAnonData);
postAnonCell = struct2cell(postAnonData);
index = ~cellfun(@isequal, preAnonCell, postAnonCell);
modFields = allFields(index);
</code>```

Now you can create a table of the changes like so:

```<code>T = table(modFields, preAnonCell(index), postAnonCell(index), ...
          'VariableNames', {'Field', 'PreAnon', 'PostAnon'});
</code>```

And you could use writetable to easily output the table data to a text file:

```<code>writetable(T, 'anonymized_data.txt');
</code>```

Note, however, that if any of the fields in the table contain vectors or structures of data, the formatting of your output file may look a little funky (i.e. lots of columns, most of them empty, except for those few fields).

Body:
I'm guessing you only want to output to your text file the fields that are changed by anonymization (either modified, removed, or added). First, you may want to modify some dicomanon options to reduce the number of changes, in particular passing the arguments 'WritePrivate', true to ensure private extensions are kept.

First, you can perform the anonymization, saving structures of pre- and post-anonymization metadata using dicominfo:

preAnonData = dicominfo('input_file.dcm');
dicomanon('input_file.dcm', 'output_file.dcm', 'WritePrivate', true);
postAnonData = dicominfo('output_file.dcm');

Then you can use fieldnames and setdiff to find fields that are removed or added by anonymization, and add them to the post-anonymization or pre-anonymization data, respectively, with a nan value as a place holder:

preFields = fieldnames(preAnonData);
postFields = fieldnames(postAnonData);

removedFields = setdiff(preFields, postFields);
for iField = 1:numel(removedFields)
  postAnonData.(removedFields{iField}) = nan;
end

addedFields = setdiff(postFields, preFields);
for iField = 1:numel(addedFields)
  preAnonData.(addedFields{iField}) = nan;
end

It will also be helpful to use orderfields so that both data structures have the same ordering for their field names:

postAnonData = orderfields(postAnonData, preAnonData);

Finally, now that each structure has the same fields in the same order we can use struct2cell to convert their field data to a cell array and use cellfun and isequal to find any fields that have been modified by the anonymization:

allFields = fieldnames(preAnonData);
preAnonCell = struct2cell(preAnonData);
postAnonCell = struct2cell(postAnonData);
index = ~cellfun(@isequal, preAnonCell, postAnonCell);
modFields = allFields(index);

Now you can create a table of the changes like so:

T = table(modFields, preAnonCell(index), postAnonCell(index), ...
          'VariableNames', {'Field', 'PreAnon', 'PostAnon'});

And you could use writetable to easily output the table data to a text file:

writetable(T, 'anonymized_data.txt');

Note, however, that if any of the fields in the table contain vectors or structures of data, the formatting of your output file may look a little funky (i.e. lots of columns, most of them empty, except for those few fields).


问:
Alternative way to code without loops in R and reduce looping time
I have 2 datasets with text data. dataset1: clusters11 and dataset2: transactns11. I am using For loop in the code and it takes more time to process the data. So can anyone suggest how I can reduce the time taken. Please go through the below sample datasets and the code I am using.

```<code>dataset1: clusters11
cluster_id  clusters
1   A,B,C
2   A,B
3   B,C
4   C,D,E
5   B,C,D
6   D,E,F
7   A,D,F
8   B,G,H
9   B,C,F
10  G,H,M
11  A,H,N
12  B,C,M

dataset2: transactns11
unique_id   skills
221 A,B,C
223 A,B
224 B,C
225 C,D,E,F
226 B,C,D,M
227 D,E,F,A
228 A,D,F
229 B,G,H
230 B,C,F,A
231 G,H,M
232 A,H,N
233 B,C,M
234 A,B,C
235 A,B
236 B,C
237 C,D,E
238 B,C,D
239 D,E,F
</code>```

I want to have my output:out_df like this( which ever cluster in clusters11 file matches 100% with the skills in transactns11 should appear as comma separate by cluster_id, with the column name matching_values in the output.

```<code>unique_id   skills  matching_values
221 A,B,C   1,2,3
223 A,B 2
224 B,C 3
225 C,D,E,F 4,6
226 B,C,D,M 3,5,12
227 D,E,F,A 6,7
228 A,D,F   7
229 B,G,H   8
230 B,C,F,A 1,2,3,9
231 G,H,M   10
232 A,H,N   11
233 B,C,M   3,12
234 A,B,C   1,2,3
235 A,B 2
236 B,C 3
237 C,D,E   4
238 B,C,D   3,5
239 D,E,F   6
</code>```

For this I have code and it is working fine with me

```<code>  out_df <- data.frame(matrix(0, ncol = 3, nrow = nrow(transactns11)))
  colnames(out_df) <- c("unique_id", "skills", "matching_values")

  transactns11$skills=as.character(transactns11$skills)
  clusters11$clusters=as.character(clusters11$clusters)

  for(n in 1:nrow(transactns11)) {

    trans1 <- strsplit(transactns11$skills[n], ",")
    trans1
    transvect <- unlist(trans1)
    transvect

    matching_clusters <- c("")
    out_df$unique_id[n] <- as.character(transactns11$unique_id[n])
    out_df$skills[n] <- transactns11$skills[n]

    for(i in 1:nrow(clusters11)) {

      cluster1 <- strsplit(clusters11$clusters[i],",")
      cluster1
      clustervect <- unlist(cluster1)
      clustervect

      if(length(intersect(transvect,clustervect)) == length(clustervect)) {
        matching_clusters <- paste(matching_clusters, clusters11$cluster_id[i], sep = ",")
      }
    }
    matching_clusters <- substring(matching_clusters,2)
    out_df$matching_values[n] <- matching_clusters
  }
</code>```

Problem is that, the code takes more time when the recods of the 2 files are more like 10000 or 20000( time taken will be 15 to 20 hrs).
Can any one please suggest how I can avoid this loops or any other method I can follow to improve the code and reduce the huge time taken to process.
Thanks in Advance.
Regards,
hari

答:
This solution uses functions from dplyr, tidyr, and purrr. So I loaded the tidyverse package for all these functions. dt_final would be the final output.

```<code># Load package
library(tidyverse)

# Separate the skills and cluster letters
dt1_update <- clusters11 %>%
  mutate(Group = strsplit(clusters, split = ",")) %>%
  unnest(Group) %>%
  select(-clusters)

dt2_update <- transactns11 %>%
  mutate(Group = strsplit(skills, split = ",")) %>%
  unnest(Group) %>%
  select(-skills)

# Split the data frame
dt1_list <- split(dt1_update, f = dt1_update$cluster_id)
dt2_list <- split(dt2_update, f = dt2_update$unique_id)

# Design a function to determine if the Group elements matched

# df1 is data frame from dt1_list, df2 is data frame from dt2_list
is.match <- function(df1, df2){

  if (all(df1$Group %in% df2$Group)){
    return(TRUE)
  } else {
    return(FALSE)
  }
}

# Design a function to return the ID
id.return <- function(df2, df1_list){
  answer <- map(df1_list, .f = is.match, df2 = df2)
  answer <- names(which(unlist(answer)))
  return(paste(answer, collapse = ","))
}

# Design a function to apply all the id.return function to all combination
id.check <- function(df2_list, df1_list){
  return(map_chr(df2_list, .f = id.return, df1_list = df1_list))
}

# Apply the id.check function
dt_final <- transactns11 %>%
  mutate(matching_values = id.check(dt2_list, dt1_list))
</code>```

Data

```<code># Create example data frame 1
clusters11 <- read.table(text = "cluster_id  clusters
1   A,B,C
                 2   A,B
                 3   B,C
                 4   C,D,E
                 5   B,C,D
                 6   D,E,F
                 7   A,D,F
                 8   B,G,H
                 9   B,C,F
                 10  G,H,M
                 11  A,H,N
                 12  B,C,M",
                 header = TRUE, stringsAsFactors = FALSE)

# Create example data frame 2
transactns11 <- read.table(text = "unique_id   skills
221 A,B,C
                  223 A,B
                  224 B,C
                  225 C,D,E,F
                  226 B,C,D,M
                  227 D,E,F,A
                  228 A,D,F
                  229 B,G,H
                  230 B,C,F,A
                  231 G,H,M
                  232 A,H,N
                  233 B,C,M
                  234 A,B,C
                  235 A,B
                  236 B,C
                  237 C,D,E
                  238 B,C,D
                  239 D,E,F",
                  header = TRUE, stringsAsFactors = FALSE)
</code>```

Update

The above code can solve OP's original question. However, based on the OP's comment, the real datasets has random cluster_id and unique_id. So I decide to update my answer to be able to generalize the use of this approach.

Basically, the random cluster_id should not be an issue if the id.return function can return the right ID. The key to deal with random unique_id is to sort the data frame by unique_id before applying the function. Below is the updated code.

Data Preparation

This part is the same. However, to simulate the OP's real world data, I randomized the transactns11 data frame and create a sorting_id to restore the order of the data frame after the applying the function.

```<code># Load package
library(tidyverse)

# Create example data frame 1
clusters11 <- read.table(text = "cluster_id  clusters
                         1   A,B,C
                         2   A,B
                         3   B,C
                         4   C,D,E
                         5   B,C,D
                         6   D,E,F
                         7   A,D,F
                         8   B,G,H
                         9   B,C,F
                         10  G,H,M
                         11  A,H,N
                         12  B,C,M",
                 header = TRUE, stringsAsFactors = FALSE)

# Create example data frame 2
transactns11 <- read.table(text = "unique_id   skills
                           221 A,B,C
                           223 A,B
                           224 B,C
                           225 C,D,E,F
                           226 B,C,D,M
                           227 D,E,F,A
                           228 A,D,F
                           229 B,G,H
                           230 B,C,F,A
                           231 G,H,M
                           232 A,H,N
                           233 B,C,M
                           234 A,B,C
                           235 A,B
                           236 B,C
                           237 C,D,E
                           238 B,C,D
                           239 D,E,F",
                  header = TRUE, stringsAsFactors = FALSE)
</code>```

Based on the OP's update, randomize the rows to simulate real condition

```<code># Set seed for reproducibility
set.seed(123)

transactns11 <- transactns11 %>%
  # Ransomize the rows
  sample_n(size = nrow(.))
</code>```

Now transactns11 looks like this.

```<code>   unique_id  skills
6        227 D,E,F,A
14       235     A,B
7        228   A,D,F
17       238   B,C,D
15       236     B,C
1        221   A,B,C
16       237   C,D,E
10       231   G,H,M
18       239   D,E,F
5        226 B,C,D,M
8        229   B,G,H
4        225 C,D,E,F
9        230 B,C,F,A
3        224     B,C
13       234   A,B,C
11       232   A,H,N
12       233   B,C,M
2        223     A,B
</code>```

It is important to create the sorting_id

```<code>transactns11 <- transactns11 %>%
  # Create a sorting ID
  mutate(sorting_id = 1:n())
</code>```

The transactns11 looks like this now.

```<code>   unique_id  skills sorting_id
1        227 D,E,F,A          1
2        235     A,B          2
3        228   A,D,F          3
4        238   B,C,D          4
5        236     B,C          5
6        221   A,B,C          6
7        237   C,D,E          7
8        231   G,H,M          8
9        239   D,E,F          9
10       226 B,C,D,M         10
11       229   B,G,H         11
12       225 C,D,E,F         12
13       230 B,C,F,A         13
14       224     B,C         14
15       234   A,B,C         15
16       232   A,H,N         16
17       233   B,C,M         17
18       223     A,B         18
</code>```

Find the matching ID

Now run the following code. The only important update here is to sort the transactns11 by unique_id when creating dt2_update

```<code># Separate the skills and cluster letters
dt1_update <- clusters11 %>%
  mutate(Group = strsplit(clusters, split = ",")) %>%
  unnest(Group) %>%
  select(-clusters)

dt2_update <- transactns11  %>%
  # Sort the data frame by unique_id
  arrange(unique_id) %>%
  mutate(Group = strsplit(skills, split = ",")) %>%
  unnest(Group) %>%
  select(-skills)

# Split the data frame
dt1_list <- split(dt1_update, f = dt1_update$cluster_id)
dt2_list <- split(dt2_update, f = dt2_update$unique_id)

# Design a function to determine if the Group elements matched

# df1 is data frame from dt1_list, df2 is data frame from dt2_list
is.match <- function(df1, df2){

  if (all(df1$Group %in% df2$Group)){
    return(TRUE)
  } else {
    return(FALSE)
  }
}

# Design a function to return the ID
id.return <- function(df2, df1_list){
  answer <- map(df1_list, .f = is.match, df2 = df2)
  answer <- names(which(unlist(answer)))
  return(paste(answer, collapse = ","))
}

# Design a function to apply all the id.return function to all combination
id.check <- function(df2_list, df1_list){
  return(map_chr(df2_list, .f = id.return, df1_list = df1_list))
}
</code>```

Now apply the id.check function. Notice that before doing that, it is necessary to sort the data frame by unique_id. After completing the matching, sort the data frame by sorting_id to restore the original order.

```<code># Apply the id.check function
dt_final <- transactns11 %>%
  # Sort the data frame by unique_id
  arrange(unique_id) %>%
  mutate(matching_values = id.check(dt2_list, dt1_list)) %>%
  # Sort the data frame by sorting_id
  arrange(sorting_id) %>%
  select(-sorting_id)
</code>```

Here is the final output.

```<code>   unique_id  skills matching_values
1        227 D,E,F,A             6,7
2        235     A,B               2
3        228   A,D,F               7
4        238   B,C,D             3,5
5        236     B,C               3
6        221   A,B,C           1,2,3
7        237   C,D,E               4
8        231   G,H,M              10
9        239   D,E,F               6
10       226 B,C,D,M          3,5,12
11       229   B,G,H               8
12       225 C,D,E,F             4,6
13       230 B,C,F,A         1,2,3,9
14       224     B,C               3
15       234   A,B,C           1,2,3
16       232   A,H,N              11
17       233   B,C,M            3,12
18       223     A,B               2
</code>```

Body:
I have 2 datasets with text data. dataset1: clusters11 and dataset2: transactns11. I am using For loop in the code and it takes more time to process the data. So can anyone suggest how I can reduce the time taken. Please go through the below sample datasets and the code I am using.

dataset1: clusters11
cluster_id  clusters
1   A,B,C
2   A,B
3   B,C
4   C,D,E
5   B,C,D
6   D,E,F
7   A,D,F
8   B,G,H
9   B,C,F
10  G,H,M
11  A,H,N
12  B,C,M

dataset2: transactns11
unique_id   skills
221 A,B,C
223 A,B
224 B,C
225 C,D,E,F
226 B,C,D,M
227 D,E,F,A
228 A,D,F
229 B,G,H
230 B,C,F,A
231 G,H,M
232 A,H,N
233 B,C,M
234 A,B,C
235 A,B
236 B,C
237 C,D,E
238 B,C,D
239 D,E,F

I want to have my output:out_df like this( which ever cluster in clusters11 file matches 100% with the skills in transactns11 should appear as comma separate by cluster_id, with the column name matching_values in the output.

unique_id   skills  matching_values
221 A,B,C   1,2,3
223 A,B 2
224 B,C 3
225 C,D,E,F 4,6
226 B,C,D,M 3,5,12
227 D,E,F,A 6,7
228 A,D,F   7
229 B,G,H   8
230 B,C,F,A 1,2,3,9
231 G,H,M   10
232 A,H,N   11
233 B,C,M   3,12
234 A,B,C   1,2,3
235 A,B 2
236 B,C 3
237 C,D,E   4
238 B,C,D   3,5
239 D,E,F   6

For this I have code and it is working fine with me

  out_df <- data.frame(matrix(0, ncol = 3, nrow = nrow(transactns11)))
  colnames(out_df) <- c("unique_id", "skills", "matching_values")

  transactns11$skills=as.character(transactns11$skills)
  clusters11$clusters=as.character(clusters11$clusters)

  for(n in 1:nrow(transactns11)) {

    trans1 <- strsplit(transactns11$skills[n], ",")
    trans1
    transvect <- unlist(trans1)
    transvect

    matching_clusters <- c("")
    out_df$unique_id[n] <- as.character(transactns11$unique_id[n])
    out_df$skills[n] <- transactns11$skills[n]

    for(i in 1:nrow(clusters11)) {

      cluster1 <- strsplit(clusters11$clusters[i],",")
      cluster1
      clustervect <- unlist(cluster1)
      clustervect

      if(length(intersect(transvect,clustervect)) == length(clustervect)) {
        matching_clusters <- paste(matching_clusters, clusters11$cluster_id[i], sep = ",")
      }
    }
    matching_clusters <- substring(matching_clusters,2)
    out_df$matching_values[n] <- matching_clusters
  }

Problem is that, the code takes more time when the recods of the 2 files are more like 10000 or 20000( time taken will be 15 to 20 hrs).
Can any one please suggest how I can avoid this loops or any other method I can follow to improve the code and reduce the huge time taken to process.
Thanks in Advance.
Regards,
hari

Body:
This solution uses functions from dplyr, tidyr, and purrr. So I loaded the tidyverse package for all these functions. dt_final would be the final output.

# Load package
library(tidyverse)

# Separate the skills and cluster letters
dt1_update <- clusters11 %>%
  mutate(Group = strsplit(clusters, split = ",")) %>%
  unnest(Group) %>%
  select(-clusters)

dt2_update <- transactns11 %>%
  mutate(Group = strsplit(skills, split = ",")) %>%
  unnest(Group) %>%
  select(-skills)

# Split the data frame
dt1_list <- split(dt1_update, f = dt1_update$cluster_id)
dt2_list <- split(dt2_update, f = dt2_update$unique_id)

# Design a function to determine if the Group elements matched

# df1 is data frame from dt1_list, df2 is data frame from dt2_list
is.match <- function(df1, df2){

  if (all(df1$Group %in% df2$Group)){
    return(TRUE)
  } else {
    return(FALSE)
  }
}

# Design a function to return the ID
id.return <- function(df2, df1_list){
  answer <- map(df1_list, .f = is.match, df2 = df2)
  answer <- names(which(unlist(answer)))
  return(paste(answer, collapse = ","))
}

# Design a function to apply all the id.return function to all combination
id.check <- function(df2_list, df1_list){
  return(map_chr(df2_list, .f = id.return, df1_list = df1_list))
}

# Apply the id.check function
dt_final <- transactns11 %>%
  mutate(matching_values = id.check(dt2_list, dt1_list))

Data

# Create example data frame 1
clusters11 <- read.table(text = "cluster_id  clusters
1   A,B,C
                 2   A,B
                 3   B,C
                 4   C,D,E
                 5   B,C,D
                 6   D,E,F
                 7   A,D,F
                 8   B,G,H
                 9   B,C,F
                 10  G,H,M
                 11  A,H,N
                 12  B,C,M",
                 header = TRUE, stringsAsFactors = FALSE)

# Create example data frame 2
transactns11 <- read.table(text = "unique_id   skills
221 A,B,C
                  223 A,B
                  224 B,C
                  225 C,D,E,F
                  226 B,C,D,M
                  227 D,E,F,A
                  228 A,D,F
                  229 B,G,H
                  230 B,C,F,A
                  231 G,H,M
                  232 A,H,N
                  233 B,C,M
                  234 A,B,C
                  235 A,B
                  236 B,C
                  237 C,D,E
                  238 B,C,D
                  239 D,E,F",
                  header = TRUE, stringsAsFactors = FALSE)

Update

The above code can solve OP's original question. However, based on the OP's comment, the real datasets has random cluster_id and unique_id. So I decide to update my answer to be able to generalize the use of this approach.

Basically, the random cluster_id should not be an issue if the id.return function can return the right ID. The key to deal with random unique_id is to sort the data frame by unique_id before applying the function. Below is the updated code.

Data Preparation

This part is the same. However, to simulate the OP's real world data, I randomized the transactns11 data frame and create a sorting_id to restore the order of the data frame after the applying the function.

# Load package
library(tidyverse)

# Create example data frame 1
clusters11 <- read.table(text = "cluster_id  clusters
                         1   A,B,C
                         2   A,B
                         3   B,C
                         4   C,D,E
                         5   B,C,D
                         6   D,E,F
                         7   A,D,F
                         8   B,G,H
                         9   B,C,F
                         10  G,H,M
                         11  A,H,N
                         12  B,C,M",
                 header = TRUE, stringsAsFactors = FALSE)

# Create example data frame 2
transactns11 <- read.table(text = "unique_id   skills
                           221 A,B,C
                           223 A,B
                           224 B,C
                           225 C,D,E,F
                           226 B,C,D,M
                           227 D,E,F,A
                           228 A,D,F
                           229 B,G,H
                           230 B,C,F,A
                           231 G,H,M
                           232 A,H,N
                           233 B,C,M
                           234 A,B,C
                           235 A,B
                           236 B,C
                           237 C,D,E
                           238 B,C,D
                           239 D,E,F",
                  header = TRUE, stringsAsFactors = FALSE)

Based on the OP's update, randomize the rows to simulate real condition

# Set seed for reproducibility
set.seed(123)

transactns11 <- transactns11 %>%
  # Ransomize the rows
  sample_n(size = nrow(.))

Now transactns11 looks like this.

   unique_id  skills
6        227 D,E,F,A
14       235     A,B
7        228   A,D,F
17       238   B,C,D
15       236     B,C
1        221   A,B,C
16       237   C,D,E
10       231   G,H,M
18       239   D,E,F
5        226 B,C,D,M
8        229   B,G,H
4        225 C,D,E,F
9        230 B,C,F,A
3        224     B,C
13       234   A,B,C
11       232   A,H,N
12       233   B,C,M
2        223     A,B

It is important to create the sorting_id

transactns11 <- transactns11 %>%
  # Create a sorting ID
  mutate(sorting_id = 1:n())

The transactns11 looks like this now.

   unique_id  skills sorting_id
1        227 D,E,F,A          1
2        235     A,B          2
3        228   A,D,F          3
4        238   B,C,D          4
5        236     B,C          5
6        221   A,B,C          6
7        237   C,D,E          7
8        231   G,H,M          8
9        239   D,E,F          9
10       226 B,C,D,M         10
11       229   B,G,H         11
12       225 C,D,E,F         12
13       230 B,C,F,A         13
14       224     B,C         14
15       234   A,B,C         15
16       232   A,H,N         16
17       233   B,C,M         17
18       223     A,B         18

Find the matching ID

Now run the following code. The only important update here is to sort the transactns11 by unique_id when creating dt2_update

# Separate the skills and cluster letters
dt1_update <- clusters11 %>%
  mutate(Group = strsplit(clusters, split = ",")) %>%
  unnest(Group) %>%
  select(-clusters)

dt2_update <- transactns11  %>%
  # Sort the data frame by unique_id
  arrange(unique_id) %>%
  mutate(Group = strsplit(skills, split = ",")) %>%
  unnest(Group) %>%
  select(-skills)

# Split the data frame
dt1_list <- split(dt1_update, f = dt1_update$cluster_id)
dt2_list <- split(dt2_update, f = dt2_update$unique_id)

# Design a function to determine if the Group elements matched

# df1 is data frame from dt1_list, df2 is data frame from dt2_list
is.match <- function(df1, df2){

  if (all(df1$Group %in% df2$Group)){
    return(TRUE)
  } else {
    return(FALSE)
  }
}

# Design a function to return the ID
id.return <- function(df2, df1_list){
  answer <- map(df1_list, .f = is.match, df2 = df2)
  answer <- names(which(unlist(answer)))
  return(paste(answer, collapse = ","))
}

# Design a function to apply all the id.return function to all combination
id.check <- function(df2_list, df1_list){
  return(map_chr(df2_list, .f = id.return, df1_list = df1_list))
}

Now apply the id.check function. Notice that before doing that, it is necessary to sort the data frame by unique_id. After completing the matching, sort the data frame by sorting_id to restore the original order.

# Apply the id.check function
dt_final <- transactns11 %>%
  # Sort the data frame by unique_id
  arrange(unique_id) %>%
  mutate(matching_values = id.check(dt2_list, dt1_list)) %>%
  # Sort the data frame by sorting_id
  arrange(sorting_id) %>%
  select(-sorting_id)

Here is the final output.

   unique_id  skills matching_values
1        227 D,E,F,A             6,7
2        235     A,B               2
3        228   A,D,F               7
4        238   B,C,D             3,5
5        236     B,C               3
6        221   A,B,C           1,2,3
7        237   C,D,E               4
8        231   G,H,M              10
9        239   D,E,F               6
10       226 B,C,D,M          3,5,12
11       229   B,G,H               8
12       225 C,D,E,F             4,6
13       230 B,C,F,A         1,2,3,9
14       224     B,C               3
15       234   A,B,C           1,2,3
16       232   A,H,N              11
17       233   B,C,M            3,12
18       223     A,B               2


问:
Extract fields and values from text line using C++
I am reading in a text file with lines of the format:

```<code>date    =20170422,line    =10,index   =3,field   =partType,lock    =productCode1,bookmark=2/19/56,
</code>```

I need to extract the name of the field (date, line, index, etc.) and its corresponding value into char field[] and char value[] variables.  If necessary, I am allowed to modify the format of the lines.

My initial thinking was to use while loops and check for = and , characters but it was getting messy and it seems like there may be a cleaner way.

答:
You could do something like the below example. Split the string by commas using getline from your file, then split use an istringstream to and getline to split it again by an equals sign.</p>

```<code>#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
int main()
{
        std::ifstream file("test.txt");
        std::string wholeLine, partOfLine;
        while(std::getline(file, wholeLine, ',')) {
                std::istringstream wholeLineSS(wholeLine);
                while(std::getline(wholeLineSS, partOfLine, '=')) {
                        std::cout<<partOfLine<<std::endl;
                }
        }
        return 0;
}
</code>```

Body:
I am reading in a text file with lines of the format:

date    =20170422,line    =10,index   =3,field   =partType,lock    =productCode1,bookmark=2/19/56,

I need to extract the name of the field (date, line, index, etc.) and its corresponding value into char field[] and char value[] variables.  If necessary, I am allowed to modify the format of the lines.

My initial thinking was to use while loops and check for = and , characters but it was getting messy and it seems like there may be a cleaner way.

Body:
You could do something like the below example. Split the string by commas using getline from your file, then split use an istringstream to and getline to split it again by an equals sign.

#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
int main()
{
        std::ifstream file("test.txt");
        std::string wholeLine, partOfLine;
        while(std::getline(file, wholeLine, ',')) {
                std::istringstream wholeLineSS(wholeLine);
                while(std::getline(wholeLineSS, partOfLine, '=')) {
                        std::cout<<partOfLine<<std::endl;
                }
        }
        return 0;
}


问:
Inserting Select from HTML to mysql
so i have this table in my html

```<code><form method = "POST" action="admin_event.php">
<table class = "table" id="dynamic_admin_add_price">
                                                        <thead>
                                                        <th>Deadline </th>
                                                        <th>Register Date</th>
                                                        <th>Price</th>
                                                        <th></th>
                                                        <th></th>
                                                        </thead>

                                                        <tbody>
                                                        <tr>
                                                            <td>
                                                                <select name="admin_add_deadline[]" class="form-control">
                                                                    <option value="early_bird">Early Bird</option>
                                                                    <option value="middle">Middle</option>
                                                                    <option value="normal">Normal</option>
                                                                </select>
                                                            </td>
                                                            <td><input type="text" name="admin_add_register_date[]" class="form-control registerDate" required></td>
                                                            <td><label>Rp.</label></td>
                                                            <td><input type="number" name="admin_add_price[]" class="form-control" value=""  required></td>
                                                            <td><button type="submit" name="button_add_price" id="price" class="btn btn-success">Add more deadlines</button></td>
                                                            <!--<td><button type="button" name=button_remove_event_time id="remove_event-time" class="btn btn-danger" disabled>Remove</button></td>-->
                                                        </tr>
                                                        </tbody>
                                                    </table>

 <button type="submit" class="btn btn-primary" name="admin_add_event_datas">Save</button>
</form>
</code>```

And i have created the javascript so that the user can add as many rows as they want

```<code>    $('#add_price').click(function(){
    j++;
    $('#dynamic_admin_add_price').append(
        '<tr id="row2'+j+'">' +
        '<td><select name="admin_add_deadline[]" class="form-control"><option value="early_bird">Early Bird</option><option value="middle">Middle</option><option value="normal">Normal</option></select></td>'+
        '<td><input type="text" name="admin_add_register_date[]" class="form-control registerDate" required></td>' +
        '<td><label>Rp.</label></td>' +
        '<td><input type="number" name="admin_add_price[]" class="form-control" value="" required></td>' +
        '<td><button type="submit" name="button_remove_event_time" id="'+j+'" class="btn btn-danger btn_remove2" required>Remove</button></td>' +
        '</tr>');
});

$(document).on('click', '.btn_remove2', function(){
    var button_id = $(this).attr("id");
    $('#row2'+button_id+'').remove();
});
</code>```

The adding rows work fine and the rest of the data can be inputted into the mysql, EXCEPT for the select fields,where it returns incorrectly and doesn't get any input at all from the non-static rows.

What i want to do is that if the user chose early bird, it gave the number 1 in the php, 2 for the middle option, and 3 for the normal ones, as it matches the id_deadline in another table that is used as the foreign key in the table i want to insert the data to. This is the snippet of the php script(i only put the one for the deadline):

```<code>if(isset($_POST['admin_add_deadline'])){
$deadline = $_POST['admin_add_deadline'];

$one = 1;
$two = 2;
$three = 3;
if($deadline == 'early_bird'){

        $deadline = $one;
}

if($deadline == 'middle'){
        $deadline = $two;
}

else{
$deadline = $three
}

}
</code>```

and this is the foreach to insert the data

```<code>    foreach ($register_date as $key => $value) {

    $post_register_date = $db->real_escape_string($value);

    $post_insert_price = $db->real_escape_string($register_price[$key]);

    $post_deadline = $deadline[$key];

    $query = "INSERT INTO register_time(id_event, id_deadline, register_date, price, created_at, status)
                          VALUES('$row_id_event','$post_deadline', '$post_register_date', '$post_insert_price', '$time', '$status')";

    if(mysqli_query($db, $query)){
        $succ = "New record created successfully";
    }

    else{
        echo "Error: " . $query . "<br>" . mysqli_error($db);
    }

}
</code>```

Again, the problem is that if i have 3 rows generated and i clicked the submit button, the inserted value for the id_deadline column in the table will always be 3 for the first row, and the other 2 rows will return an error as the value is '' for the id_deadline in the insert query

Can you guys help me with this problem?Thank you, i hope my question is clear enough.

EDIT: Fixing the typos

答:
As far as I can tell at this moment in third snippet you overriding $deadline variable with number, then you are using it in 4-th snippet as an array.

Your snippets are too sparse too say anything more, sorry...

Title: Inserting Select from HTML to mysql

Body:
so i have this table in my html

<form method = "POST" action="admin_event.php">

                                                        Deadline
                                                        Register Date
                                                        Price

                                                                <select name="admin_add_deadline[]" class="form-control">
                                                                    <option value="early_bird">Early Bird</option>
                                                                    <option value="middle">Middle</option>
                                                                    <option value="normal">Normal</option>
                                                                </select>

                                                            <input type="text" name="admin_add_register_date[]" class="form-control registerDate" required>
                                                            Rp.
                                                            <input type="number" name="admin_add_price[]" class="form-control" value=""  required>
                                                            <button type="submit" name="button_add_price" id="price" class="btn btn-success">Add more deadlines</button>

 <button type="submit" class="btn btn-primary" name="admin_add_event_datas">Save</button>
</form>

And i have created the javascript so that the user can add as many rows as they want

    $('#add_price').click(function(){
    j++;
    $('#dynamic_admin_add_price').append(
        '
' +
        '<select name="admin_add_deadline[]" class="form-control"><option value="early_bird">Early Bird</option><option value="middle">Middle</option><option value="normal">Normal</option></select>	'+
        '<input type="text" name="admin_add_register_date[]" class="form-control registerDate" required>	' +
        'Rp.	' +
        '<input type="number" name="admin_add_price[]" class="form-control" value="" required>	' +
        '<button type="submit" name="button_remove_event_time" id="'+j+'" class="btn btn-danger btn_remove2" required>Remove</button>	' +
        '
');
});

$(document).on('click', '.btn_remove2', function(){
    var button_id = $(this).attr("id");
    $('#row2'+button_id+'').remove();
});

The adding rows work fine and the rest of the data can be inputted into the mysql, EXCEPT for the select fields,where it returns incorrectly and doesn't get any input at all from the non-static rows.

What i want to do is that if the user chose early bird, it gave the number 1 in the php, 2 for the middle option, and 3 for the normal ones, as it matches the id_deadline in another table that is used as the foreign key in the table i want to insert the data to. This is the snippet of the php script(i only put the one for the deadline):

if(isset($_POST['admin_add_deadline'])){
$deadline = $_POST['admin_add_deadline'];

$one = 1;
$two = 2;
$three = 3;
if($deadline == 'early_bird'){

        $deadline = $one;
}

if($deadline == 'middle'){
        $deadline = $two;
}

else{
$deadline = $three
}

}

and this is the foreach to insert the data

    foreach ($register_date as $key => $value) {

    $post_register_date = $db->real_escape_string($value);

    $post_insert_price = $db->real_escape_string($register_price[$key]);

    $post_deadline = $deadline[$key];

    $query = "INSERT INTO register_time(id_event, id_deadline, register_date, price, created_at, status)
                          VALUES('$row_id_event','$post_deadline', '$post_register_date', '$post_insert_price', '$time', '$status')";

    if(mysqli_query($db, $query)){
        $succ = "New record created successfully";
    }

    else{
        echo "Error: " . $query . "
" . mysqli_error($db);
    }

}

Again, the problem is that if i have 3 rows generated and i clicked the submit button, the inserted value for the id_deadline column in the table will always be 3 for the first row, and the other 2 rows will return an error as the value is '' for the id_deadline in the insert query

Can you guys help me with this problem?Thank you, i hope my question is clear enough.

EDIT: Fixing the typos


问:
Rails subrouting question
Hiya everyone!
I need to put off some subroutes in a specific part of an application.
The subroutes shouldbe something like this

```<code>map.connect ':wildcard/:controller/:id/:action' , :controller => 'my_fancy_controller'
</code>```

problem is , it's not working. putting anything behind :controller will not help.

Environment is rails 2.3.10, not 3 :-).

Someone has some suggestion?

答:
Apparently the answer was very very simple.

```<code>map.connect 'my_fancy_controller/:wildcard/sub_controller/:id/:action', :controller => 'my_fancy_controller/sub_controller'
</code>```

In this way i can use my_fancy_controller and sub_controller as static text in the url, declaring them in the :controller field.

Is not rest, but it's the way my job have to be done, so i'm sorry for you purists!

Title: Rails subrouting question

Body:
Hiya everyone!
I need to put off some subroutes in a specific part of an application.
The subroutes shouldbe something like this

map.connect ':wildcard/:controller/:id/:action' , :controller => 'my_fancy_controller'

problem is , it's not working. putting anything behind :controller will not help.

Environment is rails 2.3.10, not 3 :-).

Someone has some suggestion?

Body:
Apparently the answer was very very simple.

map.connect 'my_fancy_controller/:wildcard/sub_controller/:id/:action', :controller => 'my_fancy_controller/sub_controller'

In this way i can use my_fancy_controller and sub_controller as static text in the url, declaring them in the :controller field.

Is not rest, but it's the way my job have to be done, so i'm sorry for you purists!


问:
Need some help understanding private / protected / public inheritance
Currently, I am learning OOP, and I've tried many inheritance examples. I just tested this code:

```<code>#include <iostream>
using namespace std;

class B
{
    int a;
protected:
    B(int i=0)
    {
        a=i;
    }

    int get_b()
    {
        return a;
    }
};

class D: private B
{
public:
    D(int x=0): B(x) {}

    int get_a()
    {
        return get_b();
    }
};

int main()
{
    D d(-89);
    cout << d.get_a();
    return 0;
}
</code>```

Why does this work? Why can I use the get_b() function? Why does the constructor B(x) work? Why doesn't it work if I change protected to private then?

Later Edit : By using the protected keyword on the constructor and function get_b() means that derived classes have acces to them if the inheritance is public. However, in this case by using private inheritance I would expect that the constructor and the get_b() function would be inaccesible from class D.

答:
In effect, public, protected, and private inheritance specifies the most liberal access control that will apply to inherited members. What I mean:

Public

```<code>class Pub : public B
</code>```

Public members of B inherited by Pub will be accessible both within Pub itself and from outside (as well as from any classes derived from Pub). Protected members of B inherited by Pub will be accessible within Pub and within classes derived from Pub. Private members of B will not be accessible within Pub.

Another way to put it: B's public members remain public, protected members remain protected, private members are inaccessible.

Protected

```<code>class Prot : protected B
</code>```

Public and protected members of B inherited by Prot will be accesible like protected members of Prot: within the class itself and in classes derived from it, but not from outside. Private members of B are still not accessible to Prot.

Another way to put it: B's public members become protected, protected members remain protected, private members are inaccessible.

Private

```<code>class Priv : private B
</code>```

Public and protected members of B inherited by Priv will be accessible to Priv only, and not to any derived classes (they are accessible just like private members of Priv). Private members of B are still not accessible to Prot.

Another way to put it: B's public and protected members become private, private members are inaccessible.

Body:
Currently, I am learning OOP, and I've tried many inheritance examples. I just tested this code:

#include <iostream>
using namespace std;

class B
{
    int a;
protected:
    B(int i=0)
    {
        a=i;
    }

    int get_b()
    {
        return a;
    }
};

class D: private B
{
public:
    D(int x=0): B(x) {}

    int get_a()
    {
        return get_b();
    }
};

int main()
{
    D d(-89);
    cout << d.get_a();
    return 0;
}

Why does this work? Why can I use the get_b() function? Why does the constructor B(x) work? Why doesn't it work if I change protected to private then?

Later Edit : By using the protected keyword on the constructor and function get_b() means that derived classes have acces to them if the inheritance is public. However, in this case by using private inheritance I would expect that the constructor and the get_b() function would be inaccesible from class D.

Body:
In effect, public, protected, and private inheritance specifies the most liberal access control that will apply to inherited members. What I mean:

Public

class Pub : public B

Public members of B inherited by Pub will be accessible both within Pub itself and from outside (as well as from any classes derived from Pub). Protected members of B inherited by Pub will be accessible within Pub and within classes derived from Pub. Private members of B will not be accessible within Pub.

Another way to put it: B's public members remain public, protected members remain protected, private members are inaccessible.

Protected

class Prot : protected B

Public and protected members of B inherited by Prot will be accesible like protected members of Prot: within the class itself and in classes derived from it, but not from outside. Private members of B are still not accessible to Prot.

Another way to put it: B's public members become protected, protected members remain protected, private members are inaccessible.

Private

class Priv : private B

Public and protected members of B inherited by Priv will be accessible to Priv only, and not to any derived classes (they are accessible just like private members of Priv). Private members of B are still not accessible to Prot.

Another way to put it: B's public and protected members become private, private members are inaccessible.


问:
Compare two pandas dataframe with different size
I have one massive pandas dataframe with this structure:

```<code>df1:
    A   B
0   0  12
1   0  15
2   0  17
3   0  18
4   1  45
5   1  78
6   1  96
7   1  32
8   2  45
9   2  78
10  2  44
11  2  10
</code>```

And a second one, smaller like this:

```<code>df2
   G   H
0  0  15
1  1  45
2  2  31
</code>```

I want to add a column to my first dataframe following this rule: column df1.C = df2.H when df1.A == df2.G

I manage to do it with for loops, but the database is massive and the code run really slowly so I am looking for a Pandas-way or numpy to do it.

Many thanks,

Boris

答:
Here's one vectorized NumPy approach -

```<code>idx = np.searchsorted(df2.G.values, df1.A.values)
df1['C'] = df2.H.values[idx]
</code>```

idx could be computed in a simpler way with : df2.G.searchsorted(df1.A), but don't think that would be anymore efficient, because we want to use the underlying array with .values for performance as done earlier.

Body:
I have one massive pandas dataframe with this structure:

df1:
    A   B
0   0  12
1   0  15
2   0  17
3   0  18
4   1  45
5   1  78
6   1  96
7   1  32
8   2  45
9   2  78
10  2  44
11  2  10

And a second one, smaller like this:

df2
   G   H
0  0  15
1  1  45
2  2  31

I want to add a column to my first dataframe following this rule: column df1.C = df2.H when df1.A == df2.G

I manage to do it with for loops, but the database is massive and the code run really slowly so I am looking for a Pandas-way or numpy to do it.

Many thanks,

Boris

Body:
Here's one vectorized NumPy approach -

idx = np.searchsorted(df2.G.values, df1.A.values)
df1['C'] = df2.H.values[idx]

idx could be computed in a simpler way with : df2.G.searchsorted(df1.A), but don't think that would be anymore efficient, because we want to use the underlying array with .values for performance as done earlier.


问:
What is the Java 9 reflection equivalent of --add-modules?
I need a way to tell a newly created class loader (with no set parent) about modules I want exposed to it (e.g. java.scripting).

What's the reflection equivalent of passing --add-modules on the command line?

答:
There is no programmatic way to substantially edit the module graph created by the JVM on launch (adding reads edges is the only exception). This was a deliberate decision to keep the running application secure and stable. (Case in point, what would happen to your code, if you ran on a runtime that doesn't contain the java.scripting module?)

What you can do, though, is create a new layer, which contains an entirely new module graph. When launching the JVM, it will create a single layer from the command line flags and the module path content. With the existing API, you can then create new layers on top of that one. To learn about layers, have a look at The State of the Module System and the Javadoc for ModuleLayer.


问:
How to allow the input which is having white space and character limit is 15 using regex
For one of my projects, I just want to validate the input which has the following criteria:

Input may have white spaces, but not all spaces

Input must at least contain one or more characters

white space is not mandatory

Input has to allow any keyboard character

For Example :

space14chars

#$space12chars

&^11charsspace

I didn't try much to write the regular expression, as I am a newbie to this.

```<code>^[\x00-\x7E\s]{0,15}$
</code>```

But the above expression is allowing all spaces, which is limited to 15 chars -  it is not satisfying the first criteria.

答:
You may use

```<code>^(?!\s+$)[\x00-\x7E]{1,15}$
</code>```

It matches:

The "Input may have white spaces, but not all spaces" condition is met with a negative lookahead (?!\s+$) placed immediately after the start-of-string anchor (to only run the check once).

The "Input must at least contain one or more characters" is easily met with a {1,15} limiting quantifier: the lower bound is set to 1, so there must be at least 1 char. The upper bound is set to 15, you may adjust it as per your evolving requirements.

The "white space is not mandatory" condition is met due to the use of a single generic character class that matches other types of chars, too.

The "Input has to allow any keyboard character" condition is already met by your initial expression, as [\x00-\x7E] matches an ASCII char range.

Body:
For one of my projects, I just want to validate the input which has the following criteria:

Input may have white spaces, but not all spaces

Input must at least contain one or more characters

white space is not mandatory

Input has to allow any keyboard character

For Example :

space14chars

#$space12chars

&^11charsspace

I didn't try much to write the regular expression, as I am a newbie to this.

^[\x00-\x7E\s]{0,15}$

But the above expression is allowing all spaces, which is limited to 15 chars -  it is not satisfying the first criteria.

Body:
You may use

^(?!\s+$)[\x00-\x7E]{1,15}$

It matches:

The "Input may have white spaces, but not all spaces" condition is met with a negative lookahead (?!\s+$) placed immediately after the start-of-string anchor (to only run the check once).

The "Input must at least contain one or more characters" is easily met with a {1,15} limiting quantifier: the lower bound is set to 1, so there must be at least 1 char. The upper bound is set to 15, you may adjust it as per your evolving requirements.

The "white space is not mandatory" condition is met due to the use of a single generic character class that matches other types of chars, too.

The "Input has to allow any keyboard character" condition is already met by your initial expression, as [\x00-\x7E] matches an ASCII char range.


问:
Associative array: how to get the key of the current element which is an array
I have an array

```<code>Array (
      [0] => Array ( [2006] => Array ( [0] => 12 ) )
      [1] => Array ( [2004] => Array ( [0] => 12 [1] => 6 ) )
)
</code>```

How do I get the year so I can generate the folllowing using unordered list

```<code>2006
    December
2004
    December
    June
</code>```

答:
Here's your unordered list:

```<code>foreach ($array as $year => $months)
    {
        printf('%04d: <ul>', $year);

        foreach ($months as $m)
            {
                $tm = mktime(0,0,0,$m - 1,1);
                print strftime('<li>%B</li>', $tm);
            }

        print '</ul>';
    }
</code>```

Assuming the months stored are 1 for January and 12 for December. Hence the $m - 1.

Body:
I have an array

Array (
      [0] => Array ( [2006] => Array ( [0] => 12 ) )
      [1] => Array ( [2004] => Array ( [0] => 12 [1] => 6 ) )
)

How do I get the year so I can generate the folllowing using unordered list

2006
    December
2004
    December
    June

Body:
Here's your unordered list:

foreach ($array as $year => $months)
    {
        printf('%04d: <ul>', $year);

        foreach ($months as $m)
            {
                $tm = mktime(0,0,0,$m - 1,1);
                print strftime('<li>%B</li>', $tm);
            }

        print '</ul>';
    }

Assuming the months stored are 1 for January and 12 for December. Hence the $m - 1.