问:
How do you access nested JSON data on React?
I am having trouble accessing the JSON data obtained from the Accuweather API on React in the Render Method.

I am doing this on React and get a undefined error even though I see the value in the JSON view when I open the link and format it. I have tried using the dot method but no luck.

```<code>import React, { Component } from 'react';

class App extends Component {

constructor(props){
super(props);
this.state = {
    items:[],
    isLoaded: false,
}
}

componentDidMount() {

fetch('http://dataservice.accuweather.com/forecasts/v1/daily/1day/2094578.json?details=true&apikey=JjaFgoA67A3eXoMR7SiRyprGyPiv4Eln')

.then(res => res.json())
.then(json => {
    this.setState({
        isLoaded:true,
        items:json,
      })
})
}
render() {
var {isLoaded, items} = this.state;
if (!isLoaded) {
    return <div> Loading...</div>;
}
else {
  return (
    <div className="App">

     <h1>IES Storm Water Forecast</h1>
     <h1>{new Date().toString()}</h1>
     <h2> Weather Forcast: {items["DailyForecasts"]["Day"]["ShortPhrase"]}</h2>

     <h3>Description: {items.Headline.Text}</h3>
     <h6>Source: Accuweather</h6>
    </div>

);
}

}

}

export default App;
</code>```

JSON object in there:

http://dataservice.accuweather.com/forecasts/v1/daily/1day/2094578.json?details=true&apikey=JjaFgoA67A3eXoMR7SiRyprGyPiv4Eln

I get the following errors:

Unhandled Rejection (TypeError): Cannot read property 'ShortPhrase' of
  undefined TypeError: Cannot read property 'ShortPhrase' of undefined

But I should be getting a short sentence on weather.

答:
Add a template condition like the following:
...</p>

```<code>else {
  return (
    <div className="App">

     <h1>IES Storm Water Forecast</h1>
     <h1>{new Date().toString()}</h1>
     <h2> Weather Forcast: {items["DailyForecasts"]["Day"] && items["DailyForecasts"]["Day"]["ShortPhrase"]}</h2>
                            ^^^

     <h3>Description: {items.Headline.Text}</h3>
     <h6>Source: Accuweather</h6>
    </div>

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

Body:
I am having trouble accessing the JSON data obtained from the Accuweather API on React in the Render Method.

I am doing this on React and get a undefined error even though I see the value in the JSON view when I open the link and format it. I have tried using the dot method but no luck.

import React, { Component } from 'react';

class App extends Component {

constructor(props){
super(props);
this.state = {
    items:[],
    isLoaded: false,
}
}

componentDidMount() {

fetch('http://dataservice.accuweather.com/forecasts/v1/daily/1day/2094578.json?details=true&apikey=JjaFgoA67A3eXoMR7SiRyprGyPiv4Eln')

.then(res => res.json())
.then(json => {
    this.setState({
        isLoaded:true,
        items:json,
      })
})
}
render() {
var {isLoaded, items} = this.state;
if (!isLoaded) {
    return
 Loading...
;
}
else {
  return (

IES Storm Water Forecast

{new Date().toString()}

 Weather Forcast: {items["DailyForecasts"]["Day"]["ShortPhrase"]}

Description: {items.Headline.Text}

Source: Accuweather

);
}

}

}

export default App;

JSON object in there:

http://dataservice.accuweather.com/forecasts/v1/daily/1day/2094578.json?details=true&apikey=JjaFgoA67A3eXoMR7SiRyprGyPiv4Eln

I get the following errors:

Unhandled Rejection (TypeError): Cannot read property 'ShortPhrase' of
  undefined TypeError: Cannot read property 'ShortPhrase' of undefined

But I should be getting a short sentence on weather.

Body:
Add a template condition like the following:
...

else {
  return (
    <div className="App">

     <h1>IES Storm Water Forecast</h1>
     <h1>{new Date().toString()}</h1>
     <h2> Weather Forcast: {items["DailyForecasts"]["Day"] && items["DailyForecasts"]["Day"]["ShortPhrase"]}</h2>
                            ^^^

     <h3>Description: {items.Headline.Text}</h3>
     <h6>Source: Accuweather</h6>
    </div>

);
}
...


来源: stackexchange

问:
Max function with tuple key [Updated]
I'm trying to understand what happened in the following line:

```<code>print(max([1, -2, 3, -1], key=lambda x:(-abs(x), x), default=0))
</code>```

My understanding is, the lambda will return a tuple for each element in the list [1, -2, 3, -1].

But how can a list be compared with a tuple?

And why the output is 1, instead of 3 ?

I've tried

```<code>print(max([1, -2, 3, -1], key=(-1, 1), default=0))
</code>```

But it said uple is not callable

The key to understand the problem here is the key function used. If it's hard to understand, i recommend you to read this and play with sort rather max (cause sort will give you a informational anwser)

My understanding:

Step 1. the lambda function convert a = [1, -2, 3, -1] to a new one b = [(-1, 1), (-2, -2), (-3, 3), (-1, 1)]

Step 2. max/sort will deal with the new listb. It will first compare the first element, if it's tied, compare the second

Step3. convert the sorted(b) in terms of a

答:
you've used key=lambda x:(-abs(x), x) this means the contrary of max that's why instead of getting the largest possible number it gives you the lowest number. Note if there are the +- same number the one that the max will get always is the positive number since its abs()</p>

```<code>print(max([1, -2, 3, -1], key=lambda x:(-abs(x), x), default=0))
print(max([1, -2, 3, -1], key=lambda x:(abs(x), x), default=0))
print(max([-2, 3, 4, 5], key=lambda x:(-abs(x), x), default=0))

results:
1
3
-2
</code>```

ContentLicense: CC BY-SA 4.0

Title: Max function with tuple key [Updated]

Body:
I'm trying to understand what happened in the following line:

print(max([1, -2, 3, -1], key=lambda x:(-abs(x), x), default=0))

My understanding is, the lambda will return a tuple for each element in the list [1, -2, 3, -1].

But how can a list be compared with a tuple?

And why the output is 1, instead of 3 ?

I've tried

print(max([1, -2, 3, -1], key=(-1, 1), default=0))

But it said uple is not callable

The key to understand the problem here is the key function used. If it's hard to understand, i recommend you to read this and play with sort rather max (cause sort will give you a informational anwser)

My understanding:

Step 1. the lambda function convert a = [1, -2, 3, -1] to a new one b = [(-1, 1), (-2, -2), (-3, 3), (-1, 1)]

Step 2. max/sort will deal with the new listb. It will first compare the first element, if it's tied, compare the second

Step3. convert the sorted(b) in terms of a

Body:
you've used key=lambda x:(-abs(x), x) this means the contrary of max that's why instead of getting the largest possible number it gives you the lowest number. Note if there are the +- same number the one that the max will get always is the positive number since its abs()

print(max([1, -2, 3, -1], key=lambda x:(-abs(x), x), default=0))
print(max([1, -2, 3, -1], key=lambda x:(abs(x), x), default=0))
print(max([-2, 3, 4, 5], key=lambda x:(-abs(x), x), default=0))

results:
1
3
-2


问:
how to check duplicate values go to database
this is my code insert into db so i want to check duplicate value how to find an show this message "All ready exist this item code or item name"</p>

```<code>    try {
        String sql = "insert into itemreg(ItemID,ItemName) values(?,?)";
        pst = con.prepareStatement(sql);
        pst.setString(1, icode.getText());
        pst.setString(2, iname.getText());

        JOptionPane.showMessageDialog(null, "Item saved");
        pst.execute();
        tableupdate();
        clear();

    } catch (Exception e) {
        System.out.println(e);
    }
</code>```

答: When ItemID is defined as primary key you will get an SQLException when you try to insert a row with the same id.

Body:
this is my code insert into db so i want to check duplicate value how to find an show this message "All ready exist this item code or item name"

    try {
        String sql = "insert into itemreg(ItemID,ItemName) values(?,?)";
        pst = con.prepareStatement(sql);
        pst.setString(1, icode.getText());
        pst.setString(2, iname.getText());

        JOptionPane.showMessageDialog(null, "Item saved");
        pst.execute();
        tableupdate();
        clear();

    } catch (Exception e) {
        System.out.println(e);
    }


问:
Laravel 5.7 : Supervisorctl does not auto-restart queue worker with
I have supervisor for managing queue notifications as suggested in the laravel documentation . I have configured the supervisor as per the documentation and here is my configuration file.

```<code>[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/application/artisan queue:work --tries=3
autostart=true
autorestart=true
user=root
numprocs=8
redirect_stderr=true
stdout_logfile=/var/www/application/storage/logs/worker/worker.log
</code>```

This works fine but the problem is after sometime all the workers stops and doesn't restart even though there is pending jobs to be completed.

I need to manually restart the supervisor using sudo supervisorctl start laravel-worker:*.

How can this be resolved ?

Supervisorctl does not auto-restart daemon queue worker when hanging This is similar problem but the solution given there is the same thing i am using here.

Can anyone please help ?

答:
You could use horizon. horizon handles all this for you.
https://laravel.com/docs/5.8/horizon

Example supervisor script for horizon:

```<code>[program:horizon]
process_name=%(program_name)s
command=php /var/www/application/artisan horizon
autostart=true
autorestart=true
user=root
redirect_stderr=true
stdout_logfile=/var/www/application/storage/logs/horizon.log
</code>```

Also add this command to your deploy-process:

```<code>php artisan horizon:terminate
</code>```

No need to restart it, supervisor does that for you.

Body:
I have supervisor for managing queue notifications as suggested in the laravel documentation . I have configured the supervisor as per the documentation and here is my configuration file.

[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/application/artisan queue:work --tries=3
autostart=true
autorestart=true
user=root
numprocs=8
redirect_stderr=true
stdout_logfile=/var/www/application/storage/logs/worker/worker.log

This works fine but the problem is after sometime all the workers stops and doesn't restart even though there is pending jobs to be completed.

I need to manually restart the supervisor using sudo supervisorctl start laravel-worker:*.

How can this be resolved ?

Supervisorctl does not auto-restart daemon queue worker when hanging This is similar problem but the solution given there is the same thing i am using here.

Can anyone please help ?

Body:
You could use horizon. horizon handles all this for you.
https://laravel.com/docs/5.8/horizon

Example supervisor script for horizon:

[program:horizon]
process_name=%(program_name)s
command=php /var/www/application/artisan horizon
autostart=true
autorestart=true
user=root
redirect_stderr=true
stdout_logfile=/var/www/application/storage/logs/horizon.log

Also add this command to your deploy-process:

php artisan horizon:terminate

No need to restart it, supervisor does that for you.


问:
How to pass parameter on 'vagrant up' and have it in the scope of Vagrantfile?
I'm looking for a way to pass parameter to Chef cookbook like:

```<code>$ vagrant up some_parameter
</code>```

And then use some_parameter inside one of the Chef cookbooks.

答:
```<code>Vagrant.configure("2") do |config|

    class Username
        def to_s
            print "Virtual machine needs you proxy user and password.\n"
            print "Username: "
            STDIN.gets.chomp
        end
    end

    class Password
        def to_s
            begin
            system 'stty -echo'
            print "Password: "
            pass = URI.escape(STDIN.gets.chomp)
            ensure
            system 'stty echo'
            end
            pass
        end
    end

    config.vm.provision "shell", env: {"USERNAME" => Username.new, "PASSWORD" => Password.new}, inline: <<-SHELL
        echo username: $USERNAME
        echo password: $PASSWORD
SHELL
    end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm looking for a way to pass parameter to Chef cookbook like:

$ vagrant up some_parameter

And then use some_parameter inside one of the Chef cookbooks.


问:
Apache Kafka - Volume Mapping for Message Log files in Kubernetes (K8s)
When we deploy apache kafka on Linux/Windows, we have log.dirs and broker.id properties. on bare metal, the files are saved on the individual host instances. However, when deployed via K8s on public cloud - there must be some form of volume mounting to make sure that the transaction log fils are saved somewhere?

Has anyone done this on K8s? I am not referring to Confluent (because it's a paid subscription).

答:
As far as I understand you are just asking how to deal with storage in Kubernetes.

Here is a great clip that talks about Kubernetes Storage that I would recommend to You.

In Kubernetes you are using Volumes

On-disk files in a Container are ephemeral, which presents some problems for non-trivial applications when running in Containers. First, when a Container crashes, kubelet will restart it, but the files will be lost - the Container starts with a clean state. Second, when running Containers together in a Pod it is often necessary to share files between those Containers. The Kubernetes Volume abstraction solves both of these problems.

There is many types of Volumes, some are cloud specific like awsElasticBlockStore, gcePersistentDisk, azureDisk and azureFile.

There are also other types like glusterfs, iscsi, nfs and many more that are listed here.

You can also use Persistent Volumes which provides an API for users and administrators that abstracts details of how storage is provided from how it is consumed:

A  PersistentVolume  (PV) is a piece of storage in the cluster that has been provisioned by an administrator. It is a resource in the cluster just like a node is a cluster resource. PVs are volume plugins like Volumes, but have a lifecycle independent of any individual pod that uses the PV. This API object captures the details of the implementation of the storage, be that NFS, iSCSI, or a cloud-provider-specific storage system.

A  PersistentVolumeClaim  (PVC) is a request for storage by a user. It is similar to a pod. Pods consume node resources and PVCs consume PV resources. Pods can request specific levels of resources (CPU and Memory). Claims can request specific size and access modes (e.g., can be mounted once read/write or many times read-only).

Here is a link to Portworx Kafka Kubernetes in production: How to Run HA Kafka on Amazon EKS, GKE and AKS which might be handy for you as well.

And if you would be interested in performance then Kubernetes Storage Performance Comparison is a great 10min read.

I hope those materials will help you understand Kubernetes storage.


问:
Does Roku Device is Required for Roku Development / Testing..(Simple Hello World App)
I'm new to Roku development, and facing very basic issues. I am unable to understand, how will i test my app.

I read that we can't test Roku app on simulator, and only on real device. So:
Do i need to buy Roku device?
What's the best testing strategy?

Please help. Thanks

答: Yes you need Roku device. Also you need smart TV for connecting to device. with same connectivity with Internet. I hope my answer will helpful</p>


问:
EF core Access list through Include
I have a Model named as Blog:

```<code>public class Blog
    {
        [Key]
        public int blogId { get; set; }
        [Required]
        public string blogTitle { get; set; }
        public string imagePath { get; set; }
        [Required, DataType(DataType.Html)]
        public string blogDescription { get; set; }
        [DataType(DataType.DateTime)]
        public DateTime blogDateTime { get; set; }
        [Required]
        public bool isPublished { get; set; }

        [Required]
        public BlogCategory blogCategory { get; set; }
        public List<Comments> blogComments { get; set; }
    }
</code>```

And another model Comment:

```<code>public class Comments
    {
        [Key]
        public int authorId { get; set; }
        [Required]
        public string commentAuthor { get; set; }
        [DataType(DataType.Date)]
        public DateTime commentDate { get; set; }
        public bool isHidden { get; set; }
        [Required, DataType(DataType.EmailAddress)]
        public string commentAuthorEmail { get; set; }
        [Required]
        public string commentDescription { get; set; }
        public Blog Blog { get; set; }
    }
</code>```

In the blogs controller I want to access all the comments where isHidden = false

What I have tried is:

```<code>var blog = await _context.Blog
           .Include(cat => cat.blogCategory)
           .Include(comments => comments.blogComments.Any(c => !c.isHidden))
           .FirstOrDefaultAsync(m => m.blogId == id);
</code>```

But all I am getting exception is

```<code>An unhandled exception occurred while processing the request.
InvalidOperationException: The Include property lambda expression 'comments => comments.blogComments.Find(c => Not(c.isHidden))' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'.
</code>```

How can I solve this problem?

答:
You could not do filter in Include in EF core, try to use below code instead

```<code>var blog = await _context.Blog
       .Include(cat => cat.blogCategory)
       .Include(comments => comments.blogComments)
       .FirstOrDefaultAsync(m => m.blogId == id);

blog.blogComments = blog.blogComments.Where(b => b.isHidden == false).ToList();
</code>```

Refer to Filtering on Include in EF Core

Title: EF core Access list through Include

Body:
I have a Model named as Blog:

public class Blog
    {
        [Key]
        public int blogId { get; set; }
        [Required]
        public string blogTitle { get; set; }
        public string imagePath { get; set; }
        [Required, DataType(DataType.Html)]
        public string blogDescription { get; set; }
        [DataType(DataType.DateTime)]
        public DateTime blogDateTime { get; set; }
        [Required]
        public bool isPublished { get; set; }

        [Required]
        public BlogCategory blogCategory { get; set; }
        public List<Comments> blogComments { get; set; }
    }

And another model Comment:

public class Comments
    {
        [Key]
        public int authorId { get; set; }
        [Required]
        public string commentAuthor { get; set; }
        [DataType(DataType.Date)]
        public DateTime commentDate { get; set; }
        public bool isHidden { get; set; }
        [Required, DataType(DataType.EmailAddress)]
        public string commentAuthorEmail { get; set; }
        [Required]
        public string commentDescription { get; set; }
        public Blog Blog { get; set; }
    }

In the blogs controller I want to access all the comments where isHidden = false

What I have tried is:

var blog = await _context.Blog
           .Include(cat => cat.blogCategory)
           .Include(comments => comments.blogComments.Any(c => !c.isHidden))
           .FirstOrDefaultAsync(m => m.blogId == id);

But all I am getting exception is

An unhandled exception occurred while processing the request.
InvalidOperationException: The Include property lambda expression 'comments => comments.blogComments.Find(c => Not(c.isHidden))' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'.

How can I solve this problem?

Body:
You could not do filter in Include in EF core, try to use below code instead

var blog = await _context.Blog
       .Include(cat => cat.blogCategory)
       .Include(comments => comments.blogComments)
       .FirstOrDefaultAsync(m => m.blogId == id);

blog.blogComments = blog.blogComments.Where(b => b.isHidden == false).ToList();

Refer to Filtering on Include in EF Core


问:
Pyomo: Ipopt maximum numbers of iterations exceeded
i have some troubles with my objective in pyomo. I'm trying to minimize the difference between meassured value (parameter - which i import from a .txt) and the result for a variable from my optimization model.

Now my objective is:

```<code>def _obj_rule(mode):
    return pe.summation(model.T_vl_s_M,model.T_VL_s_dyn)
model.obj = pe.Objective(rule=_obj_rule, sense=pe.minimize)
</code>```

so the first part is the meassurement (param) and the second is the variable of the optimization. I want to minimize the difference.

What shall i do? When i start the program like this, i get an error, that the maximum number of iterations is exceeded.

Thanks in advance!

答:
Not sure what your problem is, but one thing you could try is to increase the maximum number of iterations (not sure what the default value is, somewhere between 200 and 100)</p>

```<code>solver = SolverFactory('ipopt')
solver.options['max_iter']= 10000 #number of iterations you wish
solver.solve(YOURMODEL)
</code>```

Body:
i have some troubles with my objective in pyomo. I'm trying to minimize the difference between meassured value (parameter - which i import from a .txt) and the result for a variable from my optimization model.

Now my objective is:

def _obj_rule(mode):
    return pe.summation(model.T_vl_s_M,model.T_VL_s_dyn)
model.obj = pe.Objective(rule=_obj_rule, sense=pe.minimize)

so the first part is the meassurement (param) and the second is the variable of the optimization. I want to minimize the difference.

What shall i do? When i start the program like this, i get an error, that the maximum number of iterations is exceeded.

Thanks in advance!

Body:
Not sure what your problem is, but one thing you could try is to increase the maximum number of iterations (not sure what the default value is, somewhere between 200 and 100)

solver = SolverFactory('ipopt')
solver.options['max_iter']= 10000 #number of iterations you wish
solver.solve(YOURMODEL)


问:
PDF to Image convertor
I'm taking recommendations for either a library in Python or Ruby or a free web service that will simply take a PDF and a pair of image dimensions and spit out an image for each page (jpg or png).  Nothing complicated! But it must have point-for-point accuracy to the original PDF.  That is all.</p>

答: ImageMagick uses Ghostscript for PDF files. So skip ImageMagick and use Ghostscript directly. IMHO.</p>

Title: PDF to Image convertor


问:
PHP how to simulate SIGPIPE?
My environment:
Ubuntu 18.04 LTS
PHP 7.2.2 ZTS no-debug

I have a big application where sometimes Broken pipe error is happening.
I want to handle it but for this I need to simulate this error for development. How can I do that ?

I have tried:

```<code>posix_kill(posix_getpid(), SIGPIPE);
while(1) {
    sleep(5);
}
</code>```

Also:

```<code>sudo kill -13 pid
</code>```

But script keep working.

Expected result:

```<code>Thread 1 "php" received signal SIGPIPE, Broken pipe.
</code>```

and script should get stopped.

答:
signal_example.php:

```<code>pcntl_async_signals(true);

pcntl_signal(SIGPIPE, function (int $signo) {
    echo 'Process ' . posix_getpid() . ' "php" received signal SIGPIPE, Broken pipe.';
    exit;
});

while (1) {
    sleep(1);
}
</code>```

kill -13 990:

```<code>artemev@Vitaly-PC:~/project/example$ php signal_example.php
Process 990 "php" received signal SIGPIPE, Broken pipe.
</code>```

Title: PHP how to simulate SIGPIPE?

Body:
My environment:
Ubuntu 18.04 LTS
PHP 7.2.2 ZTS no-debug

I have a big application where sometimes Broken pipe error is happening.
I want to handle it but for this I need to simulate this error for development. How can I do that ?

I have tried:

posix_kill(posix_getpid(), SIGPIPE);
while(1) {
    sleep(5);
}

Also:

sudo kill -13 pid

But script keep working.

Expected result:

Thread 1 "php" received signal SIGPIPE, Broken pipe.

and script should get stopped.

Body:
signal_example.php:

pcntl_async_signals(true);

pcntl_signal(SIGPIPE, function (int $signo) {
    echo 'Process ' . posix_getpid() . ' "php" received signal SIGPIPE, Broken pipe.';
    exit;
});

while (1) {
    sleep(1);
}

kill -13 990:

artemev@Vitaly-PC:~/project/example$ php signal_example.php
Process 990 "php" received signal SIGPIPE, Broken pipe.


问:
replace values in data-table based on column number and separate index vector
I am given a large data-table and I need to set cells to a fixed value (e.g. 0) based on the column number and an index dependent on the row number.

As an example, I am given a data-table 'dt' full of ones. Additionally, I have a column vector, giving the number of columns (per row) that shall remain unchanged and the remaining ones shall be set to 0.

```<code>dt <- setnames(data.table(matrix(1,nrow=100, ncol=11)),as.character(c(0:10)))

set.seed(1)
index <- sample(c(0:11),100, replace=TRUE)

> dput(index)
c(3L, 4L, 6L, 10L, 2L, 10L, 11L, 7L, 7L, 0L, 2L, 2L, 8L, 4L,
9L, 5L, 8L, 11L, 4L, 9L, 11L, 2L, 7L, 1L, 3L, 4L, 0L, 4L, 10L,
4L, 5L, 7L, 5L, 2L, 9L, 8L, 9L, 1L, 8L, 4L, 9L, 7L, 9L, 6L, 6L,
9L, 0L, 5L, 8L, 8L, 5L, 10L, 5L, 2L, 0L, 1L, 3L, 6L, 7L, 4L,
10L, 3L, 5L, 3L, 7L, 3L, 5L, 9L, 1L, 10L, 4L, 10L, 4L, 4L, 5L,
10L, 10L, 4L, 9L, 11L, 5L, 8L, 4L, 3L, 9L, 2L, 8L, 1L, 2L, 1L,
2L, 0L, 7L, 10L, 9L, 9L, 5L, 4L, 9L, 7L)
</code>```

For example, in the first row, the first three cells remain unchanged and the other ones are set to 0.
As it is a large data-table, I look for an efficient way to do this

答:
```<code>last_col <- names(dt)[ncol(dt)]
for (r in seq_len(nrow(dt))) {
  zero_from <- max(index[r]-1L, 0L)
  set(dt, i = r, j = as.character(zero_from:last_col), value = 0)
}
</code>```

Body:
I am given a large data-table and I need to set cells to a fixed value (e.g. 0) based on the column number and an index dependent on the row number.

As an example, I am given a data-table 'dt' full of ones. Additionally, I have a column vector, giving the number of columns (per row) that shall remain unchanged and the remaining ones shall be set to 0.

dt <- setnames(data.table(matrix(1,nrow=100, ncol=11)),as.character(c(0:10)))

set.seed(1)
index <- sample(c(0:11),100, replace=TRUE)

> dput(index)
c(3L, 4L, 6L, 10L, 2L, 10L, 11L, 7L, 7L, 0L, 2L, 2L, 8L, 4L,
9L, 5L, 8L, 11L, 4L, 9L, 11L, 2L, 7L, 1L, 3L, 4L, 0L, 4L, 10L,
4L, 5L, 7L, 5L, 2L, 9L, 8L, 9L, 1L, 8L, 4L, 9L, 7L, 9L, 6L, 6L,
9L, 0L, 5L, 8L, 8L, 5L, 10L, 5L, 2L, 0L, 1L, 3L, 6L, 7L, 4L,
10L, 3L, 5L, 3L, 7L, 3L, 5L, 9L, 1L, 10L, 4L, 10L, 4L, 4L, 5L,
10L, 10L, 4L, 9L, 11L, 5L, 8L, 4L, 3L, 9L, 2L, 8L, 1L, 2L, 1L,
2L, 0L, 7L, 10L, 9L, 9L, 5L, 4L, 9L, 7L)

For example, in the first row, the first three cells remain unchanged and the other ones are set to 0.
As it is a large data-table, I look for an efficient way to do this


问:
CollectionView sections
I have a collectionview and I want it to be of n section where each section has a ten of cells, my problem is: Maybe n equals thirty five, in this case I want to show 3 section with ten of cells and the last section with just five. </p>

答:
You can simply implement UICollectionViewDataSource methods and configure collectionView(_:numberOfItemsInSection:) method based on the each section for number of cells.

```<code>let n = 35 //It specify the total elements count

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return n/10
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    switch section {
    case (n/10):
        return (n % 10)

    default:
        return 10
    }
}
</code>```

In the above code, the collectionView will have

(n % 10) cells for last section

10 cells for other sections

Kindly clarify your conditions so I can update the code accordingly.

Title: CollectionView sections

Body:
You can simply implement UICollectionViewDataSource methods and configure collectionView(_:numberOfItemsInSection:) method based on the each section for number of cells.

let n = 35 //It specify the total elements count

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return n/10
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    switch section {
    case (n/10):
        return (n % 10)

    default:
        return 10
    }
}

In the above code, the collectionView will have

(n % 10) cells for last section

10 cells for other sections

Kindly clarify your conditions so I can update the code accordingly.


问:
Struggling with correlated subqueries in SQL
I have a database about old cars, their owners, events and the attendants of those events as such:

Image of tables used :

PK: Primary Key
FK: Foreign Key

Now I need to get the amount of different events (eventId) each member (memberId) has attended.
Important note: a member can have multiple cars that can each attend events.

Here is one of my attemps:

```<code>select m.memberId, count(a.eventId).
from members m where m.memberId in (select c.memberId from cars c where m.memberId =
    c.memberId and c.carId in
    (select d.carId from attendants a where c.carId = d.carId))
order by m.memberId
</code>```

I've also tried using joins and group by to get a correct result but I am getting nowhere.
Does anyone know how i need to form the subquery so that i can get the results needed?

答:
Not sure if you are using that exact statement, but your syntax has several issues. You're using aliases that don't exist (d.CarID - what table is d?) and you don't have a group by statement at the end, which tells the engine what columns you want to preserve the values from. Try something like this:

```<code>select member_ID,
  count(*)
from (
  select distinct a.eventID, m.memberID
  from attendants a
  inner join cars c
  on a.carID = c.car_ID
  inner join members m
  on c.memberID = m.memberID
  group by a.eventID, m.memberID
)
group by memberID
</code>```

The inner query gets what you want - a big list of all the members who have attended via the cars they own, deduped so that if they had two cars at the same event they are only recorded once - which is then counted for each member.

Body:
I have a database about old cars, their owners, events and the attendants of those events as such:

Image of tables used :

PK: Primary Key
FK: Foreign Key

Now I need to get the amount of different events (eventId) each member (memberId) has attended.
Important note: a member can have multiple cars that can each attend events.

Here is one of my attemps:

select m.memberId, count(a.eventId).
from members m where m.memberId in (select c.memberId from cars c where m.memberId =
    c.memberId and c.carId in
    (select d.carId from attendants a where c.carId = d.carId))
order by m.memberId

I've also tried using joins and group by to get a correct result but I am getting nowhere.
Does anyone know how i need to form the subquery so that i can get the results needed?

Body:
Not sure if you are using that exact statement, but your syntax has several issues. You're using aliases that don't exist (d.CarID - what table is d?) and you don't have a group by statement at the end, which tells the engine what columns you want to preserve the values from. Try something like this:

select member_ID,
  count(*)
from (
  select distinct a.eventID, m.memberID
  from attendants a
  inner join cars c
  on a.carID = c.car_ID
  inner join members m
  on c.memberID = m.memberID
  group by a.eventID, m.memberID
)
group by memberID

The inner query gets what you want - a big list of all the members who have attended via the cars they own, deduped so that if they had two cars at the same event they are only recorded once - which is then counted for each member.


问:
.NET Core Web API without changes returns 404 for url http://localhost:8083/api/values on IIS
.NET Core Web API without changes returns 404 for url http://localhost:8083/api/values on IIS

```<code>    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }

</code>```

this is Startup.cs code,i only change the constructor ,was anything wrong?

```<code>public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }
}
</code>```

http://localhost:8083/api/values Getting 404.0 Not Found

what should i do?

答:
Solved with a web.config</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<confenter code hereiguration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess">
        <environmentVariables>
          <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
        </environmentVariables>
      </aspNetCore>
    </system.webServer>
  </location>
</configuration>
</code>```

Body:
.NET Core Web API without changes returns 404 for url http://localhost:8083/api/values on IIS

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }

this is Startup.cs code,i only change the constructor ,was anything wrong?

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }
}

http://localhost:8083/api/values Getting 404.0 Not Found

what should i do?

Body:
Solved with a web.config

<?xml version="1.0" encoding="utf-8"?>
<confenter code hereiguration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess">
        <environmentVariables>
          <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
        </environmentVariables>
      </aspNetCore>
    </system.webServer>
  </location>
</configuration>


问:
What's the fastest way to test the validity of a large number of well-formed URLs
My project requires me to validate a large number of web URLs. These URLs have been captured by a very unreliable process which I do not control. All of the URLs have already been regexp validated and are known to be well-formed. I also know that they all have valid TLDs

I want to be able to filter these URLs quickly in order to determine which of these are incorrect. At this point I do not care what content is on the pages - I'd just like to know as quickly as possible which of the pages are inaccessible (e.g. produce a 404 error).

Given that there are a lot of these I do not want to download the entire page, just the HTTP header and then take a good guess from the content of the header whether the page is likely to exist.

Can it be done?

答: Just send HTTP HEAD requests as shown in the accepted answer to this question.</p>

OwnerDisplayName: Salim Fadhley

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Bill the Lizard


问:
How to pick an exact element from HashMap using Java8
I need to pick an exact element from a hash map.

I wrote a method that should return an element.
From line:

```<code>this.referenceEntityCache.getReferenceEntities();
</code>```

I will receive a hashMap looking like this Map :

```<code>         {[Element: <Ry/>] = EntityTree@1,
        // [Element: <Nd/>] = EntityTree@2,
        // [Element: <Ry/>] = EntityTree@3,
        // [Element: <Ah/>] = EntityTree@4,
        // [Element: <Ah/>] = EntityTree@5 }
</code>```

and from this map I need to get only the "Ah" element.

The hashMap has the key = Element :   and value of entityTree linked to it.

```<code>public Element pickUpTheElement() {
    Element ahElement = null;
    Map<Element, EntityTree> mapOfElements = this.referenceEntityCache.getReferenceEntities();
    return ahElement = mapOfElements.map(map -> map.entrySet()
                .stream()
                .filter(e -> Objects.equals(e.getValue(), element))
                .map(Map.Entry::getKey)
                .findAny());
                .orElse(null);
</code>```

have no idea how to filter it properly using Java8 and obtain only "Ah" Element from it. There are 2 element of Ah - but as they are objects - they have different hashcodes since their values (EntityTree) are different

答:
You can return null as default value (if the Optional is empty):

```<code>return mapOfElements.entrySet()
                    .stream()
                    .filter(e -> Objects.equals(e.getValue(), element))
                    .map(Map.Entry::getKey)
                    .findAny()
                    .orElse(null);
</code>```

Body:
I need to pick an exact element from a hash map.

I wrote a method that should return an element.
From line:

this.referenceEntityCache.getReferenceEntities();

I will receive a hashMap looking like this Map :

         {[Element: <Ry/>] = EntityTree@1,
        // [Element: <Nd/>] = EntityTree@2,
        // [Element: <Ry/>] = EntityTree@3,
        // [Element: <Ah/>] = EntityTree@4,
        // [Element: <Ah/>] = EntityTree@5 }

and from this map I need to get only the "Ah" element.

The hashMap has the key = Element :   and value of entityTree linked to it.

public Element pickUpTheElement() {
    Element ahElement = null;
    Map<Element, EntityTree> mapOfElements = this.referenceEntityCache.getReferenceEntities();
    return ahElement = mapOfElements.map(map -> map.entrySet()
                .stream()
                .filter(e -> Objects.equals(e.getValue(), element))
                .map(Map.Entry::getKey)
                .findAny());
                .orElse(null);

have no idea how to filter it properly using Java8 and obtain only "Ah" Element from it. There are 2 element of Ah - but as they are objects - they have different hashcodes since their values (EntityTree) are different

Body:
You can return null as default value (if the Optional is empty):

return mapOfElements.entrySet()
                    .stream()
                    .filter(e -> Objects.equals(e.getValue(), element))
                    .map(Map.Entry::getKey)
                    .findAny()
                    .orElse(null);


问:
My Drupal sites are showing contents of /sites/default and all other folders below /sites
I have a problem that could be something simple - but I can't get my head around it at the moment.  I have a few sites hosted on my Ubuntu 10.04LTS virtual server, and on all of them (Drupal 6) I can go directly to any folder below (and including) /sites (including the modules directory).

[edit] I've just realised I can go to ANY folder - ie /includes as well...[/edit]

I don't recall this being normal, and it certainly seems to be a security risk that I can get to the /sites/default folder - although I may be just being paranoid.

Can anyone confirm if this is normal, and if not point out what might be the root of my problem?

Cheers

Steve

答:
I found the problem - it was twofold:

First, for some reason my .htaccess files (generated by Drupal) were missing on some sites (I think this might have been a permissions problem with the root folder for the sites in question).

Second, I had a dodgy rule in the config files for each site that was over-riding the .htaccess file anyway - that will teach me to copy-paste from a web blog... found the correct layout for the mod_rewrite section on the Drupal site itself.

It was an odd one, and took a little finding, but its sorted now


问:
Is possible to get Image GPS location coordinates from the Image?
I'm building a Flutter App where the user can post a photo and it's location. The use can both get a picture from the camera or from the library.

If the user take a picture from camera I can use the GPS location of the device to set the picture's location. I'm trying to get the GSP location of the pictures based on its metadata, but, I didn't found a way to do it yet.

Is possible to do it? How the best way?

Edit: I put "GPS" in the question to make it clear. I'm trying to discover the physical position where the picture was taken. I also added "Flutter" to the question to make it clear that I'm facing the problem of solving this problem in a Flutter App.

答:
I discovered that my previous problem was related to the Camera permissions of the devices. Usually a camera from android access the user location and save the GPS coordinates as Exif tag, but the ios devices usually don't save this by default unless the user allows location permissions to the camera app.

I changed my app to check if the image has GPS coordinates and the user decides if he wants to share his actual location or the image location.

I'm also having to do some math to process the coordinates:

In order to you use the code you have to add the package exif and geoflutterfire to your app.

```<code>void _checkGPSData() async {
    Map<String, IfdTag> imgTags = await readExifFromBytes( File(image.path).readAsBytesSync() );

    if (imgTags.containsKey('GPS GPSLongitude')) {
      setState(() {
        _imgHasLocation = true;
        _imgLocation = exifGPSToGeoFirePoint(imgTags);
      });
    }

  }

GeoFirePoint exifGPSToGeoFirePoint(Map<String, IfdTag> tags) {

  final latitudeValue = tags['GPS GPSLatitude'].values.map<double>( (item) => (item.numerator.toDouble() / item.denominator.toDouble()) ).toList();
  final latitudeSignal = tags['GPS GPSLatitudeRef'].printable;

  final longitudeValue = tags['GPS GPSLongitude'].values.map<double>( (item) => (item.numerator.toDouble() / item.denominator.toDouble()) ).toList();
  final longitudeSignal = tags['GPS GPSLongitudeRef'].printable;

  double latitude = latitudeValue[0]
    + (latitudeValue[1] / 60)
    + (latitudeValue[2] / 3600);

  double longitude = longitudeValue[0]
    + (longitudeValue[1] / 60)
    + (longitudeValue[2] / 3600);

  if (latitudeSignal == 'S') latitude = -latitude;
  if (longitudeSignal == 'W') longitude = -longitude;

  return  GeoFirePoint(latitude, longitude);
}
</code>```

Body:
I discovered that my previous problem was related to the Camera permissions of the devices. Usually a camera from android access the user location and save the GPS coordinates as Exif tag, but the ios devices usually don't save this by default unless the user allows location permissions to the camera app.

I changed my app to check if the image has GPS coordinates and the user decides if he wants to share his actual location or the image location.

I'm also having to do some math to process the coordinates:

In order to you use the code you have to add the package exif and geoflutterfire to your app.

void _checkGPSData() async {
    Map<String, IfdTag> imgTags = await readExifFromBytes( File(image.path).readAsBytesSync() );

    if (imgTags.containsKey('GPS GPSLongitude')) {
      setState(() {
        _imgHasLocation = true;
        _imgLocation = exifGPSToGeoFirePoint(imgTags);
      });
    }

  }

GeoFirePoint exifGPSToGeoFirePoint(Map<String, IfdTag> tags) {

  final latitudeValue = tags['GPS GPSLatitude'].values.map<double>( (item) => (item.numerator.toDouble() / item.denominator.toDouble()) ).toList();
  final latitudeSignal = tags['GPS GPSLatitudeRef'].printable;

  final longitudeValue = tags['GPS GPSLongitude'].values.map<double>( (item) => (item.numerator.toDouble() / item.denominator.toDouble()) ).toList();
  final longitudeSignal = tags['GPS GPSLongitudeRef'].printable;

  double latitude = latitudeValue[0]
    + (latitudeValue[1] / 60)
    + (latitudeValue[2] / 3600);

  double longitude = longitudeValue[0]
    + (longitudeValue[1] / 60)
    + (longitudeValue[2] / 3600);

  if (latitudeSignal == 'S') latitude = -latitude;
  if (longitudeSignal == 'W') longitude = -longitude;

  return  GeoFirePoint(latitude, longitude);
}


答:
So you want distinct events the member has attended. Member has cars which attend the events. Since different cars can attend same events, you need to take distinct from events:</p>

```<code>select m.memberId, count(distinct a.eventId)
from members m
  join cars c on c.memberId = m.memberId
  join attendants a on a.carId = c.carId
group by m.memberId
</code>```

Title: Struggling with correlated subqueries in SQL

Body:
So you want distinct events the member has attended. Member has cars which attend the events. Since different cars can attend same events, you need to take distinct from events:

select m.memberId, count(distinct a.eventId)
from members m
  join cars c on c.memberId = m.memberId
  join attendants a on a.carId = c.carId
group by m.memberId


问:
Why is this result?
Is that about stack? I think the last *p++ is undefined. *p++ means *(p++) or *p;p++;?

void test123()
{

    char s[] = "123", * p;
    p = s;
    // 1 2 3
    cout << *p++ << endl;
    cout << *p++ << endl;
    cout << *p++ << endl;

}
void test321()
{
    char s[] = "123", * p;
    p = s;
    //321
    cout << *p++ << *p++ << *p++ << endl;

}
int main(void)
{
    cout << "123:" << endl;
    test123();
    cout << "123:" << endl;
    test321();
    cout << "hello world" << endl;
    return 0;
}
```

I think the result is undefined.

答:
*p++ is evaluated to *(p++) according to operator precedence. And what p++ does is that increments p by 1 and returns the value before the increment.

From https://en.cppreference.com/w/cpp/language/operator_incdec

Post-increment and post-decrement creates a copy of the object, increments or decrements the value of the object and returns the copy from before the increment or decrement.

Even at the last line you mentioned, p++ returns the position s+2 so dereferencing it we get 3, not the next address to it.

Except the order of evaluation(in test321), there is no undefined behavior in this code.

% If the expression was *++p it would do exactly what you said(However it is still not undefined since every string literal ends with zero(\0).

Title: Why is this result?

Body:
Is that about stack? I think the last *p++ is undefined. *p++ means *(p++) or *p;p++;?

void test123()
{

    char s[] = "123", * p;
    p = s;
    // 1 2 3
    cout << *p++ << endl;
    cout << *p++ << endl;
    cout << *p++ << endl;

}
void test321()
{
    char s[] = "123", * p;
    p = s;
    //321
    cout << *p++ << *p++ << *p++ << endl;

}
int main(void)
{
    cout << "123:" << endl;
    test123();
    cout << "123:" << endl;
    test321();
    cout << "hello world" << endl;
    return 0;
}

I think the result is undefined.


问:
Git. How to roll back changes in certain file in a chain of commits?
I have a repo with three files in it - 1.txt, 2.txt and 3.txt. I created a branch 'new_branch' and made commits (let's call them A, B and C), every of these commits contains changes in several files from my repo. Then I understood, that 1.txt was updated mistakenly. Is it possible to remove changes, made in 1.txt, from commits A, B and C but keep changes in 2.txt and 3.txt?

UPD. I want also to remove changes, made it 1.txt, from commit history. As result 'git log -p' should show, that only 2.txt and 3.txt were modified in commits A, B and C.

Many thanks.

答:
git checkout <commit reference> <file> is what you are looking for.

```<code>> git init
Initialized empty Git repository in /Users/ody/temp/git-co/.git/
> touch 1 2 3
> echo foo > 1 > 2 > 3
> git add 1 2 3
> git commit -m "foo"
[master (root-commit) 470f4e8] foo
 3 files changed, 3 insertions(+)
 create mode 100644 1
 create mode 100644 2
 create mode 100644 3
> echo bar > 1 > 2 > 3
> git add 1 2 3
> git commit -m "bar"
[master 916819d] bar
 3 files changed, 3 insertions(+), 3 deletions(-)
> git checkout :/foo 1
> cat 1
foo
</code>```

NOTE: The :/ notation lets you reference a commit by a part of its name instead of a commit hash.

Body:
git checkout <commit reference> <file> is what you are looking for.

> git init
Initialized empty Git repository in /Users/ody/temp/git-co/.git/
> touch 1 2 3
> echo foo > 1 > 2 > 3
> git add 1 2 3
> git commit -m "foo"
[master (root-commit) 470f4e8] foo
 3 files changed, 3 insertions(+)
 create mode 100644 1
 create mode 100644 2
 create mode 100644 3
> echo bar > 1 > 2 > 3
> git add 1 2 3
> git commit -m "bar"
[master 916819d] bar
 3 files changed, 3 insertions(+), 3 deletions(-)
> git checkout :/foo 1
> cat 1
foo

NOTE: The :/ notation lets you reference a commit by a part of its name instead of a commit hash.


问:
How to insert variable results into calls in Django Template Language
In Django I'm trying to make a generic "confirm action" call which I can easily pass the final address to, but I'm having difficulty inserting a variable in the link:

```<code><a href="{% url 'view_do_confirm_action' 'url view_delete_object object.object_name' %}"> Delete this object </a><br>
</code>```

In case it's not clear, the argument to view_do_confirm_action is the url to be followed if the user confirms.  The final url I would like to be followed links to this pattern:

```<code>path('objects/object/<str:object_name>/delete', views.view_delete_object, name='view_delete_object'),
</code>```

"url view_delete_object object.object_name" is not being resolved at the right time here - any advice?

Thank you

scan

答:
You don't have to put another expression in django template expression.

You're passing a url as parameter to another url.

Instead of

```<code><a href="{% url 'view_do_confirm_action' 'url view_delete_object {{ object.object_name }}' %}"> Delete this object </a><br>
</code>```

Do

```<code>{% url view_delete_object object.object_name as the_url %}
<a href="{% url 'view_do_confirm_action' the_url %}"> Delete this object </a><br>
</code>```

Body:
In Django I'm trying to make a generic "confirm action" call which I can easily pass the final address to, but I'm having difficulty inserting a variable in the link:

 Delete this object

In case it's not clear, the argument to view_do_confirm_action is the url to be followed if the user confirms.  The final url I would like to be followed links to this pattern:

path('objects/object/<str:object_name>/delete', views.view_delete_object, name='view_delete_object'),

"url view_delete_object object.object_name" is not being resolved at the right time here - any advice?

Thank you

scan

Body:
You don't have to put another expression in django template expression.

You're passing a url as parameter to another url.

Instead of

<a href="{% url 'view_do_confirm_action' 'url view_delete_object {{ object.object_name }}' %}"> Delete this object </a><br>

Do

{% url view_delete_object object.object_name as the_url %}
<a href="{% url 'view_do_confirm_action' the_url %}"> Delete this object </a><br>


问:
Collection view grid last row appears differently despite equal widths - swift iOS
I've a fixed grid of collection view cells (UICollectionView) but the cells in the bottom row always appears with a slightly smaller width on screen. The frame size (or bounds) and calculated width used within collectionViewLayout: UICollectionViewLayout sizeForItemAt are the same for all rows.

```<code>        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let settings = currentContents[indexPath.item]
    let height = CGFloat(30)

    // https://stackoverflow.com/questions/54915227/uicollectionview-remove-space-between-cells-with-7-items-per-row
    var cellWidth = CGFloat()
    let availableWidth = collectionView.bounds.size.width
    print("available width", availableWidth)
    let minimumWidth = floor(availableWidth / collectionContents.cellsPerRow5)
    print("minmum width", minimumWidth)
    cellWidth = minimumWidth * settings.portion - 1
    print("cell width", cellWidth)

    return CGSize(width: cellWidth, height: height)
}
</code>```

I'd like to get the bottom row to line up with the other rows, but can't imagine what is happening that is changing the widths after returning the value in the layout delegate method (or how to fix).

答:
UIKit does not like values with more than 2 decimals, round them or it will do it for you.

Here, UICollectionViewFlowLayout rounds your cell size and starts to fill the lines with an "interitemspacing" at least equal to the minimumInteritemSpacing you specified. On the last line, it used exactly the minimumInteritemSpacing value and doesn't fill entirely the line.

Fix it using better rounded values, giving the illusion that all is perfectly aligned.

I usually use those extensions:

```<code>extension CGFloat {
    func xx_rounded(_ rule: FloatingPointRoundingRule = .down, toDecimals decimals: Int = 2) -> CGFloat {
        let multiplier = CGFloat(pow(10.0, CGFloat(decimals)))
        return (self * multiplier).rounded(.down) / multiplier
    }
}

extension CGSize {
    func xx_rounded(rule: FloatingPointRoundingRule = .down, toDecimals: Int = 2) -> CGSize {
        return CGSize(
            width: width.xx_rounded(rule, toDecimals: toDecimals),
            height: height.xx_rounded(rule, toDecimals: toDecimals)
        )
    }
}
</code>```

Change:

```<code>return CGSize(width: cellWidth, height: height)
</code>```

to

```<code>return CGSize(width: cellWidth, height: height).xx_rounded()
</code>```

Body:
I've a fixed grid of collection view cells (UICollectionView) but the cells in the bottom row always appears with a slightly smaller width on screen. The frame size (or bounds) and calculated width used within collectionViewLayout: UICollectionViewLayout sizeForItemAt are the same for all rows.

        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let settings = currentContents[indexPath.item]
    let height = CGFloat(30)

    // https://stackoverflow.com/questions/54915227/uicollectionview-remove-space-between-cells-with-7-items-per-row
    var cellWidth = CGFloat()
    let availableWidth = collectionView.bounds.size.width
    print("available width", availableWidth)
    let minimumWidth = floor(availableWidth / collectionContents.cellsPerRow5)
    print("minmum width", minimumWidth)
    cellWidth = minimumWidth * settings.portion - 1
    print("cell width", cellWidth)

    return CGSize(width: cellWidth, height: height)
}

I'd like to get the bottom row to line up with the other rows, but can't imagine what is happening that is changing the widths after returning the value in the layout delegate method (or how to fix).

Body:
UIKit does not like values with more than 2 decimals, round them or it will do it for you.

Here, UICollectionViewFlowLayout rounds your cell size and starts to fill the lines with an "interitemspacing" at least equal to the minimumInteritemSpacing you specified. On the last line, it used exactly the minimumInteritemSpacing value and doesn't fill entirely the line.

Fix it using better rounded values, giving the illusion that all is perfectly aligned.

I usually use those extensions:

extension CGFloat {
    func xx_rounded(_ rule: FloatingPointRoundingRule = .down, toDecimals decimals: Int = 2) -> CGFloat {
        let multiplier = CGFloat(pow(10.0, CGFloat(decimals)))
        return (self * multiplier).rounded(.down) / multiplier
    }
}

extension CGSize {
    func xx_rounded(rule: FloatingPointRoundingRule = .down, toDecimals: Int = 2) -> CGSize {
        return CGSize(
            width: width.xx_rounded(rule, toDecimals: toDecimals),
            height: height.xx_rounded(rule, toDecimals: toDecimals)
        )
    }
}

Change:

return CGSize(width: cellWidth, height: height)

to

return CGSize(width: cellWidth, height: height).xx_rounded()


问:
Pointer to member function using C++ lambda
I'm trying to find a way to provide pointers to a member functions between different class instances. For the moment I'm able to provide pointers to member function that takes no arguments but cannot manage to do so when the function to point to has an argument.

A sample code to illustrate my problem :

```<code>#include <iostream>

class Event
{
public:
    std::string type;
    Event(std::string type):type(type){}
};

class EventDispatcherBase
{
public:

    void addEventListener(std::function<void(Event &event)> listener)
    {
        Event myEvent("Type of the myEvent object");
        listener(myEvent);
    }
};

class EventDispatcherClass:public EventDispatcherBase
{
public:
    EventDispatcherClass()
    {
        addEventListener([](Event &event){std::cout << event.type << std::endl;});
        //addEventListener([this]{listener(Event event);});
    };

    void listener(Event &event)
    {
        std::cout << event.type << std::endl;
    }
};

int main()
{
    EventDispatcherClass eventDispatcherClass;

    return 0;
}
</code>```

This code works with an anonymous lambda expression and output "Type of the myEvent object" in the console. But if I uncomment the line

```<code>addEventListener([this]{listener(Event event);});
</code>```

in the constructor of the EventDispatcherClass in order to transmit a pointer to the void listener(Event &event) member function, the compiler throw the following error :

no viable conversion from '(lambda at .../main.cpp:27:26)' to
  'std::function'

I don't understand why.

答:
The working line:

```<code>addEventListener([](Event &event){std::cout << event.type << std::endl;});
</code>```

looks nothing like the broken one:

```<code>//addEventListener([this]{listener(Event event);});
</code>```

so start by changing the working line bit by bit.

add the capture expression you will want, and it still works

```<code>addEventListener([this](Event &event){std::cout << event.type << std::endl;});
</code>```

change the body to the one you want, and it still works

```<code>addEventListener([this](Event &event){ this->listener(event); });
</code>```

If you're having trouble seeing what's different between the two versions - which is actually pretty common when you wrote them yourself and you're seeing what you intended to type instead of what's there - try changing the layout to line everything up (so you'd see the missing (Event &event)), or transforming one into the other step-by-step as above, or just replace one with the other and diff the file versions.

Body:
I'm trying to find a way to provide pointers to a member functions between different class instances. For the moment I'm able to provide pointers to member function that takes no arguments but cannot manage to do so when the function to point to has an argument.

A sample code to illustrate my problem :

#include <iostream>

class Event
{
public:
    std::string type;
    Event(std::string type):type(type){}
};

class EventDispatcherBase
{
public:

    void addEventListener(std::function<void(Event &event)> listener)
    {
        Event myEvent("Type of the myEvent object");
        listener(myEvent);
    }
};

class EventDispatcherClass:public EventDispatcherBase
{
public:
    EventDispatcherClass()
    {
        addEventListener([](Event &event){std::cout << event.type << std::endl;});
        //addEventListener([this]{listener(Event event);});
    };

    void listener(Event &event)
    {
        std::cout << event.type << std::endl;
    }
};

int main()
{
    EventDispatcherClass eventDispatcherClass;

    return 0;
}

This code works with an anonymous lambda expression and output "Type of the myEvent object" in the console. But if I uncomment the line

addEventListener([this]{listener(Event event);});

in the constructor of the EventDispatcherClass in order to transmit a pointer to the void listener(Event &event) member function, the compiler throw the following error :

no viable conversion from '(lambda at .../main.cpp:27:26)' to
  'std::function'

I don't understand why.

Body:
The working line:

addEventListener([](Event &event){std::cout << event.type << std::endl;});

looks nothing like the broken one:

//addEventListener([this]{listener(Event event);});

so start by changing the working line bit by bit.

add the capture expression you will want, and it still works

addEventListener([this](Event &event){std::cout << event.type << std::endl;});

change the body to the one you want, and it still works

addEventListener([this](Event &event){ this->listener(event); });

If you're having trouble seeing what's different between the two versions - which is actually pretty common when you wrote them yourself and you're seeing what you intended to type instead of what's there - try changing the layout to line everything up (so you'd see the missing (Event &event)), or transforming one into the other step-by-step as above, or just replace one with the other and diff the file versions.


问:
Swap elements in array without creating new array
I was asked for a method to return the arr if element == 5 to be pushed to the end of the array and if its not 5 to be pushed to the beginning of the arr have to do this without creating new array
could you please help me solve this one time with iterating .each
and another without .each
Using ruby

Ruby please

end

puts put_num5_last([5,3,5,2,5,1,4])

答:
You could fish the fives out of the array, and concatenate them to the end.

```<code>numbs = [5, 3, 5, 2, 5, 1, 4]
fives = numbs.select { |numb| numb == 5 }
numbs.delete(5)
numbs.concat(fives)

numbs #=> [3, 2, 1, 4, 5, 5, 5]
</code>```

This is not the most efficient solution, since both select and delete iterate over the full array. But this is the most readable. More efficient, but less readable would be:

```<code>numbs = [5, 3, 5, 2, 5, 1, 4]

# reverse loop to prevent shifting of elements that are not yet iterated
numbs.each_index.reverse_each do |index|
  next unless numbs[index] == 5
  numbs << numbs.delete_at(index)
end

numbs #=> [3, 2, 1, 4, 5, 5, 5]
</code>```

The above only loops once over the array, removing the value from the array and appending it to the end.

Body:
You could fish the fives out of the array, and concatenate them to the end.

numbs = [5, 3, 5, 2, 5, 1, 4]
fives = numbs.select { |numb| numb == 5 }
numbs.delete(5)
numbs.concat(fives)

numbs #=> [3, 2, 1, 4, 5, 5, 5]

This is not the most efficient solution, since both select and delete iterate over the full array. But this is the most readable. More efficient, but less readable would be:

numbs = [5, 3, 5, 2, 5, 1, 4]

# reverse loop to prevent shifting of elements that are not yet iterated
numbs.each_index.reverse_each do |index|
  next unless numbs[index] == 5
  numbs << numbs.delete_at(index)
end

numbs #=> [3, 2, 1, 4, 5, 5, 5]

The above only loops once over the array, removing the value from the array and appending it to the end.


问:
How to pass List<int> from C# to C++ CLi?
I am beginner in C language family...

So, problem is - in my solution I have a repo (wrote in C#) that store List<int>, also I have an engine that (wrote in C++). So, I need pass List from C# implementation to C++ CLI for executing...

As far as I understood problem is C++ know how to work with std::vector and C# know how to work with List and I need somehow convert List to vector...

How to do it?

Any assumption appropriate.

EDIT

Sorry for misunderstanding, but my CLI works as a mapper for pure C++ implementation. So, as far as I understood from C# I need to pass my List to C++ CLI , C++ CLI will convert a List to vector and invoke another C++ file with pure C++ implementation.

This is my solution

h file
    using namespace System;
    using namespace System::Collections::Generic;

```<code>//forward declaration
class MathCore;

namespace MathCore_CLI_namespace
{
public ref class MathCore_CLI
{
public:
    MathCore_CLI();
    ~MathCore_CLI();

    int computeMulPlusVals(List<int>^ list_first, List<int>^ list_second);
    //int computeMulPlusVals(std::vector<int> vect_first, std::vector<int> vect_second);

private:
    MathCore * m_pMathCore;
};
}
</code>```

cpp file

```<code>#include "stdafx.h"
#include "MathCore_CLI.h"
#include "..\Engine\MathCore.h"
#include <iostream>
#include <array>
using namespace System;
using namespace System::Collections::Generic;

namespace MathCore_CLI_namespace
{
const int size = 5;
int count = 0;
int arrayVal[size];

MathCore_CLI::MathCore_CLI()
{
    m_pMathCore = new MathCore();
}

MathCore_CLI::~MathCore_CLI()
{
    delete m_pMathCore;
}

int computeMulPlusVals(List<int>^ list_first, List<int>^ list_second)
{
    return 0;
}
}
</code>```

Error

What am I doind wrong?

答:
Also I found more optimized solution

```<code>int MathCore_CLI::computeMulPlusVals(array<int>^ arr_first, array<int>^ arr_second)
{
    auto vec_first = std::vector<int>(arr_first->Length);
    cli::pin_ptr<int> pPinnedFirst = &arr_first[0];
    memcpy(vec_first.data(), pPinnedFirst, arr_first->Length * sizeof(int));

    auto vec_second = std::vector<int>(arr_second->Length);
    cli::pin_ptr<int> pPinnedSecond = &arr_second[0];
    memcpy(vec_second.data(), pPinnedSecond, arr_second->Length * sizeof(int));

    return m_pMathCore->computeMulPlusVals(vec_first, vec_second);
}
</code>```

By steps

1) you need to create your vector
2) hold this memory in heap
3) just copy the data

It is going to be much more faster

Body:
I am beginner in C language family...

So, problem is - in my solution I have a repo (wrote in C#) that store List<int>, also I have an engine that (wrote in C++). So, I need pass List from C# implementation to C++ CLI for executing...

As far as I understood problem is C++ know how to work with std::vector and C# know how to work with List and I need somehow convert List to vector...

How to do it?

Any assumption appropriate.

EDIT

Sorry for misunderstanding, but my CLI works as a mapper for pure C++ implementation. So, as far as I understood from C# I need to pass my List to C++ CLI , C++ CLI will convert a List to vector and invoke another C++ file with pure C++ implementation.

This is my solution

h file
    using namespace System;
    using namespace System::Collections::Generic;

//forward declaration
class MathCore;

namespace MathCore_CLI_namespace
{
public ref class MathCore_CLI
{
public:
    MathCore_CLI();
    ~MathCore_CLI();

    int computeMulPlusVals(List<int>^ list_first, List<int>^ list_second);
    //int computeMulPlusVals(std::vector<int> vect_first, std::vector<int> vect_second);

private:
    MathCore * m_pMathCore;
};
}

cpp file

#include "stdafx.h"
#include "MathCore_CLI.h"
#include "..\Engine\MathCore.h"
#include <iostream>
#include <array>
using namespace System;
using namespace System::Collections::Generic;

namespace MathCore_CLI_namespace
{
const int size = 5;
int count = 0;
int arrayVal[size];

MathCore_CLI::MathCore_CLI()
{
    m_pMathCore = new MathCore();
}

MathCore_CLI::~MathCore_CLI()
{
    delete m_pMathCore;
}

int computeMulPlusVals(List<int>^ list_first, List<int>^ list_second)
{
    return 0;
}
}

Error

What am I doind wrong?

Body:
Also I found more optimized solution

int MathCore_CLI::computeMulPlusVals(array<int>^ arr_first, array<int>^ arr_second)
{
    auto vec_first = std::vector<int>(arr_first->Length);
    cli::pin_ptr<int> pPinnedFirst = &arr_first[0];
    memcpy(vec_first.data(), pPinnedFirst, arr_first->Length * sizeof(int));

    auto vec_second = std::vector<int>(arr_second->Length);
    cli::pin_ptr<int> pPinnedSecond = &arr_second[0];
    memcpy(vec_second.data(), pPinnedSecond, arr_second->Length * sizeof(int));

    return m_pMathCore->computeMulPlusVals(vec_first, vec_second);
}

By steps

1) you need to create your vector
2) hold this memory in heap
3) just copy the data

It is going to be much more faster


问:
IE7 Compatibility Issues
I'm (obviously) new to web development, and I'm just now realizing that my sites are pretty screwed up in some IE versions, but how do I fix them? How do I know what to change in the CSS and where, when multiple layers and divs aren't displaying properly?

Example: http://www.jwstudio.us/bkpa

Is there a resources for IE CSS fixes/compatibility? What about for the positioning and color differences between Safari/Apple and Windows browsers?

答:
Resources you will need:

Firstly, some sites with compatiblity charts to show you what features will work in various browsers:

Quirksmode.org - http://www.quirksmode.org/css/contents.html

CanIUse.com - http://caniuse.com/

Next, places to go for some hacks ("Polyfils") to improve compatiblity:

Modernizr - http://modernizr.com/

CSS3Pie - http://www.css3pie.com/

Dean Edwards' IE7.js - http://code.google.com/p/ie7-js/

Modernizr's collection of Polyfills - https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills

Finally, if you're not using it already, I recommend JQuery. It's a Javascript library that deals with a lot of the compatiblity issues.

Title: IE7 Compatibility Issues


答:
You may try checking out 1.txt at the commit before commit A, the first commit where you started making unwanted changes:

```<code>git checkout abc123 -- 1.txt
</code>```

This assumes your branch structure looks like this (with commit S having SHA-1 hash abc123):

```<code>S -- A -- B -- C
</code>```

Then, just add the change and commit.

Title: Git. How to roll back changes in certain file in a chain of commits?

Body:
I have a repo with three files in it - 1.txt, 2.txt and 3.txt. I created a branch 'new_branch' and made commits (let's call them A, B and C), every of these commits contains changes in several files from my repo. Then I understood, that 1.txt was updated mistakenly. Is it possible to remove changes, made in 1.txt, from commits A, B and C but keep changes in 2.txt and 3.txt?

UPD. I want also to remove changes, made it 1.txt, from commit history. As result 'git log -p' should show, that only 2.txt and 3.txt were modified in commits A, B and C.

Many thanks.

Body:
You may try checking out 1.txt at the commit before commit A, the first commit where you started making unwanted changes:

git checkout abc123 -- 1.txt

This assumes your branch structure looks like this (with commit S having SHA-1 hash abc123):

S -- A -- B -- C

Then, just add the change and commit.


问:
TFException: Expects arg[0] to be string but float is provided (Unity3d)
I am using Speech Commands Model Example from TensorFlow with the variables in Unity3d:

```<code>string WAV_INPUT = "wav_data";
        string SOFTMAX_NAME = "labels_softmax";
        string[] outputScoresNames = new string[] { SOFTMAX_NAME };
</code>```

and then add input to the model like this:

```<code> private void recognize(float[] audioFile)
    {
        //labels_softmax:0 output name
        //labels wav_data:0 input name from model
        string WAV_INPUT = "wav_data";
        string SOFTMAX_NAME = "labels_softmax";
        string[] outputScoresNames = new string[] { SOFTMAX_NAME };

        int how_many_labels = 4;
        string[] labels = new string[] { "_silence_" , "_unknown_", "stop","go"};

         TextAsset model = Resources.Load("GoStop") as TextAsset;
         TFGraph  graph = new TFGraph();
         graph.Import(model.bytes);

        TFSession session = new TFSession(graph);

        var runner = session.GetRunner();

        runner.AddInput(graph[WAV_INPUT][0], audioFile);
        runner.AddTarget(outputScoresNames);
        runner.Run();
       // float[] recurrent_tensor = runner.Run()[0].GetValue() as float[];

    }
</code>```

and the exception given for softmax is like that:

```<code>TFException: Expects arg[0] to be string but float is provided
TensorFlow.TFStatus.CheckMaybeRaise (TensorFlow.TFStatus incomingStatus, System.Boolean last) (at <1fe2de69842a4a4ba15256b83cca05f3>:0)
TensorFlow.TFSession.Run (TensorFlow.TFOutput[] inputs, TensorFlow.TFTensor[] inputValues, TensorFlow.TFOutput[] outputs, TensorFlow.TFOperation[] targetOpers, TensorFlow.TFBuffer runMetadata, TensorFlow.TFBuffer runOptions, TensorFlow.TFStatus status) (at <1fe2de69842a4a4ba15256b83cca05f3>:0)
TensorFlow.TFSession+Runner.Run (TensorFlow.TFStatus status) (at <1fe2de69842a4a4ba15256b83cca05f3>:0)
tensor.recognize (System.Single[] audioFile) (at Assets/tensor.cs:51)
tensor.Start () (at Assets/tensor.cs:23)
</code>```

is it a casting problem?and how to manage it to work with TensorFlowSharp?

答:
I was able to solve this problem by simply converting the value inside tensors to string.</p>

```<code> graph.Import(model.bytes);
 var session = new TFSession(graph);
 var runner = session.GetRunner();
 TFTensor tft = TFTensor.CreateString(array);
 runner.AddInput(graph[WAV_INPUT][0], tft);
 runner.Fetch(outputScoresNames);
 var output = runner.Run();
</code>```

Body:
I am using Speech Commands Model Example from TensorFlow with the variables in Unity3d:

string WAV_INPUT = "wav_data";
        string SOFTMAX_NAME = "labels_softmax";
        string[] outputScoresNames = new string[] { SOFTMAX_NAME };

and then add input to the model like this:

 private void recognize(float[] audioFile)
    {
        //labels_softmax:0 output name
        //labels wav_data:0 input name from model
        string WAV_INPUT = "wav_data";
        string SOFTMAX_NAME = "labels_softmax";
        string[] outputScoresNames = new string[] { SOFTMAX_NAME };

        int how_many_labels = 4;
        string[] labels = new string[] { "_silence_" , "_unknown_", "stop","go"};

         TextAsset model = Resources.Load("GoStop") as TextAsset;
         TFGraph  graph = new TFGraph();
         graph.Import(model.bytes);

        TFSession session = new TFSession(graph);

        var runner = session.GetRunner();

        runner.AddInput(graph[WAV_INPUT][0], audioFile);
        runner.AddTarget(outputScoresNames);
        runner.Run();
       // float[] recurrent_tensor = runner.Run()[0].GetValue() as float[];

    }

and the exception given for softmax is like that:

TFException: Expects arg[0] to be string but float is provided
TensorFlow.TFStatus.CheckMaybeRaise (TensorFlow.TFStatus incomingStatus, System.Boolean last) (at <1fe2de69842a4a4ba15256b83cca05f3>:0)
TensorFlow.TFSession.Run (TensorFlow.TFOutput[] inputs, TensorFlow.TFTensor[] inputValues, TensorFlow.TFOutput[] outputs, TensorFlow.TFOperation[] targetOpers, TensorFlow.TFBuffer runMetadata, TensorFlow.TFBuffer runOptions, TensorFlow.TFStatus status) (at <1fe2de69842a4a4ba15256b83cca05f3>:0)
TensorFlow.TFSession+Runner.Run (TensorFlow.TFStatus status) (at <1fe2de69842a4a4ba15256b83cca05f3>:0)
tensor.recognize (System.Single[] audioFile) (at Assets/tensor.cs:51)
tensor.Start () (at Assets/tensor.cs:23)

is it a casting problem?and how to manage it to work with TensorFlowSharp?

Body:
I was able to solve this problem by simply converting the value inside tensors to string.

 graph.Import(model.bytes);
 var session = new TFSession(graph);
 var runner = session.GetRunner();
 TFTensor tft = TFTensor.CreateString(array);
 runner.AddInput(graph[WAV_INPUT][0], tft);
 runner.Fetch(outputScoresNames);
 var output = runner.Run();


问:
SOAP call from Android with KSoap2 to .net WebServer
Good day everyone.

I'm trying to do a SOAP call to a .net WebServer running locally, but I think I'm missing something. The Android code seems fine to me. Maybe the SOAP request is wrong...

This is what the webserver gives for the method I'm trying to call:

```<code>POST /WebAvanza/WebAvanzaInterface.asmx HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <InitTransazione xmlns="http://tempuri.org/">
      <ip>string</ip>
      <codice>string</codice>
    </InitTransazione>
  </soap12:Body>
</soap12:Envelope>
</code>```

and this is what i wrote so far:

```<code>private String InitTransaction(String command){
        String NAMESPACE = "http://tempuri.org/";
        String METHOD_NAME = "InitTransazione";
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        request.addProperty("ip", ipAddress);
        request.addProperty("codice", command);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);

        HttpTransportSE httpTransport = new HttpTransportSE(URL);
        httpTransport.debug = true;

        String SOAP_ACTION = NAMESPACE + METHOD_NAME;

        Object result = null;
        try {
            httpTransport.call(SOAP_ACTION, envelope);
            result = envelope.getResponse();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return String.valueOf(result);
    }
</code>```

URL is http://192.168.168.24/WebAvanza/WebAvanzaInterface.asmx, the address refers to the machine where the server is running.

I only get an exception after executing httpTransport.call.

This is the StackTrace (if anybosy needs it)

```<code>W/System.err: android.os.NetworkOnMainThreadException
W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1528)
W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
W/System.err:     at java.net.Socket.connect(Socket.java:621)
W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:145)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
W/System.err:     at org.ksoap2.transport.ServiceConnectionSE.openOutputStream(ServiceConnectionSE.java:130)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.sendData(HttpTransportSE.java:295)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:184)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:118)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:113)
W/System.err:     at com.infovision.elcam_02.Operations$override.InitTransaction(Operations.java:64)
W/System.err:     at com.infovision.elcam_02.Operations$override.InitOperation(Operations.java:40)
W/System.err:     at com.infovision.elcam_02.Operations$override.access$dispatch(Unknown Source:49)
W/System.err:     at com.infovision.elcam_02.Operations.InitOperation(Unknown Source:15)
</code>```

答:
I found out that the problem was in the server and the code was fine...
Goddamn I spent almost 5 hours behind this .__.</p>

Body:
Good day everyone.

I'm trying to do a SOAP call to a .net WebServer running locally, but I think I'm missing something. The Android code seems fine to me. Maybe the SOAP request is wrong...

This is what the webserver gives for the method I'm trying to call:

POST /WebAvanza/WebAvanzaInterface.asmx HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <InitTransazione xmlns="http://tempuri.org/">
      <ip>string</ip>
      <codice>string</codice>
    </InitTransazione>
  </soap12:Body>
</soap12:Envelope>

and this is what i wrote so far:

private String InitTransaction(String command){
        String NAMESPACE = "http://tempuri.org/";
        String METHOD_NAME = "InitTransazione";
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        request.addProperty("ip", ipAddress);
        request.addProperty("codice", command);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);

        HttpTransportSE httpTransport = new HttpTransportSE(URL);
        httpTransport.debug = true;

        String SOAP_ACTION = NAMESPACE + METHOD_NAME;

        Object result = null;
        try {
            httpTransport.call(SOAP_ACTION, envelope);
            result = envelope.getResponse();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return String.valueOf(result);
    }

URL is http://192.168.168.24/WebAvanza/WebAvanzaInterface.asmx, the address refers to the machine where the server is running.

I only get an exception after executing httpTransport.call.

This is the StackTrace (if anybosy needs it)

W/System.err: android.os.NetworkOnMainThreadException
W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1528)
W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
W/System.err:     at java.net.Socket.connect(Socket.java:621)
W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:145)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
W/System.err:     at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
W/System.err:     at org.ksoap2.transport.ServiceConnectionSE.openOutputStream(ServiceConnectionSE.java:130)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.sendData(HttpTransportSE.java:295)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:184)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:118)
W/System.err:     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:113)
W/System.err:     at com.infovision.elcam_02.Operations$override.InitTransaction(Operations.java:64)
W/System.err:     at com.infovision.elcam_02.Operations$override.InitOperation(Operations.java:40)
W/System.err:     at com.infovision.elcam_02.Operations$override.access$dispatch(Unknown Source:49)
W/System.err:     at com.infovision.elcam_02.Operations.InitOperation(Unknown Source:15)


问:
Convert an array of hash with symbols
I have an array of hashes:

```<code>[{'object' => 'ob1', 'quantity' => '2'}, {'object' => 'ob2', 'quantity' => '3'}, .....]
</code>```

I want to convert it to symbolized form:

```<code>[{:object => 'ob1', :quantity => '2'}, {:object => 'ob2', :quantity => '3'}, .....]
</code>```

tried with:

```<code>symbolized_array = array.each => { |c| c.to_options }
</code>```

but i didn't obtained any conversion, the symbolized_array is same as array

why?

答:
Since ruby 2.5 there's Hash#transform_keys:

array.map{|hash| hash.transform_keys(&:to_sym) }
```

Before that it was available in activesupport (part of rails) along with shortcut symbolize_keys

Title: Convert an array of hash with symbols

Body:
I have an array of hashes:

[{'object' => 'ob1', 'quantity' => '2'}, {'object' => 'ob2', 'quantity' => '3'}, .....]

I want to convert it to symbolized form:

[{:object => 'ob1', :quantity => '2'}, {:object => 'ob2', :quantity => '3'}, .....]

tried with:

symbolized_array = array.each => { |c| c.to_options }

but i didn't obtained any conversion, the symbolized_array is same as array

why?

Body:
Since ruby 2.5 there's Hash#transform_keys:

array.map{|hash| hash.transform_keys(&:to_sym) }

Before that it was available in activesupport (part of rails) along with shortcut symbolize_keys


问:
Git... Branches Dedicated to CSS, Comments, & Refactoring? Is it a good idea?
My commit history for my github project is a big mess because I make so many different changes (especially with commenting) that makes it hard to see what has been changed. Recently I had the idea to put styling, commenting, and refactoring on separate branches, but I'm not sure the branching system was intended for that? I'm still learning git, but from what I understand branching is mainly used for working on a new feature. So my question is, is my idea practical, and if so how would it be implemented?

The alternative I suppose is just making a bunch of very small commits of refactors, commenting changes, etc. But that also doesn't seem like a great solution because then I'll have a ton of 1 and 2 line commits.

答:
Only branching won't solve your problem. Let's say you made a dedicated branch for CSS changes and made 10 small commits to it. Once the branch is merged in master, master will have those 10 commits as well.

Branching will surely help you to segregate your work of refactoring. What you can do in addition to branching is squashing your commits before they are merged in to master.
With squashing, you can turn your 10 commits in to one single commit and name it as CSS changes. And then you can merge that single commit to master.

You can do squashing with the help of interactive rebase.

Please note: Rebase is an operation that changes history. So, never try it on shared commits unless you know what you are doing. Rebase is absolutely safe if you have local commits that haven't been pushed to remote yer and you want to play [squash, delete, reorder, etc.] around them.


问:
Regular Expression in .NET
I should write a regex pattern in c# that checks for input string whether it conains certain characters and does not conain another characters, for example:
I want that the string contain only a-z, not contain (d,b) and the length of all the string longer than 5, I write "[a-z]{5,}", how can I avoid that the input contain d and b?

Additional question: Can I have option to condition in the regex, in other words if whichever boolian var equals true check somthing and if it equals false not check it?

Thanks

答:
A useful regex resource I always use is:

http://regexlib.com/

Helped me out many times.

Title: Regular Expression in .NET


问:
ImportError: No module named IPython
When i try to use from IPython.display import clear_output, display_html, then i show the error:

(ImportError: No module named IPython)

I am using Python 2.7.13, and im trying to make the game of life from John Conway. I am following this link: http://nbviewer.jupyter.org/url/norvig.com/ipython/Life.ipynb

I have read another questions and answers about it, but any answer works for me. First, this error is showed in command line, and when i try to run this code in a file. Second, this error is direct to IPython, not submodule or something similiar.

答:
Use this code to install the IPython library:

```<code>!pip install ipython
import IPython
</code>```

Well, this works on Google Colab.

Title: ImportError: No module named IPython

Body:
Use this code to install the IPython library:

!pip install ipython
import IPython

Well, this works on Google Colab.


问:
avoid repeating the dataframe name when operating on pandas columns
Very much a beginner question, sorry: is there a way to avoid repeating the dataframe name when operating on pandas columns?

In R, data.table allows to operate on a column without repeating the dataframe name like this

```<code>very_long_dt_name = data.table::data.table(col1=c(1,2,3),col2=c(3,3,1))

# operate on the columns without repeating the dt name:

very_long_dt_name[,ratio:=round(col1/col2,2)]
</code>```

I couldn't figure out how to do it with pandas in Python so I keep repeating the df name:

```<code>data = {'col1': [1,2,3], 'col2': [3, 3, 1]}
very_long_df_name = pd.DataFrame(data)

# operate on the columns requires repeating the df name

very_long_df_name['ratio'] = np.round(very_long_df_name['col1']/very_long_df_name['col2'],2)
</code>```

I'm sure there's a way to avoid it but I can't find anything on Google. Any hint please? Thank you.

答:
Try assign:

```<code>very_long_df_name.assign(ratio=lambda x: np.round(x.col1/x.col2,2))
</code>```

Output:

```<code>    col1    col2    ratio
0   1       3       0.33
1   2       3       0.67
2   3       1       3.00
</code>```

Edit: to reflect comments, tests on 1 million rows:

```<code>%%timeit
very_long_df_name.assign(ratio = lambda x:x.col1/x.col2)
# 18.6 ms ± 506 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

and

```<code>%%timeit
very_long_df_name['ratio'] = very_long_df_name['col1']/very_long_df_name['col2']
# 13.3 ms ± 359 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

And with np.round, assign

```<code>%%timeit
very_long_df_name.assign(ratio = lambda x: np.round(x.col1/x.col2,2))
# 64.8 ms ± 958 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

and not-assign:

```<code>%%timeit
very_long_df_name['ratio'] = np.round(very_long_df_name['col1']/very_long_df_name['col2'],2)
# 55.8 ms ± 2.43 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

SO it appears that assign is vectorized, just not as well tuned.

Body:
Very much a beginner question, sorry: is there a way to avoid repeating the dataframe name when operating on pandas columns?

In R, data.table allows to operate on a column without repeating the dataframe name like this

very_long_dt_name = data.table::data.table(col1=c(1,2,3),col2=c(3,3,1))

# operate on the columns without repeating the dt name:

very_long_dt_name[,ratio:=round(col1/col2,2)]

I couldn't figure out how to do it with pandas in Python so I keep repeating the df name:

data = {'col1': [1,2,3], 'col2': [3, 3, 1]}
very_long_df_name = pd.DataFrame(data)

# operate on the columns requires repeating the df name

very_long_df_name['ratio'] = np.round(very_long_df_name['col1']/very_long_df_name['col2'],2)

I'm sure there's a way to avoid it but I can't find anything on Google. Any hint please? Thank you.

Body:
Try assign:

very_long_df_name.assign(ratio=lambda x: np.round(x.col1/x.col2,2))

Output:

    col1    col2    ratio
0   1       3       0.33
1   2       3       0.67
2   3       1       3.00

Edit: to reflect comments, tests on 1 million rows:

%%timeit
very_long_df_name.assign(ratio = lambda x:x.col1/x.col2)
# 18.6 ms ± 506 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

and

%%timeit
very_long_df_name['ratio'] = very_long_df_name['col1']/very_long_df_name['col2']
# 13.3 ms ± 359 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

And with np.round, assign

%%timeit
very_long_df_name.assign(ratio = lambda x: np.round(x.col1/x.col2,2))
# 64.8 ms ± 958 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

and not-assign:

%%timeit
very_long_df_name['ratio'] = np.round(very_long_df_name['col1']/very_long_df_name['col2'],2)
# 55.8 ms ± 2.43 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

SO it appears that assign is vectorized, just not as well tuned.


问:
add user friendly json editor to django admin
I have a django app, using also rest_framework, and a model Product with field of type JSONField. so data is stored as JSON in Postgres, Now I want to provide the admin with a nice user friendly way on how he can change the json field (names/keys and values). is there an extension for that or is there a faster way on how to do that.

here is the column definition in the database.
my_column = JSONField(default={"editorial1": "text 1", "editorial_2": "text2", "editorial_3": "text"})

BOTH KEYS AND VALUES SHOULD BE EDITABLE BY THE ADMIN

The admin should not know anything about JSON, and should not enter/edit any json format field

答:
You can try https://github.com/jrief/django-entangled

In comparison to the editors mentioned above, it doesn't replace the widget used to render the JSON, but allows to override the ModelForm which otherwise is generated by Django's ModelAdmin.