问:
Gensim - Memory error using GoogleNews-vector model
I  getting memory error, when I use GoogleNews-vectors-negative300.bin or try to train a model with Gensim with wikipedia dataset corpus.(1 GB). I have 4GB RAM in my system. Is there any way to bypass this.

Can we host it on cloud service like AWS to get better speed ?

答:
No way to get away with 4G.
I could load and compute GoogleNews-vectors-negative300.bin on my 8G RAM Macbook Pro. However, when I loaded this gigantic pretrained vector on AWS, I had to upgrade it to 16G RAM because it was serving a webapp at the same time. So basically if you want to use it on webapp with the safety margin, you would need 16G.</p>


来源: stackexchange

问:
Can the elements of a two dimensional array be processed for some output in O(n) time?
Suppose that each row of an n*n array A consists of 1’s and 0’s such that, in any row of A, all the 1’s come before any 0’s in that row. Assuming A is already in memory, describe a method running in O(n) time for finding the row of A that contains the most 1’s.</p>

答:
start from 0th row and scan from right to left to encounter the first 1

When you reach the 1, update your answer. Suppose, the column is j.

Now for every row i from 1 to n, check if jth column holds 1.

If it holds 1, that means there can be 1 in right too. So try to move right until finding the rightmost 1 and update the answer and j

If it holds 0, we won't need to go left or right as we have better result already from previous rows.

This algorithm will scan atmost c * n elements in total for all rows where c is some small constant. So time complexity is O(n).

Moreover, You can use binary search to find the rightmost 1 for each row which will require less scan. At first, it seems binary search on each row will take O(nlogn), but the left boundary will reduce in each row resulting fewer scan.

Hope it helps!

ContentLicense: CC BY-SA 3.0


问:
How to properly look for a string in a file?
In this function, I am displaying a .txt document to the screen, which works, however, I am trying to read the file document and scan the document for the word EMPTY as I have it saved as a string variable. It should be noted that I am counting the time EMPTY is in the file and later printing the times it was would in the file along with on another thing. My first question is am I doing this correct?</p>

```<code> void allSeats(void)
    {
        int position = 0;
        int count = 0;
        char gone[6] = "EMPTY";

        system("cls");
    retry:
        fseatArrangement = fopen("airlineSeatingArrangment.txt", "r");
        while (fgets(econoAirSeatArrangement, 1000, fseatArrangement) != NULL)
            printf(econoAirSeatArrangement);
        fclose(fseatArrangement);

        while (count < FULL)
        {
            fgets(econoAirSeatArrangement, 1000, fseatArrangement);
            fscanf(fseatArrangement,"%s", &gone);
            count++;
        }
        printf("There are %d seats vacant at the moment\nThere are %d seats with no vacancy at the moment \n",count, FULL-count);

        printf("Enter Zero(0) Key to return to menu at anytime.");
            scanf("%d", &position);
            if (position == 0)
            {
                system("cls");
                menu();
            }
            else
            {
                system("cls");
                printf("INVALID INPUT! Please try again.\n");
                goto retry;
            }

        system("pause");
        return;

    }
</code>```

答:
The main problem is here

```<code> fgets(econoAirSeatArrangement, 1000, fseatArrangement);
</code>```

you have already closed the file pointer using fclose(), and yet, you try to use it. It  causes undefined behavior.

That said,

printf(econoAirSeatArrangement); appears wrong. If you do not wish to have any format conversion specification you can stick to puts().

You must check the return value of fopen(), fgets(), fscanf() etc. for success before using the returned value / scanned value.

Body:
In this function, I am displaying a .txt document to the screen, which works, however, I am trying to read the file document and scan the document for the word EMPTY as I have it saved as a string variable. It should be noted that I am counting the time EMPTY is in the file and later printing the times it was would in the file along with on another thing. My first question is am I doing this correct?

 void allSeats(void)
    {
        int position = 0;
        int count = 0;
        char gone[6] = "EMPTY";

        system("cls");
    retry:
        fseatArrangement = fopen("airlineSeatingArrangment.txt", "r");
        while (fgets(econoAirSeatArrangement, 1000, fseatArrangement) != NULL)
            printf(econoAirSeatArrangement);
        fclose(fseatArrangement);

        while (count < FULL)
        {
            fgets(econoAirSeatArrangement, 1000, fseatArrangement);
            fscanf(fseatArrangement,"%s", &gone);
            count++;
        }
        printf("There are %d seats vacant at the moment\nThere are %d seats with no vacancy at the moment \n",count, FULL-count);

        printf("Enter Zero(0) Key to return to menu at anytime.");
            scanf("%d", &position);
            if (position == 0)
            {
                system("cls");
                menu();
            }
            else
            {
                system("cls");
                printf("INVALID INPUT! Please try again.\n");
                goto retry;
            }

        system("pause");
        return;

    }

Body:
The main problem is here

 fgets(econoAirSeatArrangement, 1000, fseatArrangement);

you have already closed the file pointer using fclose(), and yet, you try to use it. It  causes undefined behavior.

That said,

printf(econoAirSeatArrangement); appears wrong. If you do not wish to have any format conversion specification you can stick to puts().

You must check the return value of fopen(), fgets(), fscanf() etc. for success before using the returned value / scanned value.


问:
Netcore library compatibility with universal windows app and others
I've developed a net core library app and posted on nuget for personal use.

Then later I created a universal windows app and tried to install this net core library via nuget then I get the following error.

```<code>Package restore failed. Rolling back package changes.
</code>```

My net core library app dependencies are netcore app version 1.1

The good thing about netcore app is that I can compile, unit test and update on mac which I use frequently but then I've to develop windows app as well down the road.

答:
For maximum portability, your class library should target .NET Standard, not .NET Core.

Targeting .NET Core means that your class library will be able to run on .NET Core only, and not on the .NET Framework, Mono, etc.

Check out the compatibility chart in the .NET Core documentation. It says that if you target any version of .NET Standard up to 1.4, that will allow you to target the Universal Windows Platform version 10 onwards.

If you need to target earlier versions or other frameworks, you can do so by multi-targeting your .NET Standard class library.

Body:
I've developed a net core library app and posted on nuget for personal use.

Then later I created a universal windows app and tried to install this net core library via nuget then I get the following error.

Package restore failed. Rolling back package changes.

My net core library app dependencies are netcore app version 1.1

The good thing about netcore app is that I can compile, unit test and update on mac which I use frequently but then I've to develop windows app as well down the road.


问:
What is the difference between find with grep?
What is the difference between these command:

```<code>find . –type f –name '*txt*'
</code>```

and

```<code>find . –type f | grep 'txt'
</code>```

I tried to run this and there is a difference but I want to know why?

答: When you have a path with txt in the directory name, the second command will find a match. When you do not want to match paths like txtfiles/allfiles.tgz and transactions/txtelevisions/bigscreen.jpg you will want to use the first.

Body:
What is the difference between these command:

find . –type f –name '*txt*'

and

find . –type f | grep 'txt'

I tried to run this and there is a difference but I want to know why?


问:
How does opengl depth testing use the 24bit depth buffer?
I am using 32bit float values which I input into the vertex shader for the x,y,z positions of every vertex. But, I have read that opengl uses 24bit for depth buffer and 8 bit for stencil buffer.

Since, I am copying the same 32bit float in gl_position that I receive as input in vertex shader, I want to understand how does opengl convert this 32bit float to 24bit for depth testing.

答:
The gl_Position in the vertex shader is a clip space coordinate. There will be a division by w to generate normalized device coordinates, where the visible range is [-1,1] in OpenGL (by default, can be changed nowadays). Those values will be transformed according to the currently set glDepthRange parameters to finally get the window space z value, which is in the range [0,1].

The depth buffer must just store these values, and - very similar to color values which often store only even 8 bit per channel values - an integer depth buffer is used to represent fixed point values in that range.

Quoting from setction 13.6 "coordinate transformations" of the OpenGL 4.5 core profile spec (emphasis mine):

z_w may be represented using either a fixed-point or floating-point representation.
  However, a floating-point representation must be used if the draw framebuffer has a floating-point depth buffer. If an
  m-bit fixed-point representation is used,  we
  assume that it represents each value k/(2^m-1),
  where k in {0,1,...,2^m- 1}, as k (e.g. 1.0 is represented in binary as a string of all ones).

So, the window space z_w value (which is in [0,1]) is just multiplied by 2^m -1, and rounded to integer, and the result is stored in the buffer.


问:
Adding buttons from a dictionary in PyQt
I'm trying to make a bunch of buttons from a dictionary. In my case have to use a scrollbar, cause there's more than 200 keys. I've tried to use example in this link: link. However, no success

Here is my code:

```<code>import sys
import json
import time
from PyQt4 import QtCore, QtGui

class Form(QtGui.QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.scrollArea = QtGui.QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)
        self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea)
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 380, 247))
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.verticalLayout.addWidget(self.scrollArea)
        self.verticalLayoutScroll =
        QtGui.QVBoxLayout(self.scrollAreaWidgetContents)

        self.make_form()

    def make_form(self):
        with open('list.json', 'r') as f:
            data = json.load(f)
        for item in data.keys():
            button_name = item
            button = QtGui.QPushButton(self.scrollAreaWidgetContents)
            button.setText(button_name)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    form = Form()
    form.show()

    sys.exit(app.exec_())
</code>```

答:
You must add the buttons to self.verticalLayoutScroll:

```<code>self.verticalLayoutScroll.addWidget(button)
</code>```

Complete code:

```<code>import sys
import json
import time
from PyQt4 import QtCore, QtGui

class Form(QtGui.QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.scrollArea = QtGui.QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)
        self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea)
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 380, 247))
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.verticalLayout.addWidget(self.scrollArea)
        self.verticalLayoutScroll = QtGui.QVBoxLayout(self.scrollAreaWidgetContents)

        self.make_form()

    def make_form(self):
        with open('list.json', 'r') as f:
            data = json.load(f)
            for item in data.keys():
                button_name = item
                button = QtGui.QPushButton(self.scrollAreaWidgetContents)
                self.verticalLayoutScroll.addWidget(button)
                button.setText(button_name)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    form = Form()
    form.show()

    sys.exit(app.exec_())
</code>```

Body:
I'm trying to make a bunch of buttons from a dictionary. In my case have to use a scrollbar, cause there's more than 200 keys. I've tried to use example in this link: link. However, no success

Here is my code:

import sys
import json
import time
from PyQt4 import QtCore, QtGui

class Form(QtGui.QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.scrollArea = QtGui.QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)
        self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea)
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 380, 247))
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.verticalLayout.addWidget(self.scrollArea)
        self.verticalLayoutScroll =
        QtGui.QVBoxLayout(self.scrollAreaWidgetContents)

        self.make_form()

    def make_form(self):
        with open('list.json', 'r') as f:
            data = json.load(f)
        for item in data.keys():
            button_name = item
            button = QtGui.QPushButton(self.scrollAreaWidgetContents)
            button.setText(button_name)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    form = Form()
    form.show()

    sys.exit(app.exec_())

Body:
You must add the buttons to self.verticalLayoutScroll:

self.verticalLayoutScroll.addWidget(button)

Complete code:

import sys
import json
import time
from PyQt4 import QtCore, QtGui

class Form(QtGui.QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.scrollArea = QtGui.QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)
        self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea)
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 380, 247))
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.verticalLayout.addWidget(self.scrollArea)
        self.verticalLayoutScroll = QtGui.QVBoxLayout(self.scrollAreaWidgetContents)

        self.make_form()

    def make_form(self):
        with open('list.json', 'r') as f:
            data = json.load(f)
            for item in data.keys():
                button_name = item
                button = QtGui.QPushButton(self.scrollAreaWidgetContents)
                self.verticalLayoutScroll.addWidget(button)
                button.setText(button_name)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    form = Form()
    form.show()

    sys.exit(app.exec_())


问:
Aggregate an entire mongodb object using pymongo
I have a database containing some large objects, with always the same keys/structure:

```<code>{
  "stats": {
    "a": 100
    "b": 0
    "c": 30
    "d": 20
    ...
    "z": 100
  }
},
{
  "stats": {
    "a": 200
    "b": 2
    "c": 10
    "d": 40
    ...
    "z": 100
  }
}
</code>```

I would like to know if there is a way to aggregate all stats sub-object without specifying all their fields using PyMongo. The desired output would be this:

```<code>"stats": {
  "a": 150
  "b": 1
  "c": 20
  "d": 30
  ...
  "z": 100
}
</code>```

I found this: Mongodb Is it possible to aggregate an object? but I am kinda unsure of how to use it in PyMongo.

EDIT: I could list all fields and aggregate them, but I am looking for a solution not listing those fields (I have approximately 100 of them).

答:
There is not a built-in to do what you're asking, at least not that I am aware of.

One thing that you could do is dynamically build the pipeline in Python. Since every document has the same fields, you could do a find_one and use that to get the set of fields and build an aggregation pipeline from that.

For example:

```<code>import pprint
from pymongo import MongoClient
client = MongoClient()

pp = pprint.PrettyPrinter(indent=4)
db = MongoClient().test
collection = db.foo

pipeline = [{
    '$group': {
        '_id' : None
     }
}]

group = pipeline[0]['$group']

doc = collection.find_one()

for k in doc['stats']:
    group[k] = {'$avg' : '$stats.'+k}

pp.pprint(pipeline)

cursor = collection.aggregate(pipeline, allowDiskUse=True)

for doc in cursor:
    pp.pprint(doc)
</code>```

Output:

```<code>[   {   '$group': {   '_id': None,
                      u'a': {   '$avg': u'$stats.a'},
                      u'b': {   '$avg': u'$stats.b'},
                      u'c': {   '$avg': u'$stats.c'},
                      u'd': {   '$avg': u'$stats.d'},
                      u'z': {   '$avg': u'$stats.z'}}}]
{   u'_id': None, u'a': 150.0, u'b': 1.0, u'c': 20.0, u'd': 30.0, u'z': 100.0}
</code>```

Body:
I have a database containing some large objects, with always the same keys/structure:

{
  "stats": {
    "a": 100
    "b": 0
    "c": 30
    "d": 20
    ...
    "z": 100
  }
},
{
  "stats": {
    "a": 200
    "b": 2
    "c": 10
    "d": 40
    ...
    "z": 100
  }
}

I would like to know if there is a way to aggregate all stats sub-object without specifying all their fields using PyMongo. The desired output would be this:

"stats": {
  "a": 150
  "b": 1
  "c": 20
  "d": 30
  ...
  "z": 100
}

I found this: Mongodb Is it possible to aggregate an object? but I am kinda unsure of how to use it in PyMongo.

EDIT: I could list all fields and aggregate them, but I am looking for a solution not listing those fields (I have approximately 100 of them).

Body:
There is not a built-in to do what you're asking, at least not that I am aware of.

One thing that you could do is dynamically build the pipeline in Python. Since every document has the same fields, you could do a find_one and use that to get the set of fields and build an aggregation pipeline from that.

For example:

import pprint
from pymongo import MongoClient
client = MongoClient()

pp = pprint.PrettyPrinter(indent=4)
db = MongoClient().test
collection = db.foo

pipeline = [{
    '$group': {
        '_id' : None
     }
}]

group = pipeline[0]['$group']

doc = collection.find_one()

for k in doc['stats']:
    group[k] = {'$avg' : '$stats.'+k}

pp.pprint(pipeline)

cursor = collection.aggregate(pipeline, allowDiskUse=True)

for doc in cursor:
    pp.pprint(doc)

Output:

[   {   '$group': {   '_id': None,
                      u'a': {   '$avg': u'$stats.a'},
                      u'b': {   '$avg': u'$stats.b'},
                      u'c': {   '$avg': u'$stats.c'},
                      u'd': {   '$avg': u'$stats.d'},
                      u'z': {   '$avg': u'$stats.z'}}}]
{   u'_id': None, u'a': 150.0, u'b': 1.0, u'c': 20.0, u'd': 30.0, u'z': 100.0}


问:
ManyToOne Doctrine Database Relation with Extra Field Symfony 3
I'm just new in Symfony so please bear with me.

I want to create a database relationship in Symfony, let say..

I have Entity Currency, AddRate and AddRateCurrency
These entities would accomplish 3 simple things.

The User will gonna add different types of currencies using Currency entity.

The User will gonna choose which branch these currencies must be added using AddRate entity.

The User will gonna update the rates of each currency using AddRateCurrency.

The problem that I encountered is

Expected value of type "Doctrine\Common\Collections\Collection|array"
  for association field "MontealBundle\Entity\AddRate#$currency", got
  "MontealBundle\Entity\Currency" instead.

On adding rate AddRateForm I used EntityType to embed my form.

```<code> public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('branch', EntityType::class, array(
                'label' => 'Branch',
                'class'=>'MontealBundle\Entity\Branch',
                'query_builder' => function (BranchRepository $er) {
                    return $er->findAllActiveBranches();
                },
                'choice_label' => 'name',
                'placeholder' => 'Choose a Branch',
                'empty_data' => null,
                'required' => true,
                'constraints' => array(
                    new NotBlank(array("message" => 'Branch is required.'))
                )
            ))
            ->add('currency', EntityType::class, array(
                'label' => 'Currency',
                'class'=>'MontealBundle\Entity\Currency',
                'query_builder' => function (CurrencyRepository $er) {
                    return $er->findAllActiveCurrencies();
                },
                'choice_label' => 'currency',
                'placeholder' => 'Choose a Currency',
                'empty_data' => null,
                'multiple' => true,
                // 'expanded' => true,
                'required' => true,
                'constraints' => array(
                    new NotBlank(array("message" => 'Currency is required.'))
                )
            ))
        ;
    }
</code>```

On Currency Entity

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="currency")
 * @ORM\Entity(repositoryClass="MontealBundle\Repository\CurrencyRepository")
 * @ORM\HasLifecycleCallbacks()
 * @UniqueEntity(fields={"code"}, message="Code is already used.")
 * @UniqueEntity(fields={"currency"}, message="Currency is already used.")
 */
class Currency
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Administrator")
     * @ORM\JoinColumn(name="administrator_id", referencedColumnName="id")
     */
    private $administrator;

    /**
     * @ORM\Column(type="string", unique=true)
     */
    private $currency;

    /**
     * @ORM\Column(type="string", unique=true)
     */
    private $code;

    /**
     * @ORM\Column(type="integer")
     */
    private $status;

    /**
     * @ORM\Column(type="date")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="date", nullable=true)
     */
    private $updatedAt;

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getAdministrator()
    {
        return $this->administrator;
    }

    /**
     * @param mixed $administrator
     */
    public function setAdministrator($administrator)
    {
        $this->administrator = $administrator;
    }

    /**
     * @return mixed
     */
    public function getCurrency()
    {
        return $this->currency;
    }

    /**
     * @param mixed $currency
     */
    public function setCurrency($currency)
    {
        $this->currency = $currency;
    }

    /**
     * @return mixed
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * @param mixed $code
     */
    public function setCode($code)
    {
        $this->code = $code;
    }

    /**
     * @return mixed
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * @param mixed $status
     */
    public function setStatus($status)
    {
        $this->status = $status;
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @ORM\PrePersist
     */
    public function setCreatedAt()
    {
        $this->createdAt = new \DateTime();
    }

    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * @ORM\PreUpdate()
     */
    public function setUpdatedAt()
    {
        $this->updatedAt = new \DateTime();
    }
}
</code>```

On AddRate Entity

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="add_rate")
 * @ORM\Entity(repositoryClass="MontealBundle\Repository\AddRateRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class AddRate
{

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Branch")
     * @ORM\JoinColumn(name="branch_id", referencedColumnName="id")
     */
    private $branch;

    /**
     * @ORM\OneToMany(targetEntity="AddRateCurrency", mappedBy="add_rate")
     */
    private $currency;

    public function __construct()
    {
        $this->currency = new ArrayCollection();
    }

    /**
     * @ORM\ManyToOne(targetEntity="Administrator")
     * @ORM\JoinColumn(name="administrator_id", referencedColumnName="id")
     */
    private $administrator;

    /**
     * @ORM\Column(type="date")
     */
    private $createdAt;

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getBranch()
    {
        return $this->branch;
    }

    /**
     * @param mixed $branch
     */
    public function setBranch($branch)
    {
        $this->branch = $branch;
    }

    /**
     * @return mixed
     */
    public function getCurrency()
    {
        return $this->currency;
    }

    /**
     * @param mixed $currency
     */
    public function setCurrency($currency)
    {
        $this->currency = $currency;
    }

    public function addCurrency(Currency $currency) {
        $this->currency[] = $currency;
    }

    /**
     * @return mixed
     */
    public function getAdministrator()
    {
        return $this->administrator;
    }

    /**
     * @param mixed $administrator
     */
    public function setAdministrator($administrator)
    {
        $this->administrator = $administrator;
    }

    /**
     * @ORM\PrePersist
     */
    public function setCreatedAt()
    {
        $this->createdAt = new \DateTime();
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }
}
</code>```

On AddRateCurrency Entity

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="add_rate_currency")
 */
class AddRateCurrency
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="AddRate", inversedBy="AddRateCurrency")
     * @ORM\JoinColumn(nullable=false)
     */
    private $currency;

    /**
     * @ORM\Column(type="string")
     */
    private $rate;

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getCurrency()
    {
        return $this->currency;
    }

    /**
     * @param mixed $currency
     */
    public function setCurrency($currency)
    {
        $this->currency = $currency;
    }

    /**
     * @return mixed
     */
    public function getRate()
    {
        return $this->rate;
    }

    /**
     * @param mixed $rate
     */
    public function setRate($rate)
    {
        $this->rate = $rate;
    }

}
</code>```

答:
In your AddRate entity, remove the setCurrency function. Symfony will then (automatically) use your addCurrency function instead since $currency is an ArrayCollection.

Your choice of variable names adds to the confusion somewhat. In AddRate, you may want to consider renaming $currency to $currencies.

Body:
I'm just new in Symfony so please bear with me.

I want to create a database relationship in Symfony, let say..

I have Entity Currency, AddRate and AddRateCurrency
These entities would accomplish 3 simple things.

The User will gonna add different types of currencies using Currency entity.

The User will gonna choose which branch these currencies must be added using AddRate entity.

The User will gonna update the rates of each currency using AddRateCurrency.

The problem that I encountered is

Expected value of type "Doctrine\Common\Collections\Collection|array"
  for association field "MontealBundle\Entity\AddRate#$currency", got
  "MontealBundle\Entity\Currency" instead.

On adding rate AddRateForm I used EntityType to embed my form.

 public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('branch', EntityType::class, array(
                'label' => 'Branch',
                'class'=>'MontealBundle\Entity\Branch',
                'query_builder' => function (BranchRepository $er) {
                    return $er->findAllActiveBranches();
                },
                'choice_label' => 'name',
                'placeholder' => 'Choose a Branch',
                'empty_data' => null,
                'required' => true,
                'constraints' => array(
                    new NotBlank(array("message" => 'Branch is required.'))
                )
            ))
            ->add('currency', EntityType::class, array(
                'label' => 'Currency',
                'class'=>'MontealBundle\Entity\Currency',
                'query_builder' => function (CurrencyRepository $er) {
                    return $er->findAllActiveCurrencies();
                },
                'choice_label' => 'currency',
                'placeholder' => 'Choose a Currency',
                'empty_data' => null,
                'multiple' => true,
                // 'expanded' => true,
                'required' => true,
                'constraints' => array(
                    new NotBlank(array("message" => 'Currency is required.'))
                )
            ))
        ;
    }

On Currency Entity

/**
 * @ORM\Entity
 * @ORM\Table(name="currency")
 * @ORM\Entity(repositoryClass="MontealBundle\Repository\CurrencyRepository")
 * @ORM\HasLifecycleCallbacks()
 * @UniqueEntity(fields={"code"}, message="Code is already used.")
 * @UniqueEntity(fields={"currency"}, message="Currency is already used.")
 */
class Currency
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Administrator")
     * @ORM\JoinColumn(name="administrator_id", referencedColumnName="id")
     */
    private $administrator;

    /**
     * @ORM\Column(type="string", unique=true)
     */
    private $currency;

    /**
     * @ORM\Column(type="string", unique=true)
     */
    private $code;

    /**
     * @ORM\Column(type="integer")
     */
    private $status;

    /**
     * @ORM\Column(type="date")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="date", nullable=true)
     */
    private $updatedAt;

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getAdministrator()
    {
        return $this->administrator;
    }

    /**
     * @param mixed $administrator
     */
    public function setAdministrator($administrator)
    {
        $this->administrator = $administrator;
    }

    /**
     * @return mixed
     */
    public function getCurrency()
    {
        return $this->currency;
    }

    /**
     * @param mixed $currency
     */
    public function setCurrency($currency)
    {
        $this->currency = $currency;
    }

    /**
     * @return mixed
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * @param mixed $code
     */
    public function setCode($code)
    {
        $this->code = $code;
    }

    /**
     * @return mixed
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * @param mixed $status
     */
    public function setStatus($status)
    {
        $this->status = $status;
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @ORM\PrePersist
     */
    public function setCreatedAt()
    {
        $this->createdAt = new \DateTime();
    }

    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * @ORM\PreUpdate()
     */
    public function setUpdatedAt()
    {
        $this->updatedAt = new \DateTime();
    }
}

On AddRate Entity

/**
 * @ORM\Entity
 * @ORM\Table(name="add_rate")
 * @ORM\Entity(repositoryClass="MontealBundle\Repository\AddRateRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class AddRate
{

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Branch")
     * @ORM\JoinColumn(name="branch_id", referencedColumnName="id")
     */
    private $branch;

    /**
     * @ORM\OneToMany(targetEntity="AddRateCurrency", mappedBy="add_rate")
     */
    private $currency;

    public function __construct()
    {
        $this->currency = new ArrayCollection();
    }

    /**
     * @ORM\ManyToOne(targetEntity="Administrator")
     * @ORM\JoinColumn(name="administrator_id", referencedColumnName="id")
     */
    private $administrator;

    /**
     * @ORM\Column(type="date")
     */
    private $createdAt;

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getBranch()
    {
        return $this->branch;
    }

    /**
     * @param mixed $branch
     */
    public function setBranch($branch)
    {
        $this->branch = $branch;
    }

    /**
     * @return mixed
     */
    public function getCurrency()
    {
        return $this->currency;
    }

    /**
     * @param mixed $currency
     */
    public function setCurrency($currency)
    {
        $this->currency = $currency;
    }

    public function addCurrency(Currency $currency) {
        $this->currency[] = $currency;
    }

    /**
     * @return mixed
     */
    public function getAdministrator()
    {
        return $this->administrator;
    }

    /**
     * @param mixed $administrator
     */
    public function setAdministrator($administrator)
    {
        $this->administrator = $administrator;
    }

    /**
     * @ORM\PrePersist
     */
    public function setCreatedAt()
    {
        $this->createdAt = new \DateTime();
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }
}

On AddRateCurrency Entity

/**
 * @ORM\Entity
 * @ORM\Table(name="add_rate_currency")
 */
class AddRateCurrency
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="AddRate", inversedBy="AddRateCurrency")
     * @ORM\JoinColumn(nullable=false)
     */
    private $currency;

    /**
     * @ORM\Column(type="string")
     */
    private $rate;

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getCurrency()
    {
        return $this->currency;
    }

    /**
     * @param mixed $currency
     */
    public function setCurrency($currency)
    {
        $this->currency = $currency;
    }

    /**
     * @return mixed
     */
    public function getRate()
    {
        return $this->rate;
    }

    /**
     * @param mixed $rate
     */
    public function setRate($rate)
    {
        $this->rate = $rate;
    }

}


问:
Javascript: How to get/select all object with same keys?
I have object like this:

```<code>[
  {
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  },
  {
    "id": 3,
    "name": "App 3",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app3",
    "kat": "tei"
  },
  {
    "id": 4,
    "name": "App 4",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app4",
    "kat": "tei"
  },
  {
    "id": 5,
    "name": "App 5",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app5",
    "kat": "tei"
  }
]
</code>```

How i get/select all object with same keys (kat) in javascript?

example i want to get all object with kat=tkj will return:

```<code>[{
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  }]
</code>```

Thanks for your help ^_^

答:
use the filter method on your array in a more generic way</p>

```<code>var yourArray; //the array in your exemple

key = 'kat'; // the key you want to filter the array accordingly
value = 'tkj'; // the matching value for that key
var filteredArray = yourArray.filter(function(item){
 return item[key] === value
}
</code>```

Body:
I have object like this:

[
  {
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  },
  {
    "id": 3,
    "name": "App 3",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app3",
    "kat": "tei"
  },
  {
    "id": 4,
    "name": "App 4",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app4",
    "kat": "tei"
  },
  {
    "id": 5,
    "name": "App 5",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app5",
    "kat": "tei"
  }
]

How i get/select all object with same keys (kat) in javascript?

example i want to get all object with kat=tkj will return:

[{
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  }]

Thanks for your help ^_^

Body:
use the filter method on your array in a more generic way

var yourArray; //the array in your exemple

key = 'kat'; // the key you want to filter the array accordingly
value = 'tkj'; // the matching value for that key
var filteredArray = yourArray.filter(function(item){
 return item[key] === value
}


问:
Join lines automatically using autohotkey
Long paragraphs in Adobe Acrobat results in a line break when text is copied to clipboard and pasted in Word.

To deal with this, I manually paste the copied-text in Notepad ++ > select all > ctrl+J (join lines) > select all > Copy...... and then paste it into my Word document.

I would like to automate this join line using autohotkey as I have a large body of documents to go through. I can't seem to find any examples online in dealing with this directly within autohotkey script.

Ex.

```<code>Data structures with labeled axes supporting automatic or explicit data alignment.
This prevents common errors resulting from misaligned data and working with
differently-indexed data coming from different sources.
</code>```

After manually joining in Notepad ++

```<code>Data structures with labeled axes supporting automatic or explicit data alignment. This prevents common errors resulting from misaligned data and working with differently-indexed data coming from different sources.
</code>```

答:
This works: </p>

```<code>#Persistent
OnClipboardChange("ClipChanged")
return

ClipChanged() {

    If (WinActive("ahk_exe AcroRd32.exe")) {
        For e, v in StrSplit(clipboard, "`n", "`r")
            x .= v " "
        clipboard := trim(x)
    }
}
</code>```

Body:
Long paragraphs in Adobe Acrobat results in a line break when text is copied to clipboard and pasted in Word.

To deal with this, I manually paste the copied-text in Notepad ++ > select all > ctrl+J (join lines) > select all > Copy...... and then paste it into my Word document.

I would like to automate this join line using autohotkey as I have a large body of documents to go through. I can't seem to find any examples online in dealing with this directly within autohotkey script.

Ex.

Data structures with labeled axes supporting automatic or explicit data alignment.
This prevents common errors resulting from misaligned data and working with
differently-indexed data coming from different sources.

After manually joining in Notepad ++

Data structures with labeled axes supporting automatic or explicit data alignment. This prevents common errors resulting from misaligned data and working with differently-indexed data coming from different sources.

Body:
This works:

#Persistent
OnClipboardChange("ClipChanged")
return

ClipChanged() {

    If (WinActive("ahk_exe AcroRd32.exe")) {
        For e, v in StrSplit(clipboard, "`n", "`r")
            x .= v " "
        clipboard := trim(x)
    }
}


问:
typeof typeof x returns string and not object since type of null is object
I am new to js, trying to learn js, can you guys tell me why typeof typeof x returns string, providing code snippet below, if i understand this simple concept it will help me more:

```<code>var x=null;
console.log(typeof typeof x);
</code>```

答:
typeof operator to find the data type of a JavaScript variable
// This stands since the beginning of JavaScript
typeof null === 'object';</p>

```<code>var x=null;
var x=(typeof x);
it returns "object";
var y=typeof "object";
it returns string
so
console.log(typeof typeof x);
show string
</code>```

Body:
I am new to js, trying to learn js, can you guys tell me why typeof typeof x returns string, providing code snippet below, if i understand this simple concept it will help me more:

var x=null;
console.log(typeof typeof x);

Body:
typeof operator to find the data type of a JavaScript variable
// This stands since the beginning of JavaScript
typeof null === 'object';

var x=null;
var x=(typeof x);
it returns "object";
var y=typeof "object";
it returns string
so
console.log(typeof typeof x);
show string


问:
Filter out rows not containing certain words?
In MATLAB (R2015b) I have a very large Cell C containing multiple column vectors that can be simplified as:

```<code>C = [9000x1 double] [9000x1 double] {9000x1 cell} {9000x1 cell}
</code>```

The last two columns in C, the two cells (9000x1 cell), the first cell-column contains the words 'GREN' or 'BLU', and the second cell-column contains the words 'OVR' or 'UNDR' randomly.

So, in my mind, for example the first four rows of C may have the appearance of:

```<code>[ 123 54.3 'BLU' 'UNDR'; 125 51.3 'GREN' 'OVR'; 128 55.1 'GREN' 'UNDR'; 129 51.1 'BLU' 'OVR']
</code>```

How can I filter out the rows that do NOT contain the words 'BLU' and/or 'OVR'? I.e. so that the example above becomes:

```<code>[ 123 54.3 'BLU' 'UNDR'; 125 51.3 'GREN' 'OVR'; 129 51.1 'BLU' 'OVR']
</code>```

I've tried converting the cells into matrix format (cell2mat) and then filter the matrix without any luck. Thanks in advance!

Body:
In MATLAB (R2015b) I have a very large Cell C containing multiple column vectors that can be simplified as:

C = [9000x1 double] [9000x1 double] {9000x1 cell} {9000x1 cell}

The last two columns in C, the two cells (9000x1 cell), the first cell-column contains the words 'GREN' or 'BLU', and the second cell-column contains the words 'OVR' or 'UNDR' randomly.

So, in my mind, for example the first four rows of C may have the appearance of:

[ 123 54.3 'BLU' 'UNDR'; 125 51.3 'GREN' 'OVR'; 128 55.1 'GREN' 'UNDR'; 129 51.1 'BLU' 'OVR']

How can I filter out the rows that do NOT contain the words 'BLU' and/or 'OVR'? I.e. so that the example above becomes:

[ 123 54.3 'BLU' 'UNDR'; 125 51.3 'GREN' 'OVR'; 129 51.1 'BLU' 'OVR']

I've tried converting the cells into matrix format (cell2mat) and then filter the matrix without any luck. Thanks in advance!

Body:
using strcmp:

C = { 123, 54.3 ,'BLU', 'UNDR'; 125, 51.3, 'GREN', 'OVR'; 128, 55.1, 'GREN', 'UNDR'; 129,51.1,'BLU','OVR'};
idxs = strcmp(C(:,3),'BLU') | strcmp(C(:,4),'OVR');
CC = C(idxs,:)


问:
remove image and its container if image is broken
I am just trying to remove image and its title in case if image fails to load or broken using html or JavaScript.what is the best and easiest way to do that?

```<code><?php

   include("../includes/db.php");   // ../ means go to parent directory
  $query='SELECT * FROM `table` WHERE tag NOT IN("news") ORDER BY `id` DESC LIMIT 0,5';
  $run=mysqli_query($conn,$query);
  while($row=mysqli_fetch_array($run)){
         $img=$row['src'];
         $title=$row['title'];
   ?>

       <table class='mobileTable'>
          <tr> <td><img src='<?php echo $img ?>' onerror='imgError(this)' /></td></tr>
          <tr> <td  class='mobMidTitle'><?php echo $title ?></td></tr>//i want to remove this title as well
       </table>
   <?php } ?>

 <script>
 function imgError(image) {
    image.onerror = "";
    image.src = "http://localhost/domain/images/error.jpg";
    document.getElementById('tit').style.display='none';
    return true;
}</script>
</code>```

code above will fetch 5 images from database and with  javascript i can change image to error.jpg but i want to remove both image as well as its title only of failed image.

答:
You can replace image if img tag has broken image. Please check below code</p>

```<code><img src='brokenimage.jpg' onError="ImageError(this);">

<script language="JavaScript">
  function ImageError(img)
  {
    img.src = "https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
  }

</script>
</code>```

Body:
I am just trying to remove image and its title in case if image fails to load or broken using html or JavaScript.what is the best and easiest way to do that?

<?php

   include("../includes/db.php");   // ../ means go to parent directory
  $query='SELECT * FROM `table` WHERE tag NOT IN("news") ORDER BY `id` DESC LIMIT 0,5';
  $run=mysqli_query($conn,$query);
  while($row=mysqli_fetch_array($run)){
         $img=$row['src'];
         $title=$row['title'];
   ?>

 <img src='<?php echo $img ?>' onerror='imgError(this)' />

 <?php echo $title ?>
//i want to remove this title as well

   <?php } ?>

code above will fetch 5 images from database and with  javascript i can change image to error.jpg but i want to remove both image as well as its title only of failed image.

Body:
You can replace image if img tag has broken image. Please check below code

<img src='brokenimage.jpg' onError="ImageError(this);">

<script language="JavaScript">
  function ImageError(img)
  {
    img.src = "https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
  }

</script>


问:
how to show error message and terminate in R
```<code>s <- 2
t <- 1
a <- s^2-t^2
b <- 2*s*t
c <- s^2 + t^2

 function(coeff){
        a <- coeff[1]
        b <- coeff[2]
        c <- coeff[3]
        d <- b^2 -(4*a*c)
        cat("The discriminant is:",d,"\n")
        if(d<0) cat("There are no real roots. ","\n")
      if (d>=0){
          root1<-(-b+sqrt(d))/(2*a)
          root2 <-(-b+sqrt(d))/(2*a)
          cat("root1: ",root1,"\n")
          cat("root1: ",root2,"\n")
          }

    }
</code>```

so how do i have to fix it?

when a = 0 i want to show an error message like "invalid number" and then terminate

答:
You can use stop()

```<code>temp <- function(coeff){
    a <- coeff[1]
    b <- coeff[2]
    c <- coeff[3]
    d <- b^2 -(4*a*c)
    if( a < 0) stop("Invalid Number")
    cat("The discriminant is:",d,"\n")
    if(d<0) cat("There are no real roots. ","\n")
    if (d>=0){
        root1<-(-b+sqrt(d))/(2*a)
        root2 <-(-b+sqrt(d))/(2*a)
        cat("root1: ",root1,"\n")
        cat("root1: ",root2,"\n")
    }

}
</code>```

Body:
s <- 2
t <- 1
a <- s^2-t^2
b <- 2*s*t
c <- s^2 + t^2

 function(coeff){
        a <- coeff[1]
        b <- coeff[2]
        c <- coeff[3]
        d <- b^2 -(4*a*c)
        cat("The discriminant is:",d,"\n")
        if(d<0) cat("There are no real roots. ","\n")
      if (d>=0){
          root1<-(-b+sqrt(d))/(2*a)
          root2 <-(-b+sqrt(d))/(2*a)
          cat("root1: ",root1,"\n")
          cat("root1: ",root2,"\n")
          }

    }

so how do i have to fix it?

when a = 0 i want to show an error message like "invalid number" and then terminate

Body:
You can use stop()

temp <- function(coeff){
    a <- coeff[1]
    b <- coeff[2]
    c <- coeff[3]
    d <- b^2 -(4*a*c)
    if( a < 0) stop("Invalid Number")
    cat("The discriminant is:",d,"\n")
    if(d<0) cat("There are no real roots. ","\n")
    if (d>=0){
        root1<-(-b+sqrt(d))/(2*a)
        root2 <-(-b+sqrt(d))/(2*a)
        cat("root1: ",root1,"\n")
        cat("root1: ",root2,"\n")
    }

}


问:
C# - how to add images from folder to array and display them in listview?
```<code>string[] list = Directory.GetFiles(@"Resources/", "*.jpg");
lvDataBinding.Items.Add(list[0]);
</code>```

So the folder Resources contains several images that I want to add to an array so I can use them in an easier way.

I need to display them in a window (each one when a different listviewitem is selected).

I would like to know if I can also store them in a class alongside the ListViewItem name and description. So I can do like:

```<code>Article article1= new Article();
article1.Name = "Article name";
article1.Description = "Long article description etc etc";
article1.Image= images[0];
lvDataBinding.Items.Add(artikel1);
</code>```

And then class would be something like this I guess?

```<code>public class Article
{
    public string Name{ get; set; }
    public string Description{ get; set; }
    public Image? Image { get; set; }

    public override string ToString()
    {
        return Naziv;
    }
}
</code>```

P.S.: I respect all suggestions on how I could do this on another better way. Im sure there are better ways, but I am doing a college assignment and I'm limited on time, also my teacher suggested to "transfer" objects into new windows.
Thanks in advance!

答:
You could store the path of the image using string property. Please refer to the following sample code.

Code:

```<code>public class Article
{
    public string Name { get; set; }
    public string Description { get; set; }
    public string Path { get; set; }
}
...
string[] list = Directory.GetFiles(@"Resources/", "*.png");
List<Article> items = new List<Article>();
foreach (var path in list)
{
    items.Add(new Article()
    {
        Name = System.IO.Path.GetFileNameWithoutExtension(path),
        Path = path
    });
}
lvDataBinding.ItemsSource = items;
</code>```

XAML:

```<code><ListView x:Name="lvDataBinding" DisplayMemberPath="Name" />
<Image Source="{Binding SelectedItem.Path, ElementName=lvDataBinding}" Stretch="None" />
</code>```

Body:
string[] list = Directory.GetFiles(@"Resources/", "*.jpg");
lvDataBinding.Items.Add(list[0]);

So the folder Resources contains several images that I want to add to an array so I can use them in an easier way.

I need to display them in a window (each one when a different listviewitem is selected).

I would like to know if I can also store them in a class alongside the ListViewItem name and description. So I can do like:

Article article1= new Article();
article1.Name = "Article name";
article1.Description = "Long article description etc etc";
article1.Image= images[0];
lvDataBinding.Items.Add(artikel1);

And then class would be something like this I guess?

public class Article
{
    public string Name{ get; set; }
    public string Description{ get; set; }
    public Image? Image { get; set; }

    public override string ToString()
    {
        return Naziv;
    }
}

P.S.: I respect all suggestions on how I could do this on another better way. Im sure there are better ways, but I am doing a college assignment and I'm limited on time, also my teacher suggested to "transfer" objects into new windows.
Thanks in advance!

Body:
You could store the path of the image using string property. Please refer to the following sample code.

Code:

public class Article
{
    public string Name { get; set; }
    public string Description { get; set; }
    public string Path { get; set; }
}
...
string[] list = Directory.GetFiles(@"Resources/", "*.png");
List<Article> items = new List<Article>();
foreach (var path in list)
{
    items.Add(new Article()
    {
        Name = System.IO.Path.GetFileNameWithoutExtension(path),
        Path = path
    });
}
lvDataBinding.ItemsSource = items;

XAML:

<ListView x:Name="lvDataBinding" DisplayMemberPath="Name" />
<Image Source="{Binding SelectedItem.Path, ElementName=lvDataBinding}" Stretch="None" />


问:
ImageButton inside of GridView not clickable
Here is my code for dynamically creating ImageButtons inside of gridviews. When I run the activity, the ImageButtons are not clickable. I tried adding
 android:descendantFocusability="blocksDescendants"
to the xml file but this did not fix the problem.

EDIT: I updated the adapter to be for ImageViews, not ImageButtons, but the problem persists.

Here is my custom adapter:

```<code>    package com.example.myname.myproject;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;

/**
 * Created by myname on 3/31/17.
 */

public class ImageArrayAdapter extends BaseAdapter {
    Context context;
    int[] currentResources;
    String[] currentIcons;

    public ImageArrayAdapter(Context context, String[] currentIcons, int[] currentResources){
        ImageArrayAdapter.this.context = context;
        ImageArrayAdapter.this.currentIcons = currentIcons;
        ImageArrayAdapter.this.currentResources = currentResources;
    }

    @Override
    public int getCount() {
        return currentResources.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(context);
            imageView.setLayoutParams(new GridView.LayoutParams(300, 300));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
            imageView.setBackgroundColor(Color.TRANSPARENT);
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setClickable(true);
        imageView.setImageResource(currentResources[position]);
        return imageView;
    }

}
</code>```

Here is my xml file for the GridView.

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.myname.myproject.AdminControlTabbed$PlaceholderFragment">

<GridView
    android:id="@+id/templateGrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    android:clickable="true"
    android:descendantFocusability="blocksDescendants"
    />
</code>```

Thanks for the help.

答:
Why not ImageViews instead of ImageButtons. Then you have to only set an OnItemClickListener for your GridView in the activity class where you have initialized it. After you attach the adapter to it, you can attach a clickListener too like this:</p>

```<code>myGridView.setAdapter(this, currentIconsArray, currentResourcesArray);
myGridViewsetOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              //code for handling onClick event
        }
    });
</code>```

Body:
Here is my code for dynamically creating ImageButtons inside of gridviews. When I run the activity, the ImageButtons are not clickable. I tried adding
 android:descendantFocusability="blocksDescendants"
to the xml file but this did not fix the problem.

EDIT: I updated the adapter to be for ImageViews, not ImageButtons, but the problem persists.

Here is my custom adapter:

    package com.example.myname.myproject;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;

/**
 * Created by myname on 3/31/17.
 */

public class ImageArrayAdapter extends BaseAdapter {
    Context context;
    int[] currentResources;
    String[] currentIcons;

    public ImageArrayAdapter(Context context, String[] currentIcons, int[] currentResources){
        ImageArrayAdapter.this.context = context;
        ImageArrayAdapter.this.currentIcons = currentIcons;
        ImageArrayAdapter.this.currentResources = currentResources;
    }

    @Override
    public int getCount() {
        return currentResources.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(context);
            imageView.setLayoutParams(new GridView.LayoutParams(300, 300));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
            imageView.setBackgroundColor(Color.TRANSPARENT);
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setClickable(true);
        imageView.setImageResource(currentResources[position]);
        return imageView;
    }

}

Here is my xml file for the GridView.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.myname.myproject.AdminControlTabbed$PlaceholderFragment">

<GridView
    android:id="@+id/templateGrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    android:clickable="true"
    android:descendantFocusability="blocksDescendants"
    />

Thanks for the help.

Body:
Why not ImageViews instead of ImageButtons. Then you have to only set an OnItemClickListener for your GridView in the activity class where you have initialized it. After you attach the adapter to it, you can attach a clickListener too like this:

myGridView.setAdapter(this, currentIconsArray, currentResourcesArray);
myGridViewsetOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              //code for handling onClick event
        }
    });


问:
Windows 7 on a virtual machine
I know this question isn't "directly" programming related, but since I want to be able to be well-prepared on windows-programming when Windows 7 is released, I want to try it out now. But since I don't have two computers, I can't risk to install it as dual-boot in case it screws something up, my experience with dual-booting XP and Vista isn't the best, so dual-boot in a pre-beta-world is even more scary ;)

Anyway, my question is this: Does there exist any Virtualization-programs that handles Windows 7 now? And if there is several, which one is best? I don't really need any detailed descriptions on how to install it and such, that I have google for ;) And the install-DVD is in my hands as we speak, so that isn't a problem either.

答: I installed it using VMWare Fusion on MacBook Pro last night without any problems. I just told VMWare that it was Windows Vista 64Bit.</p>

OwnerDisplayName: Espenhh

Title: Windows 7 on a virtual machine

LastEditorDisplayName: CesarB

OwnerDisplayName: spilth

ContentLicense: CC BY-SA 2.5


问:
How to pass parameters to a method by reflection
Further to my precedent question, I want to pass parameters to the method "WriteTrace". But I don't know how to do this.

Here the actual code :

```<code>public class Trace
{
    public void WriteTrace(object sender, EventArgs e)
    {
        Console.WriteLine("Trace !");
    }
}

public void SubscribeEvent(Control control)
{
    if (typeof(Control).IsAssignableFrom(control.GetType()))
    {
        Trace test = this;
        MethodInfo method = typeof(Trace).GetMethod("WriteTrace");

        EventInfo eventInfo = control.GetType().GetEvent("Load");

        // Create the delegate on the test class because that's where the
        // method is. This corresponds with `new EventHandler(test.WriteTrace)`.
        Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, test, method);
        // Assign the eventhandler. This corresponds with `control.Load += ...`.
        eventInfo.AddEventHandler(control, handler);
    }
}
</code>```

Now I want to get some infos in the trace :

The name of the control

The name of the event

```<code>public void WriteTrace(object sender, EventArgs e)
{
    Console.WriteLine("Control : " + e.ControlName + "Event : " + e.EventName);
}
</code>```

Do I create a class TraceEventArgs which derives from EventArgs with these infos ?
How to pass these infos in the method SubscribeEvent ?

Thanks for your help,

Florian

EDIT

Sorry, here now the reference to "my previous question" : Subscribe to an event with Reflection

答:
Try something like this:</p>

```<code>public void WriteTrace(object sender, EventArgs e, string eventName)
{
    Control c = (Control)sender;
    Console.WriteLine("Control: " + f.Name + ", Event: " + eventName);
}

public void SubscribeEvent(Control control, string eventName) {
    EventInfo eInfo = control.GetType().GetEvent(eventName);

    if (eInfo != null) {
        // create a dummy, using a closure to capture the eventName parameter
        // this is to make use of the C# closure mechanism
        EventHandler dummyDelegate = (s, e) => WriteTrace(s, e, eventName);

        // Delegate.Method returns the MethodInfo for the delegated method
        Delegate realDelegate = Delegate.CreateDelegate(eInfo.EventHandlerType, dummyDelegate.Target, dummyDelegate.Method);

        eInfo.AddEventHandler(control, realDelegate);
    }
}
</code>```

Body:
Further to my precedent question, I want to pass parameters to the method "WriteTrace". But I don't know how to do this.

Here the actual code :

public class Trace
{
    public void WriteTrace(object sender, EventArgs e)
    {
        Console.WriteLine("Trace !");
    }
}

public void SubscribeEvent(Control control)
{
    if (typeof(Control).IsAssignableFrom(control.GetType()))
    {
        Trace test = this;
        MethodInfo method = typeof(Trace).GetMethod("WriteTrace");

        EventInfo eventInfo = control.GetType().GetEvent("Load");

        // Create the delegate on the test class because that's where the
        // method is. This corresponds with `new EventHandler(test.WriteTrace)`.
        Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, test, method);
        // Assign the eventhandler. This corresponds with `control.Load += ...`.
        eventInfo.AddEventHandler(control, handler);
    }
}

Now I want to get some infos in the trace :

The name of the control

The name of the event

public void WriteTrace(object sender, EventArgs e)
{
    Console.WriteLine("Control : " + e.ControlName + "Event : " + e.EventName);
}

Do I create a class TraceEventArgs which derives from EventArgs with these infos ?
How to pass these infos in the method SubscribeEvent ?

Thanks for your help,

Florian

EDIT

Sorry, here now the reference to "my previous question" : Subscribe to an event with Reflection

Body:
Try something like this:

public void WriteTrace(object sender, EventArgs e, string eventName)
{
    Control c = (Control)sender;
    Console.WriteLine("Control: " + f.Name + ", Event: " + eventName);
}

public void SubscribeEvent(Control control, string eventName) {
    EventInfo eInfo = control.GetType().GetEvent(eventName);

    if (eInfo != null) {
        // create a dummy, using a closure to capture the eventName parameter
        // this is to make use of the C# closure mechanism
        EventHandler dummyDelegate = (s, e) => WriteTrace(s, e, eventName);

        // Delegate.Method returns the MethodInfo for the delegated method
        Delegate realDelegate = Delegate.CreateDelegate(eInfo.EventHandlerType, dummyDelegate.Target, dummyDelegate.Method);

        eInfo.AddEventHandler(control, realDelegate);
    }
}


问:
Rearrange lines to tabular format
I would like to grab the part after "-" and combine it with the following letter-string into a tab-output.  I tried something like cut -d "*-" -f 2 <<< "$your_str" but I am not sure how to do the whole shuffling.

Input:

```<code>>1-395652
TATTGCACTTGTCCCGGCCTGT
>2-369990
TATTGCACTCGTCCCGGCCTCC
>3-132234
TATTGCACTCGTCCCGGCCTC
>4-122014
TATTGCACTTGTCCCGGCCTGTAA
>5-118616
</code>```

Output:

```<code>TATTGCACTTGTCCCGGCCTGT 395652
TATTGCACTCGTCCCGGCCTCC 369990
</code>```

答:
With GNU sed:

```<code>sed -nE 'N;s/.*-([0-9]+)\n(.*)/\2\t\1/p' file
</code>```

Output:

```
TATTGCACTTGTCCCGGCCTGT  395652
TATTGCACTCGTCCCGGCCTCC  369990
TATTGCACTCGTCCCGGCCTC   132234
TATTGCACTTGTCCCGGCCTGTAA        122014
```

Title: Rearrange lines to tabular format

Body:
I would like to grab the part after "-" and combine it with the following letter-string into a tab-output.  I tried something like cut -d "*-" -f 2 <<< "$your_str" but I am not sure how to do the whole shuffling.

Input:

>1-395652
TATTGCACTTGTCCCGGCCTGT
>2-369990
TATTGCACTCGTCCCGGCCTCC
>3-132234
TATTGCACTCGTCCCGGCCTC
>4-122014
TATTGCACTTGTCCCGGCCTGTAA
>5-118616

Output:

TATTGCACTTGTCCCGGCCTGT 395652
TATTGCACTCGTCCCGGCCTCC 369990

Body:
With GNU sed:

sed -nE 'N;s/.*-([0-9]+)\n(.*)/\2\t\1/p' file

Output:

TATTGCACTTGTCCCGGCCTGT  395652
TATTGCACTCGTCCCGGCCTCC  369990
TATTGCACTCGTCCCGGCCTC   132234
TATTGCACTTGTCCCGGCCTGTAA        122014


问:
WSGIRequest object has no attribute PUT
I'm trying to make a put request to the local server using the put request using curl:

```<code>curl -X PUT -H "Content-Type: application/json" -d '{"connid":"12"}' "127.0.0.1:8000/api/kill"
</code>```

I receive the same response:

'WSGIRequest' object has no attribute 'PUT'

for the following code:

```<code>def kill(req):
  conid = req.PUT['connid']
  statusres = {}

  if conid in state:
    error[conid] = 'true'
    statusres['status'] = 'ok'

  else:
    statusres['status'] = 'invalid connection Id : '+ conid
  return JsonResponse(statusres)
</code>```

I also used @csrf_exempt before the function.

答:
You have misunderstood several things here.

When you send form-encoded data, whether it's POST or PUT, in Django you always find the parameters in request.POST. So you would find your data in request.POST['conid'].

However, you are not sending form-encoded data; you are sending JSON. You need to access the request body, and pass it to the json.loads function to decode:

```<code>def kill(request):
  data = json.loads(request.body)
  conid = data['connid']
</code>```

Title: WSGIRequest object has no attribute PUT

Body:
I'm trying to make a put request to the local server using the put request using curl:

curl -X PUT -H "Content-Type: application/json" -d '{"connid":"12"}' "127.0.0.1:8000/api/kill"

I receive the same response:

'WSGIRequest' object has no attribute 'PUT'

for the following code:

def kill(req):
  conid = req.PUT['connid']
  statusres = {}

  if conid in state:
    error[conid] = 'true'
    statusres['status'] = 'ok'

  else:
    statusres['status'] = 'invalid connection Id : '+ conid
  return JsonResponse(statusres)

I also used @csrf_exempt before the function.

Body:
You have misunderstood several things here.

When you send form-encoded data, whether it's POST or PUT, in Django you always find the parameters in request.POST. So you would find your data in request.POST['conid'].

However, you are not sending form-encoded data; you are sending JSON. You need to access the request body, and pass it to the json.loads function to decode:

def kill(request):
  data = json.loads(request.body)
  conid = data['connid']


答:
Portable sed:

```<code>sed -n 's/.*-//;x;n;G;s/\n/ /p' inputfile
</code>```

Output:

```<code>TATTGCACTTGTCCCGGCCTGT 395652
TATTGCACTCGTCCCGGCCTCC 369990
TATTGCACTCGTCCCGGCCTC 132234
TATTGCACTTGTCCCGGCCTGTAA 122014
</code>```

Title: Rearrange lines to tabular format

Body:
Portable sed:

sed -n 's/.*-//;x;n;G;s/\n/ /p' inputfile

Output:

TATTGCACTTGTCCCGGCCTGT 395652
TATTGCACTCGTCCCGGCCTCC 369990
TATTGCACTCGTCCCGGCCTC 132234
TATTGCACTTGTCCCGGCCTGTAA 122014


问:
Angular 2 - Click to edit form fields
I want to replace label with input textbox and vice versa by clicking a button in Angular 2. I knowi have to use ngIf of somekind, but i am a little bit confused on how to do.

HTML:

```<code><form>
<div class="information">
  <label *ngIf="editMode">{{textValue}}</label>
  <input *ngIf="editMode" [ngModel]="name">
  <button (click)="editMode=true">Edit</button>
  <button (click)="editMode=false">Save</button>
</div>
</form>
</code>```

答:
The only thing you need to add to one of your *ngIf's, is exclamation mark:

```<code><label *ngIf="!editMode">{{textValue}}</label>
</code>```

which means that label is shown when editMode is false. The exclamation mark is the NOT operator, which is used as truth tests on a variable. More here: What does an exclamation mark before a variable mean in JavaScript

Title: Angular 2 - Click to edit form fields

Body:
I want to replace label with input textbox and vice versa by clicking a button in Angular 2. I knowi have to use ngIf of somekind, but i am a little bit confused on how to do.

HTML:

<form>

  {{textValue}}
  <input *ngIf="editMode" [ngModel]="name">
  <button (click)="editMode=true">Edit</button>
  <button (click)="editMode=false">Save</button>

</form>

Body:
The only thing you need to add to one of your *ngIf's, is exclamation mark:

<label *ngIf="!editMode">{{textValue}}</label>

which means that label is shown when editMode is false. The exclamation mark is the NOT operator, which is used as truth tests on a variable. More here: What does an exclamation mark before a variable mean in JavaScript


问:
Cards in React-Bootstrap
Are Cards added to React-Bootstrap yet?

Or is there any other undocumented way of adding it?

What I am thinking of right now is -> className = 'bootstrap card class syntax', but I guess, it won't work because it won't recognise it.

答:
Bootstrap classes can be used the same way in react like in any non-react project, even without the use of react-bootstrap.  It can be imported as a CDN in your index.html file...

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</code>```

... or it can also be saved locally and imported that way.  Or you can configure webpack to import css files directly into your project.

You'd just have to make sure to use className= instead of class=, but otherwise, it works exactly the same way.

```<code><div className="col-xs-12 well"></div>
</code>```

react-bootstrap is an add-on that provides components that do the same thing.  So, even if it's not in react-bootstrap yet, you can still use the functionality, but just as a straight css class.

Title: Cards in React-Bootstrap

Body:
Bootstrap classes can be used the same way in react like in any non-react project, even without the use of react-bootstrap.  It can be imported as a CDN in your index.html file...

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

... or it can also be saved locally and imported that way.  Or you can configure webpack to import css files directly into your project.

You'd just have to make sure to use className= instead of class=, but otherwise, it works exactly the same way.

<div className="col-xs-12 well"></div>

react-bootstrap is an add-on that provides components that do the same thing.  So, even if it's not in react-bootstrap yet, you can still use the functionality, but just as a straight css class.


问:
How to populate a list looping in another list in Python?
I am making a search page on Django and want to generate a dynamic queryset.

I have a list of string filters initiaized like this:

filter_names = ('filter1', 'filter2')

then, I want to loop in my filter_names list and make a list  of Q objects for each filter that comes in the request (with the same names in filter_names). I am creating the list of Q like this:

```<code>filter_clauses = [Q(filter=request.GET.get(filter))
                      for filter in filter_names
                      if request.GET.get(filter)]
</code>```

the problem is that the resultant list (filter_clauses) is something like:

```<code>Q(filter=value1),
Q(filter=value2)
</code>```

But I actually want a list like:

```<code>Q(filter1=value1),
Q(filter2=value2)
</code>```

In effect, the loop is not catching the value of the variable filter but interpreting it as "filter".

So, am I doing anything wrong in the loop?

For more information, I took the idea from this answer, And I'm getting this error:

Cannot resolve keyword 'filter' into field.

that means, that the framework is searching a field in the searched model with the name 'filter' and obviusly doesn't find it.

答:
You can use keyword argument unpacking:

```<code>filter_clauses = [Q(**{filter: request.GET.get(filter)})
                      for filter in filter_names
                      if request.GET.get(filter)]
</code>```

Here the value of filter is the key in the dictionary, so when you unpack the arguments, the parameter name will be filter1 etc.

Body:
I am making a search page on Django and want to generate a dynamic queryset.

I have a list of string filters initiaized like this:

filter_names = ('filter1', 'filter2')

then, I want to loop in my filter_names list and make a list  of Q objects for each filter that comes in the request (with the same names in filter_names). I am creating the list of Q like this:

filter_clauses = [Q(filter=request.GET.get(filter))
                      for filter in filter_names
                      if request.GET.get(filter)]

the problem is that the resultant list (filter_clauses) is something like:

Q(filter=value1),
Q(filter=value2)

But I actually want a list like:

Q(filter1=value1),
Q(filter2=value2)

In effect, the loop is not catching the value of the variable filter but interpreting it as "filter".

So, am I doing anything wrong in the loop?

For more information, I took the idea from this answer, And I'm getting this error:

Cannot resolve keyword 'filter' into field.

that means, that the framework is searching a field in the searched model with the name 'filter' and obviusly doesn't find it.

Body:
You can use keyword argument unpacking:

filter_clauses = [Q(**{filter: request.GET.get(filter)})
                      for filter in filter_names
                      if request.GET.get(filter)]

Here the value of filter is the key in the dictionary, so when you unpack the arguments, the parameter name will be filter1 etc.


问:
How to reformat a text file - awk
I have a text file containing 3 columns:

broke   banana    192

  broke   apple    175

  broke   avocado   20

  fixed   banana    117

  fixed   apple    89

I need the output below:

Issue,banana,apple,avocado

    broke,192,175,20

    fixed,117,90,0

I am new to this and have no idea how to get this result.

I appreciate any help,
Thanks

答:
Input

```<code>$ cat file
broke banana 192
broke apple 175
fixed banana 117
fixed apple 89
</code>```

I don't understand where from you got fixed,117,90 in expected o/p

Output

```<code>$ awk -v OFS=, '{
      is_fr[$1,$2]=$3

      if(!($1 in i_tmp))issue[++i]=$1;
      if(!($2 in f_tmp))fruit[++f]=$2;

      i_tmp[$1]; f_tmp[$2]
   }
END{
      printf ("%s","issue");
      for(i=1; i in fruit; i++)
           printf("%s%s",OFS,fruit[i]);
      print "";
      for(i=1; i in issue; i++)
      {
          printf("%s",issue[i]);
          for(j=1; j  in fruit; j++)
          {
               printf("%s%s",OFS,(issue[i],fruit[j]) in is_fr ? is_fr[issue[i],fruit[j]]:"")
          }
          print ""
      }
    }' file

issue,banana,apple
broke,192,175
fixed,117,89
</code>```

If order doesn't matter then you may try below awk

```<code>$ awk -v OFS=, '{
      issue[$1];
      fruit[$2];
      is_fr[$1,$2]=$3
   }
END{
      printf ("%s","issue");
      for(i in fruit)
           printf("%s%s",OFS,i);
      print "";
      for(i in issue)
      {
          printf("%s",i);
          for(j in fruit)
          {
               printf("%s%s",OFS,(i,j) in is_fr ? is_fr[i,j]:"")
          }
          print ""
      }
   }' file
issue,apple,banana
fixed,89,117
broke,175,192
</code>```

For new input edited by OP

```<code>akshay@db-3325:/tmp$ cat f
broke banana 192
broke apple 175
broke avocado 20
fixed banana 117
fixed apple 89

akshay@db-3325:/tmp$ awk -v OFS=, '{
      is_fr[$1,$2]=$3

      if(!($1 in i_tmp))issue[++i]=$1;
      if(!($2 in f_tmp))fruit[++f]=$2;

      i_tmp[$1]; f_tmp[$2]
   }
END{
      printf ("%s","issue");
      for(i=1; i in fruit; i++)
           printf("%s%s",OFS,fruit[i]);
      print "";
      for(i=1; i in issue; i++)
      {
          printf("%s",issue[i]);
          for(j=1; j  in fruit; j++)
          {
               printf("%s%s",OFS,(issue[i],fruit[j]) in is_fr ? is_fr[issue[i],fruit[j]]+0:0)
          }
          print ""
      }
    }' f
issue,banana,apple,avocado
broke,192,175,20
fixed,117,89,0
</code>```

Title: How to reformat a text file - awk

Body:
Input

$ cat file
broke banana 192
broke apple 175
fixed banana 117
fixed apple 89

I don't understand where from you got fixed,117,90 in expected o/p

Output

$ awk -v OFS=, '{
      is_fr[$1,$2]=$3

      if(!($1 in i_tmp))issue[++i]=$1;
      if(!($2 in f_tmp))fruit[++f]=$2;

      i_tmp[$1]; f_tmp[$2]
   }
END{
      printf ("%s","issue");
      for(i=1; i in fruit; i++)
           printf("%s%s",OFS,fruit[i]);
      print "";
      for(i=1; i in issue; i++)
      {
          printf("%s",issue[i]);
          for(j=1; j  in fruit; j++)
          {
               printf("%s%s",OFS,(issue[i],fruit[j]) in is_fr ? is_fr[issue[i],fruit[j]]:"")
          }
          print ""
      }
    }' file

issue,banana,apple
broke,192,175
fixed,117,89

If order doesn't matter then you may try below awk

$ awk -v OFS=, '{
      issue[$1];
      fruit[$2];
      is_fr[$1,$2]=$3
   }
END{
      printf ("%s","issue");
      for(i in fruit)
           printf("%s%s",OFS,i);
      print "";
      for(i in issue)
      {
          printf("%s",i);
          for(j in fruit)
          {
               printf("%s%s",OFS,(i,j) in is_fr ? is_fr[i,j]:"")
          }
          print ""
      }
   }' file
issue,apple,banana
fixed,89,117
broke,175,192

For new input edited by OP

akshay@db-3325:/tmp$ cat f
broke banana 192
broke apple 175
broke avocado 20
fixed banana 117
fixed apple 89

akshay@db-3325:/tmp$ awk -v OFS=, '{
      is_fr[$1,$2]=$3

      if(!($1 in i_tmp))issue[++i]=$1;
      if(!($2 in f_tmp))fruit[++f]=$2;

      i_tmp[$1]; f_tmp[$2]
   }
END{
      printf ("%s","issue");
      for(i=1; i in fruit; i++)
           printf("%s%s",OFS,fruit[i]);
      print "";
      for(i=1; i in issue; i++)
      {
          printf("%s",issue[i]);
          for(j=1; j  in fruit; j++)
          {
               printf("%s%s",OFS,(issue[i],fruit[j]) in is_fr ? is_fr[issue[i],fruit[j]]+0:0)
          }
          print ""
      }
    }' f
issue,banana,apple,avocado
broke,192,175,20
fixed,117,89,0


问:
Using structs in oneOf field in Protocol Buffers v3 via Go
So trying to using Protocol Buffers v3 and Go together (new to both).

example.proto

```<code>syntax = "proto3";

package test;

import "google/protobuf/timestamp.proto";

message Metadata {
    uint64 userID = 2;
    google.protobuf.Timestamp time= 3;
}

//SignOff when user logs out of Glory
message SignOff {
    Metadata metadata =1;
}

//SignOn when user logs into Glory
message SignOn {
    Metadata metadata =1;
}

message EventWrapper {
    oneof event {
        SignOff signOff = 1;
        SignOn signOn = 2;
    }
}
</code>```

Converting with protoc and using in Go

```<code>now, _ := ptypes.TimestampProto(time.Now())
event := &pb_test.EventWrapper{
    Event: &pb_test.EventWrapper_SignOn{
        SignOn: &pb_test.SignOn{
            Metadata: &pb_test.Metadata{
                UserID: 1234,
                Time:   now,
            },
        },
    },
}
protoBytes, err := proto.Marshal(event)
if err != nil {
    log.Fatal(err)
}
log.Println(len(protoBytes) == 0)

jsonBytes, _ = json.MarshalIndent(event, "", "\t")
log.Println(string(jsonBytes))
</code>```

The output shows the JSON is right but the protobuf encoded byte array is empty.

```<code>{
    "Event": {
        "SignOn": {
            "metadata": {
                "userID": 1234,
                "time": {
                    "seconds": 1491143507,
                    "nanos": 654053400
                }
            }
        }
    }
}
</code>```

The intent is the have a array of these (repeated *EventWrapper) to send along the wire via gRPC, but the individual ones don't work at the moment.  The protobuf Language Guide doesn't say anything about structs not being allowed.  Is there something I'm missing?

答:
Nothing in the Protocol Buffer documentation indicates oneof cannot be structs, and in fact the example generates structs for a union field.

I recommend using gogo, which I have personally used for previous commercial projects. Specifically, use protoc-gen-gogoslick

See this section for installing the necessary packages, then run the following for your project

```<code>protoc --gogoslick_out=Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types:. example.proto
</code>```

Body:
So trying to using Protocol Buffers v3 and Go together (new to both).

example.proto

syntax = "proto3";

package test;

import "google/protobuf/timestamp.proto";

message Metadata {
    uint64 userID = 2;
    google.protobuf.Timestamp time= 3;
}

//SignOff when user logs out of Glory
message SignOff {
    Metadata metadata =1;
}

//SignOn when user logs into Glory
message SignOn {
    Metadata metadata =1;
}

message EventWrapper {
    oneof event {
        SignOff signOff = 1;
        SignOn signOn = 2;
    }
}

Converting with protoc and using in Go

now, _ := ptypes.TimestampProto(time.Now())
event := &pb_test.EventWrapper{
    Event: &pb_test.EventWrapper_SignOn{
        SignOn: &pb_test.SignOn{
            Metadata: &pb_test.Metadata{
                UserID: 1234,
                Time:   now,
            },
        },
    },
}
protoBytes, err := proto.Marshal(event)
if err != nil {
    log.Fatal(err)
}
log.Println(len(protoBytes) == 0)

jsonBytes, _ = json.MarshalIndent(event, "", "\t")
log.Println(string(jsonBytes))

The output shows the JSON is right but the protobuf encoded byte array is empty.

{
    "Event": {
        "SignOn": {
            "metadata": {
                "userID": 1234,
                "time": {
                    "seconds": 1491143507,
                    "nanos": 654053400
                }
            }
        }
    }
}

The intent is the have a array of these (repeated *EventWrapper) to send along the wire via gRPC, but the individual ones don't work at the moment.  The protobuf Language Guide doesn't say anything about structs not being allowed.  Is there something I'm missing?

Body:
Nothing in the Protocol Buffer documentation indicates oneof cannot be structs, and in fact the example generates structs for a union field.

I recommend using gogo, which I have personally used for previous commercial projects. Specifically, use protoc-gen-gogoslick

See this section for installing the necessary packages, then run the following for your project

protoc --gogoslick_out=Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types:. example.proto


问:
Generating N numbers that sum to 1
Given an array of size n I want to generate random probabilities for each index such that Sigma(a[0]..a[n-1])=1

One possible result might be:

```<code>0     1     2     3     4
0.15  0.2   0.18  0.22  0.25
</code>```

Another perfectly legal result can be:

```<code>0     1     2     3     4
0.01  0.01  0.96  0.01  0.01
</code>```

How can I generate these easily and quickly? Answers in any language are fine, Java preferred.

答:
Get n random numbers, calculate their sum and normalize the sum to 1
  by dividing each number with the sum.

Expanding on Kobi's answer, here's a Java function that does exactly that.

```<code>public static double[] getRandDistArray(int n)  {
    double randArray[] = new double[n];
    double sum = 0;

    // Generate n random numbers
    for (int i = 0; i < randArray.length; i++) {
        randArray[i] = Math.random();
        sum += randArray[i];
    }

    // Normalize sum to 1
    for (int i = 0; i < randArray.length; i++) {
        randArray[i] /= sum;
    }
    return randArray;
}
</code>```

In a test run, getRandDistArray(5) returned the following

```<code>[0.1796505603694718, 0.31518724882558813, 0.15226147256596428, 0.30954417535503603, 0.043356542883939767]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Generating N numbers that sum to 1

Body:
Given an array of size n I want to generate random probabilities for each index such that Sigma(a[0]..a[n-1])=1

One possible result might be:

0     1     2     3     4
0.15  0.2   0.18  0.22  0.25

Another perfectly legal result can be:

0     1     2     3     4
0.01  0.01  0.96  0.01  0.01

How can I generate these easily and quickly? Answers in any language are fine, Java preferred.

Body:
Get n random numbers, calculate their sum and normalize the sum to 1
  by dividing each number with the sum.

Expanding on Kobi's answer, here's a Java function that does exactly that.

public static double[] getRandDistArray(int n)  {
    double randArray[] = new double[n];
    double sum = 0;

    // Generate n random numbers
    for (int i = 0; i < randArray.length; i++) {
        randArray[i] = Math.random();
        sum += randArray[i];
    }

    // Normalize sum to 1
    for (int i = 0; i < randArray.length; i++) {
        randArray[i] /= sum;
    }
    return randArray;
}

In a test run, getRandDistArray(5) returned the following

[0.1796505603694718, 0.31518724882558813, 0.15226147256596428, 0.30954417535503603, 0.043356542883939767]


问:
Javascript: How to get/select all object with same keys?
I have object like this:

```<code>[
  {
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  },
  {
    "id": 3,
    "name": "App 3",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app3",
    "kat": "tei"
  },
  {
    "id": 4,
    "name": "App 4",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app4",
    "kat": "tei"
  },
  {
    "id": 5,
    "name": "App 5",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app5",
    "kat": "tei"
  }
]
</code>```

How i get/select all object with same keys (kat) in javascript?

example i want to get all object with kat=tkj will return:

```<code>[{
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  }]
</code>```

Thanks for your help ^_^

答:
Here is working example, I prepared two working functions, one in pure javascript, second in ES6.

// PureJS
function findObjectsByKeyValue(object, key, value) {
  var result = [];

  for (i = 0; i < object.length; i++) {
    var element = object[i];

    if (element[key] === value) {
      result.push(element);
    }
  }

  return result;
}

// ES6
function findObjectsByKeyValueES6(object, key, value) {
  return object.filter(element => {
    return element[key] === value
  });
}

var obj = [
  {
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  },
  {
    "id": 3,
    "name": "App 3",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app3",
    "kat": "tei"
  },
  {
    "id": 4,
    "name": "App 4",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app4",
    "kat": "tei"
  },
  {
    "id": 5,
    "name": "App 5",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app5",
    "kat": "tei"
  }
];

// Pure JS
var result = findObjectsByKeyValue(obj, 'kat', 'tkj');
// ES6 filter
//var result = findObjectsByKeyValueES6(obj, 'kat', 'tkj');
console.log(result);```

Body:
I have object like this:

[
  {
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  },
  {
    "id": 3,
    "name": "App 3",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app3",
    "kat": "tei"
  },
  {
    "id": 4,
    "name": "App 4",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app4",
    "kat": "tei"
  },
  {
    "id": 5,
    "name": "App 5",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app5",
    "kat": "tei"
  }
]

How i get/select all object with same keys (kat) in javascript?

example i want to get all object with kat=tkj will return:

[{
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  }]

Thanks for your help ^_^


问:
OpenCV (android) convert a unknown type image to CV_8UC3
First, I have no idea what is the type of user input images.
But I want to convert all of them to type CV_8UC3.

I use this function :

```<code>Imgproc.cvtColor(img,img,CvType.CV_8UC3);
</code>```

But it doesn't work.

And I try this :

```<code>Imgproc.cvtColor(img_edge,img_edge,Imgproc.COLOR_GRAY2RGB);
</code>```

This is from gray to RGB, but actually I have no idea what is the type of the input image, I just want to convert all of them to CV_8UC3.

Is that possible ?

答:
You simply need to write an if-else clause, there are not too many cases, only 2 formats other than RGB exist, One bring Gray and the other being RGBA. So you may go like:

```<code>if (img.channels() == 1) {
    Imgproc.cvtColor(img_edge,img_edge,Imgproc.COLOR_GRAY2BGR);
} else if (img.channels() == 4) {
    Imgproc.cvtColor(img_edge,img_edge,Imgproc.COLOR_BGRA2BGR);
}
</code>```

Body:
First, I have no idea what is the type of user input images.
But I want to convert all of them to type CV_8UC3.

I use this function :

Imgproc.cvtColor(img,img,CvType.CV_8UC3);

But it doesn't work.

And I try this :

Imgproc.cvtColor(img_edge,img_edge,Imgproc.COLOR_GRAY2RGB);

This is from gray to RGB, but actually I have no idea what is the type of the input image, I just want to convert all of them to CV_8UC3.

Is that possible ?

Body:
You simply need to write an if-else clause, there are not too many cases, only 2 formats other than RGB exist, One bring Gray and the other being RGBA. So you may go like:

if (img.channels() == 1) {
    Imgproc.cvtColor(img_edge,img_edge,Imgproc.COLOR_GRAY2BGR);
} else if (img.channels() == 4) {
    Imgproc.cvtColor(img_edge,img_edge,Imgproc.COLOR_BGRA2BGR);
}