问:
hook.params.user does not exist after successful feathers js authentication
If you look at the official feathers-authentication plugin's default options, it says there should be a user object available in hook.params.user (under entity option)

https://github.com/feathersjs/feathers-authentication

```<code>{
  path: '/authentication', // the authentication service path
  header: 'Authorization', // the header to use when using JWT auth
  **entity: 'user', // the entity that will be added to the request, socket, and hook.params. (ie. req.user, socket.user, hook.params.user)**
  service: 'users', // the service to look up the entity
  passReqToCallback: true, // whether the request object should be passed to the strategies `verify` function
  session: false, // whether to use sessions
  cookie: {
    enabled: false, // whether the cookie should be enabled
    name: 'feathers-jwt', // the cookie name
    httpOnly: false, // whether the cookie should not be available to client side JavaScript
    secure: true // whether cookies should only be available over HTTPS
  },
  jwt: {
    header: { typ: 'access' }, // by default is an access token but can be any type
    audience: 'https://yourdomain.com', // The resource server where the token is processed
    subject: 'anonymous', // Typically the entity id associated with the JWT
    issuer: 'feathers', // The issuing server, application or resource
    algorithm: 'HS256', // the algorithm to use
    expiresIn: '1d' // the access token expiry
  }
}
</code>```

I have a successful authentication and I have a jwt token stored in window.localStorage. I just have no idea how to add to get the hook.params.user object to appear. Do I need to set something up in server side? My current authentication flow is just the example set by the docs.

My current suspicion is that this is legacy information, since the new docs do not mention hook.params.user object being available, and I think it just uses hooks to insert the user id instead.

https://docs.feathersjs.com/api/authentication/client.html

If this is the case, is there a way just to get the user id of the current logged in user without using a hook to add it in?

Thanks

答: It is still being added but you have to either authenticate the socket connection or the HTTP request with the token from the storage. This is usually done by calling client.reAuthenticate() (with no parameters) on the client before making any other service calls. To see it in action, have a look at the JS chat frontend.

Body:
If you look at the official feathers-authentication plugin's default options, it says there should be a user object available in hook.params.user (under entity option)

https://github.com/feathersjs/feathers-authentication

{
  path: '/authentication', // the authentication service path
  header: 'Authorization', // the header to use when using JWT auth
  **entity: 'user', // the entity that will be added to the request, socket, and hook.params. (ie. req.user, socket.user, hook.params.user)**
  service: 'users', // the service to look up the entity
  passReqToCallback: true, // whether the request object should be passed to the strategies `verify` function
  session: false, // whether to use sessions
  cookie: {
    enabled: false, // whether the cookie should be enabled
    name: 'feathers-jwt', // the cookie name
    httpOnly: false, // whether the cookie should not be available to client side JavaScript
    secure: true // whether cookies should only be available over HTTPS
  },
  jwt: {
    header: { typ: 'access' }, // by default is an access token but can be any type
    audience: 'https://yourdomain.com', // The resource server where the token is processed
    subject: 'anonymous', // Typically the entity id associated with the JWT
    issuer: 'feathers', // The issuing server, application or resource
    algorithm: 'HS256', // the algorithm to use
    expiresIn: '1d' // the access token expiry
  }
}

I have a successful authentication and I have a jwt token stored in window.localStorage. I just have no idea how to add to get the hook.params.user object to appear. Do I need to set something up in server side? My current authentication flow is just the example set by the docs.

My current suspicion is that this is legacy information, since the new docs do not mention hook.params.user object being available, and I think it just uses hooks to insert the user id instead.

https://docs.feathersjs.com/api/authentication/client.html

If this is the case, is there a way just to get the user id of the current logged in user without using a hook to add it in?

Thanks


来源: stackexchange

问:
JSON Deserialize to generic type
I am writing tests for my controllers (ASP.NET Core), and am receiving back some JSON.  I would now like to deserialize it into the correct object so that I can do some assertions against the returned data.  There are no exceptions thrown during deserialization, but my Data variable is null.

Here is the code used for the deserialization:

```<code>var output = JsonConvert.DeserializeObject(responseString,
                typeof(CrudOperationResult<IEnumerable<ApiResource>>));
</code>```

This is the CrudOperationResult class:

```<code>public class CrudOperationResult<T>
{
    private CrudOperationResult()
    { }

    private CrudOperationResult(CrudResult result, string errorMessage, T data)
    {
        Result = result;
        ErrorMessage = errorMessage;
        Data = data;
    }

    [JsonIgnore]
    public CrudResult Result { get; private set; }

    public bool IsError
    {
        get
        {
            return Result == CrudResult.Error;
        }
    }

    public string ErrorMessage { get; private set; }

    public T Data { get; private set; }
}
</code>```

And here is the JSON data returned:

```<code>{
    "isError": false,
    "errorMessage": null,
    "data": [{
        "id": 1,
        "enabled": true,
        "name": "apiResource1",
        "displayName": "My API",
        "description": null,
        "secrets": null,
        "scopes": [{
            "id": 1,
            "name": "apiResource1",
            "displayName": "My API",
            "description": null,
            "required": false,
            "emphasize": false,
            "showInDiscoveryDocument": true,
            "userClaims": null
        }],
        "userClaims": [{
            "id": 1,
            "type": "role"
        },
        {
            "id": 2,
            "type": "user"
        }]
    }]
}
</code>```

答:
use this function :</p>

```<code>List<T> ToJson<T>(byte[] byteArray) where T : new()
{

MemoryStream stream = new MemoryStream(byteArray);

JsonSerializer se = new JsonSerializer();

StreamReader re = new StreamReader(stream);
JsonTextReader reader = new JsonTextReader(re);
    return se.Deserialize<List<T>>(reader);
 }
</code>```

ContentLicense: CC BY-SA 3.0

Title: JSON Deserialize to generic type

Body:
I am writing tests for my controllers (ASP.NET Core), and am receiving back some JSON.  I would now like to deserialize it into the correct object so that I can do some assertions against the returned data.  There are no exceptions thrown during deserialization, but my Data variable is null.

Here is the code used for the deserialization:

var output = JsonConvert.DeserializeObject(responseString,
                typeof(CrudOperationResult<IEnumerable<ApiResource>>));

This is the CrudOperationResult class:

public class CrudOperationResult<T>
{
    private CrudOperationResult()
    { }

    private CrudOperationResult(CrudResult result, string errorMessage, T data)
    {
        Result = result;
        ErrorMessage = errorMessage;
        Data = data;
    }

    [JsonIgnore]
    public CrudResult Result { get; private set; }

    public bool IsError
    {
        get
        {
            return Result == CrudResult.Error;
        }
    }

    public string ErrorMessage { get; private set; }

    public T Data { get; private set; }
}

And here is the JSON data returned:

{
    "isError": false,
    "errorMessage": null,
    "data": [{
        "id": 1,
        "enabled": true,
        "name": "apiResource1",
        "displayName": "My API",
        "description": null,
        "secrets": null,
        "scopes": [{
            "id": 1,
            "name": "apiResource1",
            "displayName": "My API",
            "description": null,
            "required": false,
            "emphasize": false,
            "showInDiscoveryDocument": true,
            "userClaims": null
        }],
        "userClaims": [{
            "id": 1,
            "type": "role"
        },
        {
            "id": 2,
            "type": "user"
        }]
    }]
}

Body:
use this function :

List<T> ToJson<T>(byte[] byteArray) where T : new()
{

MemoryStream stream = new MemoryStream(byteArray);

JsonSerializer se = new JsonSerializer();

StreamReader re = new StreamReader(stream);
JsonTextReader reader = new JsonTextReader(re);
    return se.Deserialize<List<T>>(reader);
 }


问:
Can I revert a range of lines in a file with mercurial?
I often notice a few unwanted changes when I review my working copy (with hg status and hg diff) right before a commit. For example, I might have temporarily added or remove some code just for the duration of a debugging session.

I know I can use hg revert to remove unwanted changes, but this removes all the changes in the entire file. Is there a way to revert just a part of a file?

答:
One way is using a graphical diff tool like kdiff3.  If you feed it the diff and choose "merge current file" you can go line by line and pick what you want.

The better way is to commit more often.  If you make a habit to commit right before adding debugging code, then either commit or revert your debug code before adding your "real" code, it makes it very easy to remove your debug code because it has its own revision.  Alternately, you can put your debugging code in a separate branch altogether.

ContentLicense: CC BY-SA 2.5


问:
How can I make my android emulator faster?
I'm using the Andyroid emulator and it seems whenever I try to play an app/game then it becomes incredibly slow and laggy to the point that I can't even play said game. Are there any settings I can tweak to make it faster?

I have around 4 GB of RAM and my processor is AMD Athlon 64 X2 Dual Core 4800+ 2.50 GHz.

答: Firstly update to the latest Android Studio. Emulators start work faster and faster with new Android Studio versions. Also make sure you select x86 image, during emulator setup. Arm emulators are very slow.</p>


问:
Excel Extraction, taking out three numeric characters in a string
I am looking to find an excel formula or VB formula which would be able to extract specific data in excel.

For example we have the following in a cell:
Time spent in script:333

The above will always remain the same, however the time will be different and can range from 1 to 999 so 3 numeric characters max. However.. In some cells there maybe changes after the 3 characters and may come out like so:
Time spent in script:333Q1

So I need a formula which extracts 3 numeric characters after the semi colon but to ignore anything after the 3 characters.

答:
Quite lengthy, but should help you,

```<code>=IF(ISNUMBER(VALUE(LEFT(MID(A1,FIND(":",A1)+1,99),3))),VALUE(LEFT(MID(A1,FIND(":",A1)+1,99),3)),IF(ISNUMBER(VALUE(LEFT(MID(A1,FIND(":",A1)+1,99),2))),VALUE(LEFT(MID(A1,FIND(":",A1)+1,99),2)),VALUE(LEFT(MID(A1,FIND(":",A1)+1,99),1))))
</code>```

Body:
Quite lengthy, but should help you,

=IF(ISNUMBER(VALUE(LEFT(MID(A1,FIND(":",A1)+1,99),3))),VALUE(LEFT(MID(A1,FIND(":",A1)+1,99),3)),IF(ISNUMBER(VALUE(LEFT(MID(A1,FIND(":",A1)+1,99),2))),VALUE(LEFT(MID(A1,FIND(":",A1)+1,99),2)),VALUE(LEFT(MID(A1,FIND(":",A1)+1,99),1))))


问:
Intellij maven imports have broken classpath
I'm using Intellij 13, I've been using Maven quite happily for awhile now to manage the JAR dependencies.

But the last few I've imported are causing a broken classpath issue, and they're not being installed to the repository.

I though it might be just the JSONPath library, but when I tried to install Selenium drivers it also happened with those libs. I checked the local repository and the directories exist, but the JARs haven't downloaded.

This only started happening recently, and a lot of other dependencies have been installed fine (but not since this issue started happening). I'm really not sure what might have caused it.

Does anyone know how to troubleshoot this? Or why the JARs aren't installing? And can I just trigger an update somehow from Intellij to try to reinstall them?

Quick Edit Here:

I tried installing the modules using Intellij's "add library" feature. It installed them fine, whereas before I was just updating them directly in the pom.xml and it was downloading them.

The library feature seems a little better because it automatically adds them to my output artefacts anyway, but it would be nice if it also updated the pom so I can use it outside of the intellij environment.

So I'm not sure why updating the pom.xml isn't working any more...

答:
I've had this issue in IntelliJ IDEA 2017 Ultimate.

After changing dependency versions, the IDE was unable to fix the path on its own. I went to my ~/.m2 directory and deleted all of the dependencies for the problem jar and then executed the "ReImport All Maven Projects" action. When it was complete, the dependency issue was resolved.


问:
Sqlalchemy error handling and custom validations
I've read several questions about this and I don't know yet what's the best solution for this problem. Suppose we have a Model like this:

```<code>from sqlalchemy import Column, Integer, String

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    email = Column(String, unique=True)
    fullname = Column(String)
    password = Column(String, nullable=False)
</code>```

In my controller, I want to create a user, while validating parameters and handling sqlalchemy errors to reply to this request.

validation checks:

email uniqeness

password can't be null

password must be at least 6 characters.

for validation number 3, we can use validates decoraor.
for first 2 validation, we can add and commit this user and somehow parse sqlalchemy.exc.SQLAlchemyError error which is raised.

But I really don't like this way. because it's so dirty and not scalable. some validtions like uniqeness needs to query to db. but checking if a value is null, doesn't need to query to db and parse sqlAlchemyError.

What's the best way to handle various types of validation?

What's the best way to parse sqlAlchemyError messages and return proper HTTP status codes to clients?

答:
Depending on what you are planning to do with your application you could use the excellent validation capabilities of wtforms:

```<code>from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField
from wtforms.fields.html5 import EmailField
from wtforms.validators import Length, Required, Email, EqualTo

class FooForm(Form):
    email = EmailField('Email', validators=[Required(),Email()])
    fullname = StringField('Name', validators=[Required(), Length(64)])
    password = PasswordField('Password', validators=[Required(), EqualTo('password2', message='Passwords must match.'), Length(8)])
    password2 = PasswordField('Password (confirm)', validators=[Required(),Length(8)])
    submit = SubmitField('Submit')
</code>```

That takes care of your userinput validation - if something doesn't fit the requirements it will catch the errors before any sort of request to the backand is made. For the email uniquenes, i would suggest wrapping the sqla transaction in "try:...except:" to catch the error and flash a respective message to the user.
Or you could write your own wtforms validator as described here.
You could, for example, shoot an ajax request to the backend and check whether the emailaddress in question is already taken.

Body:
I've read several questions about this and I don't know yet what's the best solution for this problem. Suppose we have a Model like this:

from sqlalchemy import Column, Integer, String

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    email = Column(String, unique=True)
    fullname = Column(String)
    password = Column(String, nullable=False)

In my controller, I want to create a user, while validating parameters and handling sqlalchemy errors to reply to this request.

validation checks:

email uniqeness

password can't be null

password must be at least 6 characters.

for validation number 3, we can use validates decoraor.
for first 2 validation, we can add and commit this user and somehow parse sqlalchemy.exc.SQLAlchemyError error which is raised.

But I really don't like this way. because it's so dirty and not scalable. some validtions like uniqeness needs to query to db. but checking if a value is null, doesn't need to query to db and parse sqlAlchemyError.

What's the best way to handle various types of validation?

What's the best way to parse sqlAlchemyError messages and return proper HTTP status codes to clients?

Body:
Depending on what you are planning to do with your application you could use the excellent validation capabilities of wtforms:

from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField
from wtforms.fields.html5 import EmailField
from wtforms.validators import Length, Required, Email, EqualTo

class FooForm(Form):
    email = EmailField('Email', validators=[Required(),Email()])
    fullname = StringField('Name', validators=[Required(), Length(64)])
    password = PasswordField('Password', validators=[Required(), EqualTo('password2', message='Passwords must match.'), Length(8)])
    password2 = PasswordField('Password (confirm)', validators=[Required(),Length(8)])
    submit = SubmitField('Submit')

That takes care of your userinput validation - if something doesn't fit the requirements it will catch the errors before any sort of request to the backand is made. For the email uniquenes, i would suggest wrapping the sqla transaction in "try:...except:" to catch the error and flash a respective message to the user.
Or you could write your own wtforms validator as described here.
You could, for example, shoot an ajax request to the backend and check whether the emailaddress in question is already taken.


问:
How to get random value from specific ranges of dictionary content
If this way I can get random value from given range:

```<code> int r = ran.Next(1, 4);
 string v;
 if (dict.TryGetValue(r, out v))
 {
    ///...
 }
</code>```

how to properly get random value of <int, string> dictionary content from specific range, for example only from 4 to 6 and 1 and 2 and avoid look for 3:

```<code>Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "word1" },
    { 2, "word2" },
    { 3, "word3" },
    { 4, "word4" },
    { 5, "word5" },
    { 6, "word6" }
};
</code>```

答:
In general there are a couple of functions available in LINQ namely IEnumerable.Skip and IEnumerable.Take

These functions can be used to get a slice of any IEnumerable. Remember that Dictionary<TKey, TValue> is also an IEnumerable<KeyValuePair<TKey, TValue>>

So to access a random element between the 4th and 10th element.

```<code>var rand = new Random();
dict.Skip(3).Take(6 /* 10 - 4 */).ElementAt(rand.Next(6 /* 10 - 4 */)
</code>```

Now do remember that the sequence is not necessarily sorted or sequenced by the key or in any predictable way. You might have to use OrderBy to traverse the dictionary in the sequence of your choice.

If you want to do these things numerous times between the dictionary getting updated, then you can simply access dict.Keys.OrderBy().ToList() and then access this List using the same Skip().Take().ElementAt() or directly with index manipulations. This will avoid re-enumerating the same dictionary multiple times

Body:
If this way I can get random value from given range:

 int r = ran.Next(1, 4);
 string v;
 if (dict.TryGetValue(r, out v))
 {
    ///...
 }

how to properly get random value of <int, string> dictionary content from specific range, for example only from 4 to 6 and 1 and 2 and avoid look for 3:

Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "word1" },
    { 2, "word2" },
    { 3, "word3" },
    { 4, "word4" },
    { 5, "word5" },
    { 6, "word6" }
};

Body:
In general there are a couple of functions available in LINQ namely IEnumerable.Skip and IEnumerable.Take

These functions can be used to get a slice of any IEnumerable. Remember that Dictionary<TKey, TValue> is also an IEnumerable<KeyValuePair<TKey, TValue>>

So to access a random element between the 4th and 10th element.

var rand = new Random();
dict.Skip(3).Take(6 /* 10 - 4 */).ElementAt(rand.Next(6 /* 10 - 4 */)

Now do remember that the sequence is not necessarily sorted or sequenced by the key or in any predictable way. You might have to use OrderBy to traverse the dictionary in the sequence of your choice.

If you want to do these things numerous times between the dictionary getting updated, then you can simply access dict.Keys.OrderBy().ToList() and then access this List using the same Skip().Take().ElementAt() or directly with index manipulations. This will avoid re-enumerating the same dictionary multiple times


问:
How is docker useful for non webapp applications (e.g. Python scripts)? What is the advantage of using it over LXC/LXD?
I am trying to understand how docker is useful outside of the webapp space.

If for example someone wants to run a python script which downloads global weather data every 12 hours, why would they use docker?

What is the advantage of using docker to Linux LXC/LXD containers?

I am struggling to understand the benefits of using Docker.

答:
If for example someone wants to run a python script which downloads global weather data every 12 hours, why would they use docker?

I wouldn't, in this case. set up a cron job to run the script.

What is the advantage of using docker to Linux LXC/LXD containers?

Docker was originally built on top of LXC containers. Since then, it has moved to a newer standard, libcontainer.

The major benefit here, is cross-platform compatibility with a much larger ecosystem.

The world of linux containers with lxc probably still has a place, but Docker is quickly bringing containers to everyone and not just linux users.

I am struggling to understand the benefits of using Docker.

for me, the big advantage i see in docker is in my development efforts. i no longer have to worry about older projects that require older runtime libraries and dependencies. it's all encapsulated in docker.

then there's the production scaling and deployment story. with the community and user base around docker, there are simple solutions for nearly every scenario - from one server deployments, to auto-scaling and netflix level stuff that i'll never get near.

I'm just finding it difficult to understand Docker outside of a webapp server context

think slightly more broadly to any app or process that runs continuously, providing an API or service for other applications to consume. it's typically web based services, yes, but any TCP/IP or UDP enabled process should be able to work.

database systems, cache systems, key-value stores, web servers... anything with an always running process that provides an API over TCP/IP or UDP.

the big benefit here is encapsulating the service and all of it's runtime dependencies, like i was saying before.

need to run MongoDB 2.3 and 3.2 on your server? no problem. they are both in separate containers, can both run independently.

want to run mysql for this app, and mongo for that app? done.

containerization is powerful in helping keep apps separate from each other, and in helping to reduce the "works on my machine" problem.


问:
Saving XlsxWriter workbook more than once
I am writing software that manipulates Excel sheets. So far, I've been using xlrd and xlwt to do so, and everything works pretty well.

It opens a sheet (xlrd) and copies select columns to a new workbook (xlwt)

It then opens the newly created workbook to read data (xlrd) and does some math and formatting with the data (which couldn't be done if the file isn't saved once) - (xlwt saves once again)

However, I am now willing to add charts in my documents, and this function is not supported by xlwt. I have found that xlsxwriter does, but this adds other complications to my code: xlsxwriter only has xlsxwriter.close(), which saves AND closes the document.

Does anyone know if there's any workaround for this? Whenever I use xlsxwriter.close(), my workbook object containing the document I'm writing isn't usable anymore.

答:
Fundamentally, there is no reason you need to read twice and save twice. For your current (no charts) process, you can just read the data you need using xlrd; then do all your processing; and write once with xlwt.

Following this workflow, it is a relatively simple matter to replace xlwt with XlsxWriter.


问:
Reduced size of dictionary elements when two lists combined into a dictionary
I have 2 lists that I combined their elements into a dictionary. Both lists have size of 20, and the created dictionary is almost always 13-15. The code is:

```<code>nodes = []
for x in range(1,21):
    nodes.append(str(random.randint(1,20)))
print(nodes)
</code>```

Output:

```<code>['3', '6', '10', '12', '12', '10', '11', '17', '6', '19', '20', '19', '7', '16', '9', '13', '15', '9', '12', '5']
</code>```

The rest of the code:

```<code>lines=[]

fp = open("work.txt") # open file on read mode
lines = fp.read().split("\n") # create a list containing all lines
fp.close() # close file
print(lines)
</code>```

Output:

```<code>['5', '1', '7', '1', '1', '3', '12', '1', '1', '8', '7', '5', '12', '5', '5', '3', '7', '7', '13', '1', '']
</code>```

To make a dictionary:

```<code>dictionary = dict(zip(nodes,lines))
print(dictionary)

{'3': '1', '6': '5', '10': '12', '12': '13', '10': '12', '11': '7', '17': '7', '6': '5', '19': '3', '20': '1', '19': '1', '17': '3', '16': '5', '9': '7'}
</code>```

As you see, the size is got smaller to 14 when zipped. Do you know what is the reason and how can I fix it?

NOTE: I have to keep all the keys. The duplicates in the lists are on purpose.
NOTE2: The output should have the format above, the pairs of two numbers. (1,3) or (1:3) but not (1:3,4).

答:
For a node,line dictionary, you need unique keys. Creating a dict from non-unique keys overwrites the first ones at some point.

If you really want non-unique indexes, just store your data in a list of tuples. You won't get quick access but that will work:

```<code>tuples = list(zip(nodes,lines))
</code>```

Now if you want to gather the lines under the same node index, you can create a dictionary of lists of lines using for instance defaultdict:

```<code>import collections

d = collections.defaultdict(list)

for node,text in zip(nodes,lines):
    d[node].append(text)
</code>```

so for each unique node, you get a list of associated lines.

Body:
I have 2 lists that I combined their elements into a dictionary. Both lists have size of 20, and the created dictionary is almost always 13-15. The code is:

nodes = []
for x in range(1,21):
    nodes.append(str(random.randint(1,20)))
print(nodes)

Output:

['3', '6', '10', '12', '12', '10', '11', '17', '6', '19', '20', '19', '7', '16', '9', '13', '15', '9', '12', '5']

The rest of the code:

lines=[]

fp = open("work.txt") # open file on read mode
lines = fp.read().split("\n") # create a list containing all lines
fp.close() # close file
print(lines)

Output:

['5', '1', '7', '1', '1', '3', '12', '1', '1', '8', '7', '5', '12', '5', '5', '3', '7', '7', '13', '1', '']

To make a dictionary:

dictionary = dict(zip(nodes,lines))
print(dictionary)

{'3': '1', '6': '5', '10': '12', '12': '13', '10': '12', '11': '7', '17': '7', '6': '5', '19': '3', '20': '1', '19': '1', '17': '3', '16': '5', '9': '7'}

As you see, the size is got smaller to 14 when zipped. Do you know what is the reason and how can I fix it?

NOTE: I have to keep all the keys. The duplicates in the lists are on purpose.
NOTE2: The output should have the format above, the pairs of two numbers. (1,3) or (1:3) but not (1:3,4).

Body:
For a node,line dictionary, you need unique keys. Creating a dict from non-unique keys overwrites the first ones at some point.

If you really want non-unique indexes, just store your data in a list of tuples. You won't get quick access but that will work:

tuples = list(zip(nodes,lines))

Now if you want to gather the lines under the same node index, you can create a dictionary of lists of lines using for instance defaultdict:

import collections

d = collections.defaultdict(list)

for node,text in zip(nodes,lines):
    d[node].append(text)

so for each unique node, you get a list of associated lines.


问:
How to populate a FlatList's header with data from the network?
I have a FlatList that displays a user's comments and I want to also populate the header with the user's profile (which is a different network call from the one fetching the comments).

Here's how render() looks like:

```<code>render() {
    return (
      <FlatList
        data = {this.state.comments}
        renderItem = {this.renderComment}
        ListHeaderComponent={this.renderHeader}
        keyExtractor={(comment, index) => comment.id}
      />
    )
  }
</code>```

and then renderHeader looks like:

```<code>  renderHeader() {
     return (
      <ProfileView user={this.state.profile} />
    )
  }
</code>```

I use fetch in componentWillMount and then setState in order to get the data (this part works fine).
Now the error I get on the simulator is

undefined is not an object (evaluating 'this.state.profile')

but when I remove the renderHeader method, comments are fetched properly.

Since I'm very new to RN, can you help me understand what is wrong and how to fix it?

答:
This looks like simply an issue with accessing context. When you run the renderHeader method called by the FlatList it doesn't know what this relates to.

So, you can simply set this.renderHeader = this.renderHeader.bind(this) in your constructor() method.

Alternatively, you should also be able to use an arrow function to call it, as this automatically refers to the correct this context.

```<code>ListHeaderComponent={() => this.renderHeader()}
</code>```

Body:
I have a FlatList that displays a user's comments and I want to also populate the header with the user's profile (which is a different network call from the one fetching the comments).

Here's how render() looks like:

render() {
    return (
      <FlatList
        data = {this.state.comments}
        renderItem = {this.renderComment}
        ListHeaderComponent={this.renderHeader}
        keyExtractor={(comment, index) => comment.id}
      />
    )
  }

and then renderHeader looks like:

  renderHeader() {
     return (
      <ProfileView user={this.state.profile} />
    )
  }

I use fetch in componentWillMount and then setState in order to get the data (this part works fine).
Now the error I get on the simulator is

undefined is not an object (evaluating 'this.state.profile')

but when I remove the renderHeader method, comments are fetched properly.

Since I'm very new to RN, can you help me understand what is wrong and how to fix it?

Body:
This looks like simply an issue with accessing context. When you run the renderHeader method called by the FlatList it doesn't know what this relates to.

So, you can simply set this.renderHeader = this.renderHeader.bind(this) in your constructor() method.

Alternatively, you should also be able to use an arrow function to call it, as this automatically refers to the correct this context.

ListHeaderComponent={() => this.renderHeader()}


问:
How to create a "dot-dash" border with css or javascript?
In css3, they plan to add a border-style called "dot-dash" that will look like this:

Unfortunately, that is not yet implemented in any browser, and I need that kind of border now for a web-app.
The Application works with the Javascript-Framework ExtJS, so the solution of my problem can be a javascript one, too.

I already tried with a background-image (very bad solution, I know) - but that didn't work because there will be many divs with this border, which will all have different sizes (which I don't know before).

Thank you!

答:
If you need only the bottom border, you could try the following css

```<code>.class:after {
    content: '–⋅–⋅–⋅–⋅–⋅–';
    display: block;
    position: absolute;
    top: 30px;
    left: -4px;
    font-size: xx-large;
    font-weight: bolder;
    color: #59defc;
    height: 12px;
    overflow:hidden;
    width: 130px;
}
</code>```

Please note that  the dashes in the above code are special unicode characters and are not the ones on the english keyboard (those dots and dashes wont align on the same line).

Please change the pixel properties values to match your need. I found all these properties are needed to get the same behavior across multiple browsers.

@vals solution will work but with inconsistent results across browsers especially IE stretches the dashes.

ContentLicense: CC BY-SA 4.0

Body:
If you need only the bottom border, you could try the following css

.class:after {
    content: '–⋅–⋅–⋅–⋅–⋅–';
    display: block;
    position: absolute;
    top: 30px;
    left: -4px;
    font-size: xx-large;
    font-weight: bolder;
    color: #59defc;
    height: 12px;
    overflow:hidden;
    width: 130px;
}

Please note that  the dashes in the above code are special unicode characters and are not the ones on the english keyboard (those dots and dashes wont align on the same line).

Please change the pixel properties values to match your need. I found all these properties are needed to get the same behavior across multiple browsers.

@vals solution will work but with inconsistent results across browsers especially IE stretches the dashes.


问:
Make a div fill the remaining dynamic height and scroll without javascript
I have a document structure that maintains the header at the top of the page and the footer at the bottom. It's working well as long as the content in the middle is less than the height of the window. If the content is too long, the footer gets pushed further down the page and a full body scrollbar is displayed.
How can I get the scrollbar to be limited to the content DIV.

Note that the content of the header and footer are not fixed so I don't know the height of those elements and can't set the top position of the content element as a fixed value. I've added a show/hide feature in the example to demonstrate this.

I'm trying to resolve this in pure CSS (avoiding Javascript). I know that using javascript, I could monitor changes to window size and element visibility, I could calculate the height of the header and footer and set fixed dimensions to the content element. But is there a non-javascript solution?

http://jsfiddle.net/sA5fD/1/

```<code>html { height: 100%; }
body {
    padding:0 0;
    margin:0 0;
    height: 100%;
}
#main {
    display:table;
    height:100%;
    width:100%;
}
#header, #footer {
    display:table-row;
    background:#88f;
}
#more {
    display: none;
}
#content {
    display:table-row;
    height:100%;
    background:#8f8;
}
</code>```

It should work for all modern browsers, desktop, tablets and mobiles. For old browsers, a full body scrollbar would be ok.

答:
For future visitors:

HTML

```<code><div class="parent">

  <div class="child">
    <div class="large-element> </div>
  </div>

</div>
</code>```

CSS

```<code> .parent {
   height: 1000px
   overflow-y: scroll;
 }

 .child {
   background-color: royalblue;
   height: auto;
 }

 .large-element {
   height: 1200px;
 }
</code>```

In this scenario, the child element will create an overflow. Since the child's height is set to auto, it will stretch out to fill the container. If you had set it to 100%, it would only go 1000px, leaving some white space beneath!

Here is a pen: https://codepen.io/meteora/pen/JJYoZM

This should work in all browsers :)

Body:
I have a document structure that maintains the header at the top of the page and the footer at the bottom. It's working well as long as the content in the middle is less than the height of the window. If the content is too long, the footer gets pushed further down the page and a full body scrollbar is displayed.
How can I get the scrollbar to be limited to the content DIV.

Note that the content of the header and footer are not fixed so I don't know the height of those elements and can't set the top position of the content element as a fixed value. I've added a show/hide feature in the example to demonstrate this.

I'm trying to resolve this in pure CSS (avoiding Javascript). I know that using javascript, I could monitor changes to window size and element visibility, I could calculate the height of the header and footer and set fixed dimensions to the content element. But is there a non-javascript solution?

http://jsfiddle.net/sA5fD/1/

html { height: 100%; }
body {
    padding:0 0;
    margin:0 0;
    height: 100%;
}
#main {
    display:table;
    height:100%;
    width:100%;
}
#header, #footer {
    display:table-row;
    background:#88f;
}
#more {
    display: none;
}
#content {
    display:table-row;
    height:100%;
    background:#8f8;
}

It should work for all modern browsers, desktop, tablets and mobiles. For old browsers, a full body scrollbar would be ok.

Body:
For future visitors:

HTML

<div class="parent">

  <div class="child">
    <div class="large-element> </div>
  </div>

</div>

CSS

 .parent {
   height: 1000px
   overflow-y: scroll;
 }

 .child {
   background-color: royalblue;
   height: auto;
 }

 .large-element {
   height: 1200px;
 }

In this scenario, the child element will create an overflow. Since the child's height is set to auto, it will stretch out to fill the container. If you had set it to 100%, it would only go 1000px, leaving some white space beneath!

Here is a pen: https://codepen.io/meteora/pen/JJYoZM

This should work in all browsers :)


问:
How can I translate a perl script to Java?

Possible Duplicate:

  How can I convert OO Perl to Java?

Hello.

I have a perl script and I want to translate it to Java.

Is there any translator/conversor from perl script to Java?

By the way, I'm developing an Android 2.2 application.

EDIT

I have closed the question. Stop downvoting me!!!!!! And if you downvote tell us why!!

Thanks.

答:
You should consider using the Android Scripting Environment so that you can just use your Perl script rather than having to "translate" it to Java (especially if you plan on relying on some translation tool to do it).

It supports Perl, along with Python, Ruby, and some others.


问:
Is possible to capture the button name in a MessageFilter function?
I have the following code and I need to know the name of a button because that button is the only one that is enabled to perform task.</p>

```<code>Class MessageFilter
    Implements IMessageFilter
    Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
        If Form1.SavingData Then
            Const WM_KEYDOWN As Integer = &H100
            'Const WM_MOUSELEAVE As Integer = &H2A3
            Const WM_MOUSE_LEFT_CLICK As Integer = &H201

            Select Case m.Msg
                Case WM_KEYDOWN, WM_MOUSE_LEFT_CLICK
                    ' Do something to indicate the user is still active.
                    Form1.SavingData = False

                    Exit Select
            End Select

            ' Returning true means that this message should stop here,
            ' we aren't actually filtering messages, so we need to return false.
        End If

        Return False
    End Function
End Class
</code>```

答:
I recommend that you do not use the default Form1 instance and instead pass the form reference as a argument to the message filter's constructor.  Default form instances where added to VB to facilitate converting VB6 code to VB.Net.

If you declare your filter class like this:

```<code>Class MessageFilter
     Implements IMessageFilter
     Private frm As Form1
     Private targetButton As Button
     Public Sub New(frm As Form1, targetbutton As Button)
        Me.frm = frm
        Me.targetButton = targetbutton
     End Sub

    Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
        Const WM_KEYDOWN As Integer = &H100
        Const WM_MOUSE_LEFT_CLICK As Integer = &H201

        If Me.frm.SavingData AndAlso
            m.HWnd = Me.targetButton.Handle AndAlso
            (m.Msg = WM_KEYDOWN OrElse m.Msg = WM_MOUSE_LEFT_CLICK) Then
            Me.frm.SavingData = False
        End If
        ' Returning true means that this message should stop here,
        ' we aren't actually filtering messages, so we need to return false.
        Return False
    End Function
End Class
</code>```

You can apply the filter like this:

```<code>Private filter As MessageFilter

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    filter = New MessageFilter(Me, Me.Button2)
    Application.AddMessageFilter(filter)
End Sub
</code>```

This allows you to specify the specific Button you want to use.  The filter checks to see if the message is to be sent to that particular Button using its Handle property that will be a unique value instead of using its Name property.

Body:
I have the following code and I need to know the name of a button because that button is the only one that is enabled to perform task.

Class MessageFilter
    Implements IMessageFilter
    Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
        If Form1.SavingData Then
            Const WM_KEYDOWN As Integer = &H100
            'Const WM_MOUSELEAVE As Integer = &H2A3
            Const WM_MOUSE_LEFT_CLICK As Integer = &H201

            Select Case m.Msg
                Case WM_KEYDOWN, WM_MOUSE_LEFT_CLICK
                    ' Do something to indicate the user is still active.
                    Form1.SavingData = False

                    Exit Select
            End Select

            ' Returning true means that this message should stop here,
            ' we aren't actually filtering messages, so we need to return false.
        End If

        Return False
    End Function
End Class

Body:
I recommend that you do not use the default Form1 instance and instead pass the form reference as a argument to the message filter's constructor.  Default form instances where added to VB to facilitate converting VB6 code to VB.Net.

If you declare your filter class like this:

Class MessageFilter
     Implements IMessageFilter
     Private frm As Form1
     Private targetButton As Button
     Public Sub New(frm As Form1, targetbutton As Button)
        Me.frm = frm
        Me.targetButton = targetbutton
     End Sub

    Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
        Const WM_KEYDOWN As Integer = &H100
        Const WM_MOUSE_LEFT_CLICK As Integer = &H201

        If Me.frm.SavingData AndAlso
            m.HWnd = Me.targetButton.Handle AndAlso
            (m.Msg = WM_KEYDOWN OrElse m.Msg = WM_MOUSE_LEFT_CLICK) Then
            Me.frm.SavingData = False
        End If
        ' Returning true means that this message should stop here,
        ' we aren't actually filtering messages, so we need to return false.
        Return False
    End Function
End Class

You can apply the filter like this:

Private filter As MessageFilter

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    filter = New MessageFilter(Me, Me.Button2)
    Application.AddMessageFilter(filter)
End Sub

This allows you to specify the specific Button you want to use.  The filter checks to see if the message is to be sent to that particular Button using its Handle property that will be a unique value instead of using its Name property.


问:
VLOOKUP (or INDEX/MATCH) through multiple columns, but get value from other column
Hope to have a relatively simple question.

I use VLOOKUP every day, for comparing 2 lists of itemnumbers and corresponding stock.

In a new situation itemnumbers are not longer in only one column, but the correct one could be in column A, B or C. While the stock is always in F.

Is it possible with VLOOKUP, or INDEX/MATCH to fill the corresponding stock in the orange cells, according to the itemnumber in one of three columns?

Many thanks in advance, Richard

答:
Say we have data like:

We want to lookup the word hello in the table from A1 to H14 and retrieve the associated value from column J

Pick some cell, say K1, and enter:

Hello

Then in another cell enter the array formula:

```<code>=INDEX(J1:J14,MIN(IF($A$1:$H$14=K1,ROW($A$1:$H$14)-ROW($A$1)+1)))
</code>```

Array formulas must be entered with Ctrl + Shift + Enter rather than just the Enter key.

Body:
Say we have data like:

We want to lookup the word hello in the table from A1 to H14 and retrieve the associated value from column J

Pick some cell, say K1, and enter:

Hello

Then in another cell enter the array formula:

=INDEX(J1:J14,MIN(IF($A$1:$H$14=K1,ROW($A$1:$H$14)-ROW($A$1)+1)))

Array formulas must be entered with Ctrl + Shift + Enter rather than just the Enter key.


问:
Wordpress WP_Query/get_posts where post_title equals returns all results
I've created a custom post type called 'snippets' where there are snippets of data like 'address' that the client can change.

The title of the snippets are all unique:

I have created a simple function to return these snippets however it's not working quite right and I'm not sure why.

Function:

```<code>function get_snippet($snippet_title) {
    $snippet_page = new WP_Query(array(
        'post_type' => 'snippets',
        'post_title' => $snippet_title
    ));
    return $snippet_page->posts[0]->post_content;
}
</code>```

Here is an example call to the function:

```<code>echo get_snippet('footer_address');
</code>```

The issue is:

It will always return all the snippets and not filter by post_title.

Even if I use get_posts() it will always return all snippets in the same order and will not return the single snippet based on the post_title.

The result is instead the equivalent to:

```<code>$snippet_page = new WP_Query(array(
    'post_type' => 'snippets'
));
</code>```

Why will it not filter by 'post_title'?

Thanks

(I am also using multisite)

Here is my custom post type init code:

```<code>function snippets() {
    $labels = array(
        'name'                => _x( 'Snippets', 'Post Type General Name', 'text_domain' ),
        'singular_name'       => _x( 'Snippet', 'Post Type Singular Name', 'text_domain' ),
        'menu_name'           => __( 'Snippets', 'text_domain' ),
        'name_admin_bar'      => __( 'Snippets', 'text_domain' ),
        'parent_item_colon'   => __( 'Parent Item:', 'text_domain' ),
        'all_items'           => __( 'All Snippets', 'text_domain' ),
        'add_new_item'        => __( 'Add New Snippet', 'text_domain' ),
        'add_new'             => __( 'Add New Snippet', 'text_domain' ),
        'new_item'            => __( 'New Snippet', 'text_domain' ),
        'edit_item'           => __( 'Edit Snippet', 'text_domain' ),
        'update_item'         => __( 'Update Snippet', 'text_domain' ),
        'view_item'           => __( 'View Snippet', 'text_domain' ),
        'search_items'        => __( 'Search Snippet', 'text_domain' ),
        'not_found'           => __( 'Not found', 'text_domain' ),
        'not_found_in_trash'  => __( 'Not found in Trash', 'text_domain' ),
    );
    $args = array(
        'label'               => __( 'snippets', 'text_domain' ),
        'description'         => __( 'For custom snippets of code/data.', 'text_domain' ),
        'labels'              => $labels,
        'supports'            => array( ),
        'hierarchical'        => false,
        'public'              => false,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'menu_icon'           => 'dashicons-tagcloud',
        'menu_position'       => 5,
        'show_in_admin_bar'   => true,
        'show_in_nav_menus'   => false,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => true,
        'publicly_queryable'  => false,
        'capability_type'     => 'page',
    );
    register_post_type( 'snippets', $args );
}
add_action( 'init', 'snippets', 0 );
</code>```

答:
I know that this is a very old post, but maybe someone will be searching for the solution just like I did today.

It turns out that you just need to use 'title' instead of 'post_title'.

Here is an example:

```<code>$author_id = 20;
$args = array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'post_status' => 'inherit',
    'title' => 'Reviewer Plugin - User review image',
    'author' => $author_id,
);
$attachments = get_posts($args);
if ($attachments) {
    foreach ($attachments as $attachedfile) {
        $mediaIds =  $attachedfile->ID .','. $mediaIds;
    }
    $mediaIds = rtrim($mediaIds,",");
}
print_r($mediaIds);
</code>```

Body:
I've created a custom post type called 'snippets' where there are snippets of data like 'address' that the client can change.

The title of the snippets are all unique:

I have created a simple function to return these snippets however it's not working quite right and I'm not sure why.

Function:

function get_snippet($snippet_title) {
    $snippet_page = new WP_Query(array(
        'post_type' => 'snippets',
        'post_title' => $snippet_title
    ));
    return $snippet_page->posts[0]->post_content;
}

Here is an example call to the function:

echo get_snippet('footer_address');

The issue is:

It will always return all the snippets and not filter by post_title.

Even if I use get_posts() it will always return all snippets in the same order and will not return the single snippet based on the post_title.

The result is instead the equivalent to:

$snippet_page = new WP_Query(array(
    'post_type' => 'snippets'
));

Why will it not filter by 'post_title'?

Thanks

(I am also using multisite)

Here is my custom post type init code:

function snippets() {
    $labels = array(
        'name'                => _x( 'Snippets', 'Post Type General Name', 'text_domain' ),
        'singular_name'       => _x( 'Snippet', 'Post Type Singular Name', 'text_domain' ),
        'menu_name'           => __( 'Snippets', 'text_domain' ),
        'name_admin_bar'      => __( 'Snippets', 'text_domain' ),
        'parent_item_colon'   => __( 'Parent Item:', 'text_domain' ),
        'all_items'           => __( 'All Snippets', 'text_domain' ),
        'add_new_item'        => __( 'Add New Snippet', 'text_domain' ),
        'add_new'             => __( 'Add New Snippet', 'text_domain' ),
        'new_item'            => __( 'New Snippet', 'text_domain' ),
        'edit_item'           => __( 'Edit Snippet', 'text_domain' ),
        'update_item'         => __( 'Update Snippet', 'text_domain' ),
        'view_item'           => __( 'View Snippet', 'text_domain' ),
        'search_items'        => __( 'Search Snippet', 'text_domain' ),
        'not_found'           => __( 'Not found', 'text_domain' ),
        'not_found_in_trash'  => __( 'Not found in Trash', 'text_domain' ),
    );
    $args = array(
        'label'               => __( 'snippets', 'text_domain' ),
        'description'         => __( 'For custom snippets of code/data.', 'text_domain' ),
        'labels'              => $labels,
        'supports'            => array( ),
        'hierarchical'        => false,
        'public'              => false,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'menu_icon'           => 'dashicons-tagcloud',
        'menu_position'       => 5,
        'show_in_admin_bar'   => true,
        'show_in_nav_menus'   => false,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => true,
        'publicly_queryable'  => false,
        'capability_type'     => 'page',
    );
    register_post_type( 'snippets', $args );
}
add_action( 'init', 'snippets', 0 );

Body:
I know that this is a very old post, but maybe someone will be searching for the solution just like I did today.

It turns out that you just need to use 'title' instead of 'post_title'.

Here is an example:

$author_id = 20;
$args = array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'post_status' => 'inherit',
    'title' => 'Reviewer Plugin - User review image',
    'author' => $author_id,
);
$attachments = get_posts($args);
if ($attachments) {
    foreach ($attachments as $attachedfile) {
        $mediaIds =  $attachedfile->ID .','. $mediaIds;
    }
    $mediaIds = rtrim($mediaIds,",");
}
print_r($mediaIds);


问:
Bad Data exception during RSA decryption
I was working on a project. Encryption is working fine but when it comes to decryption my program is throwing "Bad data Exception". How do I remedy this problem?</p>

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace WindowsFormsApplication2
{

    public partial class Form1 : Form
    {
        byte[] cipher;
        byte[] plain;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private static string Encrypt(byte[] plain)
        {
            byte[] encrypted;
          RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                StreamReader StRe = new StreamReader("D:\\PjesaVetemPublike.xml");
                string VetemPublikeXML = StRe.ReadToEnd();
                rsa.FromXmlString(VetemPublikeXML);
                StRe.Close();
                encrypted = rsa.Encrypt(plain, true);

            return Encoding.UTF8.GetString(encrypted);
        }

        private static string Decrypt(byte[] encrypted)
        {
            byte[] decrypted;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                StreamReader StRe = new
         StreamReader("D:\\PjesaPublikeDhePrivate.xml");
                string PublikeDhePrivate = StRe.ReadToEnd();
                rsa.FromXmlString(PublikeDhePrivate);
                StRe.Close();

                decrypted = rsa.Decrypt(encrypted, false);   //THE ERROR APPEARS RIGHT HERE

            return Encoding.UTF8.GetString(decrypted);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            plain = Encoding.UTF8.GetBytes(txtPlain.Text);
            txtCipher.Text = Encrypt(plain);

        }

        private void button2_Click(object sender, EventArgs e)
        {

            txtDekriptuar.Text = Decrypt(cipher);
        }
    }
}
</code>```

答:
Among other problems you are assuming that the ciphertext can be converted to UTF-8 meaningfully, and that isn't guaranteed.

If you want to encrypt text and transmit/store the encrypted contents as text you need to follow this pattern:

Encrypt(textIn => textOut):

Convert textIn to bytesIn via some encoding.  UTF-8 is pretty good.

Encrypt bytesIn to bytesOut.

Apply a lossless encoding to bytesOut.  Base64 is almost always the best choice for this, and is the best one that's built in to .NET.  (textOut = Convert.ToBase64String(bytesOut)).

Return textOut.

Decrypt(textIn => textOut):

Apply the inverse transform from Encrypt to turn textIn to bytesIn.  So likely Convert.FromBase64String.

Decrypt bytesIn to bytesOut.

Apply a text encoding transform to turn bytesOut to textOut. There's nothing that really says that this needs to be the same as the one used in Encrypt, but it probably makes sense to do so.

The problem with using UTF-8 (or ASCII or UCS-2, etc) for a textual representation of encrypted data is that the encrypted data can legitimately contain a byte whose value is 0x00 (or a control code, linebreak, etc).  While .NET, for the most part, happily transports embedded null characters in a string it definitely can be a large source of confusion (and not all languages/functions handle it the same).

Other fun characters:

What does your language/function do for an embedded 0x7F (Delete)?

If you store the string in a single-line text field, what happens to any CR or LF characters?  What does your program do on Windows if it gets CR without LF, or LF without CR?

A Unix command-line with 0x13 (^S) may appear to hang, but it's just waiting on 0x11 (^Q).

What encodings to use for storing ciphertext?  Well, anything that safely packs control characters.

Base64: 33% increase in storage: 3 bytes => 4 ASCII characters == 4 bytes

Hexadecimal (aka Base16): 100% increase in storage, but easier to inspect than Base64

Other, less common options are summarized at https://en.wikipedia.org/wiki/Binary-to-text_encoding#Encoding_standards.

Body:
I was working on a project. Encryption is working fine but when it comes to decryption my program is throwing "Bad data Exception". How do I remedy this problem?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace WindowsFormsApplication2
{

    public partial class Form1 : Form
    {
        byte[] cipher;
        byte[] plain;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private static string Encrypt(byte[] plain)
        {
            byte[] encrypted;
          RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                StreamReader StRe = new StreamReader("D:\\PjesaVetemPublike.xml");
                string VetemPublikeXML = StRe.ReadToEnd();
                rsa.FromXmlString(VetemPublikeXML);
                StRe.Close();
                encrypted = rsa.Encrypt(plain, true);

            return Encoding.UTF8.GetString(encrypted);
        }

        private static string Decrypt(byte[] encrypted)
        {
            byte[] decrypted;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                StreamReader StRe = new
         StreamReader("D:\\PjesaPublikeDhePrivate.xml");
                string PublikeDhePrivate = StRe.ReadToEnd();
                rsa.FromXmlString(PublikeDhePrivate);
                StRe.Close();

                decrypted = rsa.Decrypt(encrypted, false);   //THE ERROR APPEARS RIGHT HERE

            return Encoding.UTF8.GetString(decrypted);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            plain = Encoding.UTF8.GetBytes(txtPlain.Text);
            txtCipher.Text = Encrypt(plain);

        }

        private void button2_Click(object sender, EventArgs e)
        {

            txtDekriptuar.Text = Decrypt(cipher);
        }
    }
}


问:
Doctrine flush changes and free up memory
I'm experiencing problems working on a Symfony project with low memory limit. I need to create several entities, add them to another entity (entities are associated) and then flush changes to database. This happens in a while loop.

The problem is that sometimes the loop can't finish the whole cycle because the process crashes for memory exhausting. Of course I can't raise the memory limit.

I try to explain you better with some code...

Entities structure

```<code>class Device
{
    /**
     * @ORM\ManyToMany(targetEntity="Resource", inversedBy="devices",cascade={"persist", "refresh"}, fetch="EXTRA_LAZY")
     */
    protected $resources;

    public function addResource(Resource $resource)
    {
        if ($this->resources->contains($resource)) return;
        $this->resources->add($resource);
        $resource->addDevice($this);
    }
}

class Resource
{
    /**
     * @ORM\ManyToMany(targetEntity="Device", mappedBy="resources")
     */
    protected $devices;

    public function addDevice(Device $device)
    {
        if ($this->devices->contains($device)) return;
        $this->devices->add($device);
        $device->addResource($this);
    }
}
</code>```

The loop

```<code>function doIt(Device $device) {
    while(...) {
        $res = new Resource(...);
        $device->addResource($res); // store $res in memory until end
    }
    $em->persist($device);
    $em->flush();
}
</code>```

So the problem is that until the loop finishes, $device keeps in memory Resource objects and sometimes memory limit is reached.

What I tried so far

```<code>function doIt(Device $device) {
   $i = 0;
   while(...) {
       $res = new Resource(...);
       $device->addResource($res);
       $i++;
       if ($i % 100 == 0) {
              $em->persist($device);
              $em->flush($device);
              $device->setResources(null); // free up Resources in memory
              $em->refresh($device); // Resources are not stored in memory
       }
   }
   $em->persist($device);
   $em->flush();
}
</code>```

This works not that good even because I see memory raising anyway (probably caused then by Doctrine). Moreover there are a lot of entities and several associations between them, and checking results in database gives me something wrong (e.g. an Entity not persisted).

What would you do?

答:
There are a few things you can try to improve the situation:

Disable doctrine SQL logging mechanism in the setup stage of your import

```<code>$this->getContainer()->get('doctrine')->getConnection()->getConfiguration()->setSQLLogger(null);
</code>```

Try calling a clear periodically (i do it after a batch of items is processed and flushed), but read the docs before because there may be side effects depending on your code

```<code>$this->entityManager->clear();
</code>```

You already seem to be clearing all unused objects and variables you could also try calling a manual gc_collect_cycle in php

```<code>gc_collect_cycles();
</code>```

If your import is executed with a symfony Command make sure you start it with the --no-debug flag

Worked fine with an import command within my project although it didn't achieve complete memory neutrality but the remaining leaks were negligible.
Maybe this can help in your case.

Body:
I'm experiencing problems working on a Symfony project with low memory limit. I need to create several entities, add them to another entity (entities are associated) and then flush changes to database. This happens in a while loop.

The problem is that sometimes the loop can't finish the whole cycle because the process crashes for memory exhausting. Of course I can't raise the memory limit.

I try to explain you better with some code...

Entities structure

class Device
{
    /**
     * @ORM\ManyToMany(targetEntity="Resource", inversedBy="devices",cascade={"persist", "refresh"}, fetch="EXTRA_LAZY")
     */
    protected $resources;

    public function addResource(Resource $resource)
    {
        if ($this->resources->contains($resource)) return;
        $this->resources->add($resource);
        $resource->addDevice($this);
    }
}

class Resource
{
    /**
     * @ORM\ManyToMany(targetEntity="Device", mappedBy="resources")
     */
    protected $devices;

    public function addDevice(Device $device)
    {
        if ($this->devices->contains($device)) return;
        $this->devices->add($device);
        $device->addResource($this);
    }
}

The loop

function doIt(Device $device) {
    while(...) {
        $res = new Resource(...);
        $device->addResource($res); // store $res in memory until end
    }
    $em->persist($device);
    $em->flush();
}

So the problem is that until the loop finishes, $device keeps in memory Resource objects and sometimes memory limit is reached.

What I tried so far

function doIt(Device $device) {
   $i = 0;
   while(...) {
       $res = new Resource(...);
       $device->addResource($res);
       $i++;
       if ($i % 100 == 0) {
              $em->persist($device);
              $em->flush($device);
              $device->setResources(null); // free up Resources in memory
              $em->refresh($device); // Resources are not stored in memory
       }
   }
   $em->persist($device);
   $em->flush();
}

This works not that good even because I see memory raising anyway (probably caused then by Doctrine). Moreover there are a lot of entities and several associations between them, and checking results in database gives me something wrong (e.g. an Entity not persisted).

What would you do?

Body:
There are a few things you can try to improve the situation:

Disable doctrine SQL logging mechanism in the setup stage of your import

$this->getContainer()->get('doctrine')->getConnection()->getConfiguration()->setSQLLogger(null);

Try calling a clear periodically (i do it after a batch of items is processed and flushed), but read the docs before because there may be side effects depending on your code

$this->entityManager->clear();

You already seem to be clearing all unused objects and variables you could also try calling a manual gc_collect_cycle in php

gc_collect_cycles();

If your import is executed with a symfony Command make sure you start it with the --no-debug flag

Worked fine with an import command within my project although it didn't achieve complete memory neutrality but the remaining leaks were negligible.
Maybe this can help in your case.


问:
Changing the color of the stroke dynamically in Recyclerview Adapter class
How to change the color of the stroke which is in rectangle in shape? I want to change the color dynamically in top stroke or bottom stroke color of the particular item in RecyclerView Adapter.

@drawable/border_custom

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- TOP STROKE-->
<item android:top="15dp" android:id="@+id/deviceTop">
    <shape android:shape="rectangle">
        <solid android:color="@color/ripple_divider" />
    </shape>
</item>
<!-- BOTTOM STROKE-->
<item android:top="15dp" android:id="@+id/deviceBottom">
    <shape android:shape="rectangle">
        <solid android:color="@color/ripple_divider" />
    </shape>
</item>
<!--LEFT STROKE-->
<item android:left="15dp" android:id="@+id/deviceLeft">
    <shape android:shape="rectangle">
        <solid android:color="@color/ripple_divider" />
    </shape>
</item>
<!--RIGHT STROKE-->
<item android:right="15dp" android:id="@+id/deviceRight">
    <shape android:shape="rectangle">
        <solid android:color="@color/ripple_divider" />
    </shape>
</item>
<!-- MAIN SHAPE -->
<item android:top="15dp" android:bottom="15dp" android:left="15dp" android:right="15dp">
    <shape android:shape="rectangle">
        <solid android:color="@color/ripple_white" />
    </shape>
</item>
</code>```

Here is my XML file where I am using above XML in my Linear Layout the background

```<code><LinearLayout
    android:id="@+id/llDevice"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="@drawable/border_device"
    android:orientation="vertical"
    android:gravity="center_horizontal|center_vertical"/>
</code>```

and my Main Activity XML

```<code><android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="1dp"
        android:layout_marginTop="16dp"
        android:scrollbars="vertical"
        android:visibility="gone" />
</code>```

How can I achieve this?

答:
You can get a reference to your Drawable as a LayerDrawable via:

```<code>LayerDrawable layerDrawable = (LayerDrawable) getResources()
                    .getDrawable(R.drawable.border_device);
</code>```

And then you can reference your different layers via their id's

```<code>GradientDrawable leftSide = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.deviceLeft);
</code>```

And lastly modify it's color:

```<code>leftSide.setColor(Color.GRAY);
</code>```

Body:
How to change the color of the stroke which is in rectangle in shape? I want to change the color dynamically in top stroke or bottom stroke color of the particular item in RecyclerView Adapter.

@drawable/border_custom

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:top="15dp" android:id="@+id/deviceTop">
    <shape android:shape="rectangle">
        <solid android:color="@color/ripple_divider" />
    </shape>
</item>

<item android:top="15dp" android:id="@+id/deviceBottom">
    <shape android:shape="rectangle">
        <solid android:color="@color/ripple_divider" />
    </shape>
</item>

<item android:left="15dp" android:id="@+id/deviceLeft">
    <shape android:shape="rectangle">
        <solid android:color="@color/ripple_divider" />
    </shape>
</item>

<item android:right="15dp" android:id="@+id/deviceRight">
    <shape android:shape="rectangle">
        <solid android:color="@color/ripple_divider" />
    </shape>
</item>

<item android:top="15dp" android:bottom="15dp" android:left="15dp" android:right="15dp">
    <shape android:shape="rectangle">
        <solid android:color="@color/ripple_white" />
    </shape>
</item>

Here is my XML file where I am using above XML in my Linear Layout the background

<LinearLayout
    android:id="@+id/llDevice"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="@drawable/border_device"
    android:orientation="vertical"
    android:gravity="center_horizontal|center_vertical"/>

and my Main Activity XML

<android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="1dp"
        android:layout_marginTop="16dp"
        android:scrollbars="vertical"
        android:visibility="gone" />

How can I achieve this?

Body:
You can get a reference to your Drawable as a LayerDrawable via:

LayerDrawable layerDrawable = (LayerDrawable) getResources()
                    .getDrawable(R.drawable.border_device);

And then you can reference your different layers via their id's

GradientDrawable leftSide = (GradientDrawable) layerDrawable.findDrawableByLayerId(R.id.deviceLeft);

And lastly modify it's color:

leftSide.setColor(Color.GRAY);


问:
pandas adding new rows to dataframe based on dataframe values
I have transactional data for users as follows:

```<code>userid accountid weeknumber amount_spent
1      a         1          100
1      a         2          200
1      a         4          500
1      b         1          500
...
9      z         1          350
</code>```

The data only captured weeks where the user had transactions. I need to go through the data and add rows for when the user didn't spend any money.

E.g. I need to add rows like:

```<code>userid accountid weeknumber amount_spent
1      a         3          0
</code>```

Currently I do it as follows:

```<code># get all user-account pairs
for user_acct_pair in df.groupby(['userid', 'accountid']).groups.iterkeys():
    userid = user_acct_pair[0]
    acctid = user_acct_pair[1]

# get the weeks that we have recorded for this user
weeks_recorded = df.xs((userid, acctid), axis=0, level=[0, 1], \
                              drop_level=True).index.values

for i in range(1, MAX_WEEK_NUMBER):
    if i not in weeks_recorded:
        # add the row for the week without transactions
        df.loc[(userid, acctid, i), 'amount_spent'] = 0

# convert back to df from groupby object
df = df.reset_index()
</code>```

This seems to be incredibly slow when I run on a dataset with ~90,000 rows.
I think that there is a high cost in finding a row in a multilevel index when the row doesn't exist yet.

Are there more efficient ways to do this, or perhaps built in functionalities to achieve what I'm trying to do?

答:
Personally I would forget groupby and iterating through the dataframe. I would just create a dataframe that looks like the empty rows you want, and then merge in the data that is populated.

```<code>#create your existing data
df = pd.DataFrame({'userId'    : [1, 1, 1, 1, 2],
                   'accountId' : ['a', 'a', 'a', 'b', 'z'],
                   'week'            : [1, 2, 4, 1, 1],
                   'amount'    : [100, 200, 500, 500, 350]})

#create unique ID pairs
unique_ids = set(zip(df['userId'], df['accountId']))

#create empty data frame
new_df = pd.DataFrame({'userId'    :  np.repeat([val[0] for val in unique_ids], 5),
                       'accountId' :  np.repeat([val[1] for val in unique_ids], 5),
                       'week'      :  np.tile(list(range(1, 6)), len(unique_ids))})

#merge
pd.merge(df, new_df, how = 'outer').sort_values(['accountId', 'userId', 'week']).fillna(0)
</code>```

This is for a 5 week period. The result is:

```<code>   accountId  amount  userId  week
0          a   100.0       1     1
1          a   200.0       1     2
5          a     0.0       1     3
2          a   500.0       1     4
6          a     0.0       1     5
3          b   500.0       1     1
11         b     0.0       1     2
12         b     0.0       1     3
13         b     0.0       1     4
14         b     0.0       1     5
4          z   350.0       2     1
7          z     0.0       2     2
8          z     0.0       2     3
9          z     0.0       2     4
10         z     0.0       2     5
</code>```

Body:
I have transactional data for users as follows:

userid accountid weeknumber amount_spent
1      a         1          100
1      a         2          200
1      a         4          500
1      b         1          500
...
9      z         1          350

The data only captured weeks where the user had transactions. I need to go through the data and add rows for when the user didn't spend any money.

E.g. I need to add rows like:

userid accountid weeknumber amount_spent
1      a         3          0

Currently I do it as follows:

# get all user-account pairs
for user_acct_pair in df.groupby(['userid', 'accountid']).groups.iterkeys():
    userid = user_acct_pair[0]
    acctid = user_acct_pair[1]

# get the weeks that we have recorded for this user
weeks_recorded = df.xs((userid, acctid), axis=0, level=[0, 1], \
                              drop_level=True).index.values

for i in range(1, MAX_WEEK_NUMBER):
    if i not in weeks_recorded:
        # add the row for the week without transactions
        df.loc[(userid, acctid, i), 'amount_spent'] = 0

# convert back to df from groupby object
df = df.reset_index()

This seems to be incredibly slow when I run on a dataset with ~90,000 rows.
I think that there is a high cost in finding a row in a multilevel index when the row doesn't exist yet.

Are there more efficient ways to do this, or perhaps built in functionalities to achieve what I'm trying to do?

Body:
Personally I would forget groupby and iterating through the dataframe. I would just create a dataframe that looks like the empty rows you want, and then merge in the data that is populated.

#create your existing data
df = pd.DataFrame({'userId'    : [1, 1, 1, 1, 2],
                   'accountId' : ['a', 'a', 'a', 'b', 'z'],
                   'week'            : [1, 2, 4, 1, 1],
                   'amount'    : [100, 200, 500, 500, 350]})

#create unique ID pairs
unique_ids = set(zip(df['userId'], df['accountId']))

#create empty data frame
new_df = pd.DataFrame({'userId'    :  np.repeat([val[0] for val in unique_ids], 5),
                       'accountId' :  np.repeat([val[1] for val in unique_ids], 5),
                       'week'      :  np.tile(list(range(1, 6)), len(unique_ids))})

#merge
pd.merge(df, new_df, how = 'outer').sort_values(['accountId', 'userId', 'week']).fillna(0)

This is for a 5 week period. The result is:

   accountId  amount  userId  week
0          a   100.0       1     1
1          a   200.0       1     2
5          a     0.0       1     3
2          a   500.0       1     4
6          a     0.0       1     5
3          b   500.0       1     1
11         b     0.0       1     2
12         b     0.0       1     3
13         b     0.0       1     4
14         b     0.0       1     5
4          z   350.0       2     1
7          z     0.0       2     2
8          z     0.0       2     3
9          z     0.0       2     4
10         z     0.0       2     5


问:
What's the difference between Laravel automatic injection and manually specifying the dependencies in the constructor body?
I'm using a Repository pattern in my Laravel project. This pattern is not really explained in the official documentation, except for this snippet:

You may type-hint a repository defined by your application in a controller's constructor. The repository will automatically be resolved and injected into the class.

This is my code, in accordance with the documentation:

```<code>class CategoriesController extends Controller
{
    protected $repo;

    public function __construct(CategoriesRepository $repo)
    {
        $this->repo = $repo;
    }
</code>```

I've type-hinted the CategoriesRepository so it gets automatically loaded by the Service Container.

However, if I directly create a new instance of the CategoriesController class (without using the Service Container), I have to specify that I need a new instance of the CategoriesRepository too, like this:

```<code>$example = new CategoriesController(new CategoriesRepository());
</code>```

Now, let's suppose I write the following code.

```<code>class CategoriesController extends Controller
{
    protected $repo;

    public function __construct()
    {
        $this->repo = new CategoriesRepository();
    }
</code>```

This way, I don't have to load the class through the Service Container, nor call it by passing a new instance of CategoriesRepository as the argument, because it's automatically created inside of the constructor.

So, my question is: would this be bad practice? What's the difference between type-hinting as a parameter and creating a new instance inside of the constructor?

答:
Here's the beauty of dependency injection:

Complex initialization

```<code>class MyController {

     public function __construct(A $a) { }
}

class A {
     public function __construct(B $b) { }
}
class B {
     public function __construct(C $c) { }
}

class C {
     public function __construct(D $d) { }
}
class D {
     public function __construct() { }
}
</code>```

Now you can ask laravel to create that class for you e.g:

```<code>$controller = make(MyController::class);
</code>```

or you can do:

```<code>$controller = new MyController(new A(new B(new C(new D())))));
</code>```

In addition you can specify more complex rules on how to create the variables:

```<code>app()->bind(D::class, function ($app) {
       $d = new D();
       $d->setValueOfSomething($app->make(AnotherClass::class));
       return $d;
});
</code>```

Testing

That's one advantage of dependency injection over manual creation of things. Another is unit testing:

```<code>    public function testSomeFunctionOfC() {
        $this->app->bind(D::class, function () {
               $dMock = $this->createMock(D::class);
        });
        $c = make(C::class);
    }
</code>```

Now when you create C the class D will be the mocked class instead which you can ensure works according to your specification.

Body:
I'm using a Repository pattern in my Laravel project. This pattern is not really explained in the official documentation, except for this snippet:

You may type-hint a repository defined by your application in a controller's constructor. The repository will automatically be resolved and injected into the class.

This is my code, in accordance with the documentation:

class CategoriesController extends Controller
{
    protected $repo;

    public function __construct(CategoriesRepository $repo)
    {
        $this->repo = $repo;
    }

I've type-hinted the CategoriesRepository so it gets automatically loaded by the Service Container.

However, if I directly create a new instance of the CategoriesController class (without using the Service Container), I have to specify that I need a new instance of the CategoriesRepository too, like this:

$example = new CategoriesController(new CategoriesRepository());

Now, let's suppose I write the following code.

class CategoriesController extends Controller
{
    protected $repo;

    public function __construct()
    {
        $this->repo = new CategoriesRepository();
    }

This way, I don't have to load the class through the Service Container, nor call it by passing a new instance of CategoriesRepository as the argument, because it's automatically created inside of the constructor.

So, my question is: would this be bad practice? What's the difference between type-hinting as a parameter and creating a new instance inside of the constructor?

Body:
Here's the beauty of dependency injection:

Complex initialization

class MyController {

     public function __construct(A $a) { }
}

class A {
     public function __construct(B $b) { }
}
class B {
     public function __construct(C $c) { }
}

class C {
     public function __construct(D $d) { }
}
class D {
     public function __construct() { }
}

Now you can ask laravel to create that class for you e.g:

$controller = make(MyController::class);

or you can do:

$controller = new MyController(new A(new B(new C(new D())))));

In addition you can specify more complex rules on how to create the variables:

app()->bind(D::class, function ($app) {
       $d = new D();
       $d->setValueOfSomething($app->make(AnotherClass::class));
       return $d;
});

Testing

That's one advantage of dependency injection over manual creation of things. Another is unit testing:

    public function testSomeFunctionOfC() {
        $this->app->bind(D::class, function () {
               $dMock = $this->createMock(D::class);
        });
        $c = make(C::class);
    }

Now when you create C the class D will be the mocked class instead which you can ensure works according to your specification.


问:
Should I invalidate timer when my application is suspended or in background?
I have scheduler that fetch user profile data every 15 seconds.

```<code>class ProfileScheduler: NSObject {

    private var _timer: Timer?

    func start() {
        _timer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(self.fetchProfile), userInfo: nil, repeats: true)
    }

    func fetchProfile() {
       print("Update........")
       ProfileManager.getProfileData()
    }

}
</code>```

Should I invalidate Timer each time my application in (Suspended, Background) mode? And restore it when app become (Active).

答:
Should I invalidate Timer each time my application in (Suspended, Background) mode?

Yes. See What to do When Your App is Interrupted Temporarily, which explains that you should stop timers and other periodic tasks. Timers need an active run loop to work, so you should stop any timers when your app becomes inactive, and then restart them when it becomes active again.

Body:
I have scheduler that fetch user profile data every 15 seconds.

class ProfileScheduler: NSObject {

    private var _timer: Timer?

    func start() {
        _timer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(self.fetchProfile), userInfo: nil, repeats: true)
    }

    func fetchProfile() {
       print("Update........")
       ProfileManager.getProfileData()
    }

}

Should I invalidate Timer each time my application in (Suspended, Background) mode? And restore it when app become (Active).


问:
Mailboxer: creating link to new conversation on a product page
I am working on a marketplace.
I have a page with all the products.

I want to create a link on each of this product, to allow user to send message to the seller, creating a new conversation.

I am thinking about creating a link with that:

```<code><%= link_to "Contactar", new_conversation_path %>
</code>```

But can i put in this link the recipient directly ?

If yes, what should i change in the conversation_controller ?

```<code>def new
  recipients = Product.where(user: params[:user_id])
end

def create
  receipt = current_user.send_message(recipient, params[:body], params[:subject])
  redirect_to conversation_path(receipt.conversation)
end
</code>```

答:
Here is what i finally written:

On my product listing

```<code><%= link_to "Contact", new_conversation_path(recipient_id: service.user.id) %>
</code>```

In the conversations_controller:

```<code>def new

@recipient = params[:recipient_id]
end

def create
receipt = current_user.send_message(@recipient, params[:body],     params[:subject])
redirect_to conversation_path(receipt.conversation)
end
</code>```

So now on the conversation new page, the url show: /conversations/new?recipient_id=

thanks @Pavan

Body:
I am working on a marketplace.
I have a page with all the products.

I want to create a link on each of this product, to allow user to send message to the seller, creating a new conversation.

I am thinking about creating a link with that:

<%= link_to "Contactar", new_conversation_path %>

But can i put in this link the recipient directly ?

If yes, what should i change in the conversation_controller ?

def new
  recipients = Product.where(user: params[:user_id])
end

def create
  receipt = current_user.send_message(recipient, params[:body], params[:subject])
  redirect_to conversation_path(receipt.conversation)
end

Body:
Here is what i finally written:

On my product listing

<%= link_to "Contact", new_conversation_path(recipient_id: service.user.id) %>

In the conversations_controller:

def new

@recipient = params[:recipient_id]
end

def create
receipt = current_user.send_message(@recipient, params[:body],     params[:subject])
redirect_to conversation_path(receipt.conversation)
end

So now on the conversation new page, the url show: /conversations/new?recipient_id=

thanks @Pavan


问:
How Do I Combine Multiple SQL Queries?
I'm having some trouble figuring out any way to combine two SQL queries into a single one that expresses some greater idea.

For example, let's say that I have query A, and query B. Query A returns the total number of hours worked. Query B returns the total number of hours that were available for workers to work. Each one of these queries returns a single column with a single row.

What I really want, though, is essentially query A over query B. I want to know the percentage of capacity that was worked.

I know how to write query A and B independently, but my problem comes when I try to figure out how to use those prewritten queries to come up with a new SQL query that uses them together. I know that, on a higher level, like say in a report, I could just call both queries and then divide them, but I'd rather encompass it all into a single SQL query.

What I'm looking for is a general idea on how to combine these queries using SQL.

Thanks!

答:
You can query the queries:</p>

```<code>SELECT
  a.ID
  a.HoursWorked/b.HoursAvailable AS UsedWork
FROM
  ( SELECT ID, HoursWorked FROM Somewhere ) a
INNER JOIN
  ( SELECT ID, HoursAvailable FROM SomewhereElse ) b
ON
  a.ID =  b.ID
</code>```

Title: How Do I Combine Multiple SQL Queries?

Body:
You can query the queries:

SELECT
  a.ID
  a.HoursWorked/b.HoursAvailable AS UsedWork
FROM
  ( SELECT ID, HoursWorked FROM Somewhere ) a
INNER JOIN
  ( SELECT ID, HoursAvailable FROM SomewhereElse ) b
ON
  a.ID =  b.ID


问:
Setting a variable equal to the data attribute of the current selected link
I need to set the variable current equal to the data attribute for the link which has been selected how can I do this. I know there are easier ways of doing what im trying to do but I need to do it this way.

I tried to create it but I can't do it.

$(".links").click(function(){
  var current = $(this).getAttribute("data-cat");
  $(current).addClass('hide');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul{
  list-style-type: none;
}

ul li{
  display: inline-block;
}

ul li a{
  font-size: 20px;
  padding: 10px;
  background-color: yellow;
}

.change{
  background-color: red;
}

.hide{
  display: none;
}

.print{
  height: 100px;
  width: 100px;
  background-color: blue;
}</code>```

link1

link2

link3

```

答:
Use $(this).attr("data-cat"); to get the attribute and $('.'+current).addClass('hide'); to use the variable as class selector

$(".links").click(function(){
  var current = $(this).attr("data-cat");
  console.log(current)
  $('.'+current).addClass('hide');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul{
  list-style-type: none;
}

ul li{
  display: inline-block;
}

ul li a{
  font-size: 20px;
  padding: 10px;
  background-color: yellow;
}

.change{
  background-color: red;
}

.hide{
  display: none;
}

.print{
  height: 100px;
  width: 100px;
  background-color: blue;
}</code>```

link1

link2

link3

```

Body:
I need to set the variable current equal to the data attribute for the link which has been selected how can I do this. I know there are easier ways of doing what im trying to do but I need to do it this way.

I tried to create it but I can't do it.

$(".links").click(function(){
  var current = $(this).getAttribute("data-cat");
  $(current).addClass('hide');
});

ul{
  list-style-type: none;
}

ul li{
  display: inline-block;
}

ul li a{
  font-size: 20px;
  padding: 10px;
  background-color: yellow;
}

.change{
  background-color: red;
}

.hide{
  display: none;
}

.print{
  height: 100px;
  width: 100px;
  background-color: blue;
}

link1

link2

link3

Body:
Use $(this).attr("data-cat"); to get the attribute and $('.'+current).addClass('hide'); to use the variable as class selector

$(".links").click(function(){
  var current = $(this).attr("data-cat");
  console.log(current)
  $('.'+current).addClass('hide');
});

ul{
  list-style-type: none;
}

ul li{
  display: inline-block;
}

ul li a{
  font-size: 20px;
  padding: 10px;
  background-color: yellow;
}

.change{
  background-color: red;
}

.hide{
  display: none;
}

.print{
  height: 100px;
  width: 100px;
  background-color: blue;
}

<ul>
  <li><a id="hi" class="links" data-cat="print" href="#">link1</a></li>
  <li><a class="links" data-cat="porfolio" href="#">link2</a></li>
  <li><a class="links" data-cat="print" href="#">link3</a></li>
</ul>

<div class="print">

</div>

<div class="porfolio">

</div>

<div class="print">

</div>

<script
  src="https://code.jquery.com/jquery-3.2.1.js"
  integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
  crossorigin="anonymous"></script>


问:
HTML form filled with post parameter string. String getting truncated
I have an html form (form2) with variable called cat:

```<code><input type="text" name="cat" value=<?php echo $_POST['cat']; ?>><br> <b>
</code>```

File A ---> File B

File A gets input from form1 and posts to File B, which has a form called form2.

This form gets the POST variables from form1, and uses them, but also takes in some additional input. Cat, which I can see bc it's input type is text is truncated for some reason. Even though cat is normally only 1400 characters, it is truncated down to 164 for some reason.
Why/How do I fix this?

答:
You need to enclose value's value in quotes, as such:

```<code>value=<?php echo $_POST['cat']; ?>
</code>```

to

```<code>value="<?php echo htmlentities($_POST['cat']); ?>"
</code>```

Body:
I have an html form (form2) with variable called cat:

<input type="text" name="cat" value=<?php echo $_POST['cat']; ?>>

File A ---> File B

File A gets input from form1 and posts to File B, which has a form called form2.

This form gets the POST variables from form1, and uses them, but also takes in some additional input. Cat, which I can see bc it's input type is text is truncated for some reason. Even though cat is normally only 1400 characters, it is truncated down to 164 for some reason.
Why/How do I fix this?

Body:
You need to enclose value's value in quotes, as such:

value=<?php echo $_POST['cat']; ?>

to

value="<?php echo htmlentities($_POST['cat']); ?>"


问:
How to fix "@types/node/index.d.ts is not a module"?
I have installed node type definitions using the following command

```<code>npm install --save-dev @types/node
</code>```

After that, when I try to import the node type definitions using the following statement

```<code>import { Process } from '@types/node';
</code>```

or

```<code>import { Process } from 'node';
</code>```

I get the following error

```<code>[ts] File '<root_path>/node_modules/@types/node/index.d.ts' is not a module.
</code>```

I am sure there is something very basic that I am missing here but I cannot figure out.

Few more things

I am using Windows 8

I am using Visual Studio Code

Here is how my tsconfig.json looks

```<code>{
  "compilerOptions": {
    "target": "es2015",
    "module": "commonjs",
    "outDir": "lib",
    "typeRoots": [
        "node_modules/@typings"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}
</code>```

And here is how my webpackconfig.js looks

```<code>var path = require('path');

module.exports = {
  entry: './ts/handler.ts',
  target: 'node',
  module: {
    loaders: [
      { test: /\.ts(x?)$/, loader: 'ts-loader' },
      { test: /\.json$/, loader: 'json-loader' }
    ]
  },
  resolve: {
    extensions: ['.ts', '.js', '.tsx', '.jsx']
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, '.webpack'),
    filename: 'handler.js'
  },
};
</code>```

答:
Instead of using:

```<code>import { Process } from '@types/node';
</code>```

You need to change your tsconfig.json:

```<code>{
  "compilerOptions": {
    ...
    "typeRoots": ["node_modules/@types"]
  }
}
</code>```

After doing that the process variable becomes available as a global.

Sometimes you will need to import from a Node.js module like for example the fs module. You can do:

```<code>import * as fs from "fs";
</code>```

You don't need to import fs from "node" or from "@types/node".

You can learn more here.

Body:
I have installed node type definitions using the following command

npm install --save-dev @types/node

After that, when I try to import the node type definitions using the following statement

import { Process } from '@types/node';

or

import { Process } from 'node';

I get the following error

[ts] File '<root_path>/node_modules/@types/node/index.d.ts' is not a module.

I am sure there is something very basic that I am missing here but I cannot figure out.

Few more things

I am using Windows 8

I am using Visual Studio Code

Here is how my tsconfig.json looks

{
  "compilerOptions": {
    "target": "es2015",
    "module": "commonjs",
    "outDir": "lib",
    "typeRoots": [
        "node_modules/@typings"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

And here is how my webpackconfig.js looks

var path = require('path');

module.exports = {
  entry: './ts/handler.ts',
  target: 'node',
  module: {
    loaders: [
      { test: /\.ts(x?)$/, loader: 'ts-loader' },
      { test: /\.json$/, loader: 'json-loader' }
    ]
  },
  resolve: {
    extensions: ['.ts', '.js', '.tsx', '.jsx']
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, '.webpack'),
    filename: 'handler.js'
  },
};

Body:
Instead of using:

import { Process } from '@types/node';

You need to change your tsconfig.json:

{
  "compilerOptions": {
    ...
    "typeRoots": ["node_modules/@types"]
  }
}

After doing that the process variable becomes available as a global.

Sometimes you will need to import from a Node.js module like for example the fs module. You can do:

import * as fs from "fs";

You don't need to import fs from "node" or from "@types/node".

You can learn more here.