问:
Python 3.5 multiprocessing pool and queue don't work
I encounter a multiprocessing problem. The code is included below. The code can execute as expected, but when uncommenting self.queue = multiprocessing.Queue(), this program will exit immediately and it seems that the subprocess can't be started successfully.

I don't know what happened. Could someone help me out? Many Thanks!

```<code>import multiprocessing
import time

class Test:
    def __init__(self):
        self.pool = multiprocessing.Pool(1)
        #self.queue = multiprocessing.Queue()

    def subprocess(self):
        for i in range(10):
            print("Running")
            time.sleep(1)
        print("Subprocess Completed")

    def start(self):
        self.pool.apply_async(func=self.subprocess)
        print("Subprocess has been started")
        self.pool.close()
        self.pool.join()

    def __getstate__(self):
        self_dict = self.__dict__.copy()
        del self_dict['pool']
        return self_dict

    def __setstate__(self, state):
        self.__dict__.update(state)

if __name__ == '__main__':
    test = Test()
    test.start()
</code>```

答:
you use apply_async, which returns immediately. so you should wait for the result somewhere

under the hood, python will pickle the function to be executed to the child process. but self.process as a method is not pickle-able here (because of the self.pool attribute, see comment by ShadowRanger below).

```<code>import multiprocessing
import time

def subprocess():   # is a plain old (pickle-able) function
    for i in range(10):
        print("Running")
        time.sleep(1)
    print("Subprocess Completed")
    return True

class Test:
    def __init__(self):
        self.pool = multiprocessing.Pool(1)

    def start(self):
        result = self.pool.apply_async(subprocess)
        print("Subprocess has been started")
        result.get()    # wait for the end of subprocess
        self.pool.close()
        self.pool.join()

if __name__ == '__main__':
    test = Test()
    test.start()
</code>```

Body:
I encounter a multiprocessing problem. The code is included below. The code can execute as expected, but when uncommenting self.queue = multiprocessing.Queue(), this program will exit immediately and it seems that the subprocess can't be started successfully.

I don't know what happened. Could someone help me out? Many Thanks!

import multiprocessing
import time

class Test:
    def __init__(self):
        self.pool = multiprocessing.Pool(1)
        #self.queue = multiprocessing.Queue()

    def subprocess(self):
        for i in range(10):
            print("Running")
            time.sleep(1)
        print("Subprocess Completed")

    def start(self):
        self.pool.apply_async(func=self.subprocess)
        print("Subprocess has been started")
        self.pool.close()
        self.pool.join()

    def __getstate__(self):
        self_dict = self.__dict__.copy()
        del self_dict['pool']
        return self_dict

    def __setstate__(self, state):
        self.__dict__.update(state)

if __name__ == '__main__':
    test = Test()
    test.start()

Body:
you use apply_async, which returns immediately. so you should wait for the result somewhere

under the hood, python will pickle the function to be executed to the child process. but self.process as a method is not pickle-able here (because of the self.pool attribute, see comment by ShadowRanger below).

import multiprocessing
import time

def subprocess():   # is a plain old (pickle-able) function
    for i in range(10):
        print("Running")
        time.sleep(1)
    print("Subprocess Completed")
    return True

class Test:
    def __init__(self):
        self.pool = multiprocessing.Pool(1)

    def start(self):
        result = self.pool.apply_async(subprocess)
        print("Subprocess has been started")
        result.get()    # wait for the end of subprocess
        self.pool.close()
        self.pool.join()

if __name__ == '__main__':
    test = Test()
    test.start()


来源: stackexchange

问:
not malicious hidden link
hey i'm using a jquery plugin Fancybox, which is a Lightbox type plugin.

This plugin can only be triggered by clicking a link. I want to show the plugin on PostBack.

 I have no problem doing this programmatically.
My concerns are purely from an SEO perspective. How can I add a hidden link that wouldn't be identified as trying to cheat Google and other search engines.

答:
Simple answer is don't. Just add the no follow tag to the link e.g. </p>

```<code><a href="mylink" rel="nofollow">my link</a>
</code>```

<p>Goggle now wont follow it / it wont effect your SEO, also I would add the location to the robots .txt and make sure its not indexed. </p>

ContentLicense: CC BY-SA 2.5

Title: not malicious hidden link

Body:
Simple answer is don't. Just add the no follow tag to the link e.g.

<a href="mylink" rel="nofollow">my link</a>

Goggle now wont follow it / it wont effect your SEO, also I would add the location to the robots .txt and make sure its not indexed.


问:
Django Models - How to store fields in a dict
I have a fairly simple user-model perfectly working.
In order to reduce code redundancy, I try to store fields inside a dictory for reasons you can easily guess.

Example:

```<code>def get_social_token(self,social_net=""):
   return self.social_dict[social_net]["token"]
</code>```

If I don't do such a structure I must do some "if/then ... elif... else".
And of course I need to modify my code whenever I decide to add a new social network to my app.

I have tried two different approaches, both of them give me the same result:

No error

No field is actually detected and created in the DB

I'd like to mention that if I use a "conventional manner" to implement this behaviour such as:

twitter_social_token = EncryptedCharField(max_length=500, default='', blank=True, null=True)

It perfectly works, so it comes from the use of a dictionary.

Any idea to solve this ?
Btw. I would prefer avoiding using a new model and a foreign key... Only a One-to-One association, I would prefer not having to perform any "join" or select in another table...

Bellow, you'll find the two attempts I made which doesn't work (and I don't know why):

First attempt:

```<code>social_fields = {
    'twitter' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
    'facebook' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
    'gplus' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
    'linkedin' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
}
</code>```

Second attempt:

```<code>social_tokens = dict()

social_tokens["twitter"] = dict()
social_tokens["facebook"] = dict()
social_tokens["linkedin"] = dict()
social_tokens["gplus"] = dict()

social_tokens["twitter"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["twitter"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_tokens["facebook"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["facebook"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_tokens["linkedin"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["linkedin"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_tokens["gplus"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["gplus"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
</code>```

Thanks for the help dear friends,

Jonathan

答:
It would definetely works, however as you seen I use Encrypted Fields in order to keep secure my user's tokens and secret_tokens.

I hope this not a bad thing to do or some kind of anti-pattern.
Feel free to share a better way doing this.

I just found a workaround which actually works exactely the way I wanted, even if it's not super efficiant from my point of view.

Here is you access the data:

```<code>from application.models import *
tmp_user = CustomUser.objects.get(username="random_username")

print (getattr(tmp_user, tmp_user.social_fields["twitter"]["token"]))
>>> e72e16c7e42f292c6912e7710c838347ae178b4a ### This token is a fake !
</code>```

Here is how managed to do this:

```<code>twitter_token          = EncryptedCharField(max_length=500, default='', blank=True, null=True)
twitter_token_secret   = EncryptedCharField(max_length=500, default='', blank=True, null=True)

facebook_token         = EncryptedCharField(max_length=500, default='', blank=True, null=True)
facebook_token_secret  = EncryptedCharField(max_length=500, default='', blank=True, null=True)

gplus_token            = EncryptedCharField(max_length=500, default='', blank=True, null=True)
gplus_token_secret     = EncryptedCharField(max_length=500, default='', blank=True, null=True)

linkedin_token         = EncryptedCharField(max_length=500, default='', blank=True, null=True)
linkedin_token_secret  = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_fields = {
    'twitter' : {
        'token'  : "twitter_token",
        'secret' : "twitter_token_secret"
    },
    'facebook' : {
        'token'  : "facebook_token",
        'secret' : "facebook_token_secret"
    },
    'gplus' : {
        'token'  : "gplus_token",
        'secret' : "gplus_token_secret"
    },
    'linkedin' : {
        'token'  : "linkedin_token",
        'secret' : "linkedin_token_secret"
    },
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a fairly simple user-model perfectly working.
In order to reduce code redundancy, I try to store fields inside a dictory for reasons you can easily guess.

Example:

def get_social_token(self,social_net=""):
   return self.social_dict[social_net]["token"]

If I don't do such a structure I must do some "if/then ... elif... else".
And of course I need to modify my code whenever I decide to add a new social network to my app.

I have tried two different approaches, both of them give me the same result:

No error

No field is actually detected and created in the DB

I'd like to mention that if I use a "conventional manner" to implement this behaviour such as:

twitter_social_token = EncryptedCharField(max_length=500, default='', blank=True, null=True)

It perfectly works, so it comes from the use of a dictionary.

Any idea to solve this ?
Btw. I would prefer avoiding using a new model and a foreign key... Only a One-to-One association, I would prefer not having to perform any "join" or select in another table...

Bellow, you'll find the two attempts I made which doesn't work (and I don't know why):

First attempt:

social_fields = {
    'twitter' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
    'facebook' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
    'gplus' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
    'linkedin' : {
        'token'  : EncryptedCharField(max_length=500, default='', blank=True, null=True),
        'secret' : EncryptedCharField(max_length=500, default='', blank=True, null=True)
    },
}

Second attempt:

social_tokens = dict()

social_tokens["twitter"] = dict()
social_tokens["facebook"] = dict()
social_tokens["linkedin"] = dict()
social_tokens["gplus"] = dict()

social_tokens["twitter"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["twitter"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_tokens["facebook"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["facebook"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_tokens["linkedin"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["linkedin"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_tokens["gplus"]["token"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)
social_tokens["gplus"]["secret"] = EncryptedCharField(max_length=500, default='', blank=True, null=True)

Thanks for the help dear friends,

Jonathan

Body:
It would definetely works, however as you seen I use Encrypted Fields in order to keep secure my user's tokens and secret_tokens.

I hope this not a bad thing to do or some kind of anti-pattern.
Feel free to share a better way doing this.

I just found a workaround which actually works exactely the way I wanted, even if it's not super efficiant from my point of view.

Here is you access the data:

from application.models import *
tmp_user = CustomUser.objects.get(username="random_username")

print (getattr(tmp_user, tmp_user.social_fields["twitter"]["token"]))
>>> e72e16c7e42f292c6912e7710c838347ae178b4a ### This token is a fake !

Here is how managed to do this:

twitter_token          = EncryptedCharField(max_length=500, default='', blank=True, null=True)
twitter_token_secret   = EncryptedCharField(max_length=500, default='', blank=True, null=True)

facebook_token         = EncryptedCharField(max_length=500, default='', blank=True, null=True)
facebook_token_secret  = EncryptedCharField(max_length=500, default='', blank=True, null=True)

gplus_token            = EncryptedCharField(max_length=500, default='', blank=True, null=True)
gplus_token_secret     = EncryptedCharField(max_length=500, default='', blank=True, null=True)

linkedin_token         = EncryptedCharField(max_length=500, default='', blank=True, null=True)
linkedin_token_secret  = EncryptedCharField(max_length=500, default='', blank=True, null=True)

social_fields = {
    'twitter' : {
        'token'  : "twitter_token",
        'secret' : "twitter_token_secret"
    },
    'facebook' : {
        'token'  : "facebook_token",
        'secret' : "facebook_token_secret"
    },
    'gplus' : {
        'token'  : "gplus_token",
        'secret' : "gplus_token_secret"
    },
    'linkedin' : {
        'token'  : "linkedin_token",
        'secret' : "linkedin_token_secret"
    },
}


问:
"Entity name must be unique in a persistence unit"
I'm new to GlassFish server and I'm experiencing this problem. I first imported a template project (that uses JPA) into NetBeans, which was working fine. Then, since I wanted to modify the template, I created a copy of the project, closed the original one in NetBeans, undeployed the first project and then imported the new copied project into NetBeans. I changed the package name and the name of the persistence unit. However when I try to run the new project I get the error

```<code>Entity name must be unique in a persistence unit. Entity name [ToDoItem] is used for the entity classes [package1.ToDoItem] and [package2.ToDoItem]
</code>```

How is this possible? The original project no longer exists in NetBeans, I explicitly undeployed it from GlassFish by using the asadmin undeploy command, and I even tried to remove and reinstall GlassFish, but nothing changes.

My persistence.xml looks like this:

```<code><persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="myserver-unit" transaction-type="JTA">
<jta-data-source/>
<properties>
  <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
  <property name="javax.persistence.schema-generation.create-source" value="metadata-then-script"/>
  <property name="javax.persistence.schema-generation.drop-source" value="metadata-then-script"/>
  <property name="javax.persistence.schema-generation.create-script-source" value="create-script.sql"/>
  <property name="javax.persistence.schema-generation.drop-script-source" value="drop-script.sql"/>
  <property name="javax.persistence.sql-load-script-source" value="load-script.sql"/>
  <property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</code>```

The only thing I changed is the name of the persistence unit.

答:
This happened to me and what worked for me was a clean project and removing the osgi-cache directory in the domain folder; it seems the built packages stay in the cache and cause naming conflicts.

Edit: a bit of clarification, I managed to get the same error on the clean install of glassfish because i had the old .class files in the project even though the source didn't exist and they ended up on the clean domain anyway.

Body:
I'm new to GlassFish server and I'm experiencing this problem. I first imported a template project (that uses JPA) into NetBeans, which was working fine. Then, since I wanted to modify the template, I created a copy of the project, closed the original one in NetBeans, undeployed the first project and then imported the new copied project into NetBeans. I changed the package name and the name of the persistence unit. However when I try to run the new project I get the error

Entity name must be unique in a persistence unit. Entity name [ToDoItem] is used for the entity classes [package1.ToDoItem] and [package2.ToDoItem]

How is this possible? The original project no longer exists in NetBeans, I explicitly undeployed it from GlassFish by using the asadmin undeploy command, and I even tried to remove and reinstall GlassFish, but nothing changes.

My persistence.xml looks like this:

<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="myserver-unit" transaction-type="JTA">
<jta-data-source/>
<properties>
  <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
  <property name="javax.persistence.schema-generation.create-source" value="metadata-then-script"/>
  <property name="javax.persistence.schema-generation.drop-source" value="metadata-then-script"/>
  <property name="javax.persistence.schema-generation.create-script-source" value="create-script.sql"/>
  <property name="javax.persistence.schema-generation.drop-script-source" value="drop-script.sql"/>
  <property name="javax.persistence.sql-load-script-source" value="load-script.sql"/>
  <property name="eclipselink.logging.level" value="FINEST"/>
</properties>

The only thing I changed is the name of the persistence unit.


问:
Query a chain of one to many and many to one
I currently have 3 tables roughly described as the following SQLAlchemy mapping:

```<code>class Task(BASE):
    __tablename__ = 'tasks'
    id = Column(Integer, primary_key=True)

    service_id = Column(Integer, ForeignKey('services.id'))
    service = relationship('Service', back_populates="tasks")

    updates = relationship("TaskUpdate")

class TaskUpdate(BASE):
    __tablename__ = 'task_updates'

    id = Column(Integer, primary_key=True)
    external_status = Column(String(32))
    external_updated_at = Column(DateTime(timezone=True))

    task_id = Column(Integer, ForeignKey('tasks.id'))
    task = relationship('Task', back_populates="updates")

class Service(BASE):
    __tablename__ = 'services'

    id = Column(Integer, primary_key=True)

    client_id = Column(Integer, ForeignKey('clients.id'))
    client = relationship('Client', back_populates='services')
</code>```

So I have one-to-many relationship from Task to TaskUpdates and a many-to-one from Task to Service.

I'm trying to create a query to get all Tasks where their latest TaskUpdate (by timestamp) has an external_status that is "New", or "Open."

Here's what I got:

```<code>sub = SESSION.query(
        TaskUpdate.task_id,
        TaskUpdate.external_status.label('last_status'),
        func.max(TaskUpdate.external_updated_at).label('last_update')
        ).group_by(TaskUpdate.task_id
        ).subquery()
tasks = SESSION.query(Task
        ).join(Service
        ).filter(Service.client_id == client_id
        ).join((sub, sub.c.task_id == Task.id)
        ).filter(sub.c.last_status.in_(['New', 'Open']))
</code>```

When I run this, I get this error:

```<code>ProgrammingError: (psycopg2.ProgrammingError) column "task_updates.external_status" must appear in the GROUP BY clause or be used in an aggregate function
</code>```

I'd appreciate any help you can give. This is important.

Update 1 (this is the SQL that ended up working (as far as I can tell, I can't test the frontend until I get this working in SQLAlchemy though:

```<code>SELECT t.* FROM (
  SELECT DISTINCT ON (task_id) task_id, external_status
  FROM task_updates
  ORDER BY task_id, external_updated_at DESC NULLS LAST) tu
JOIN tasks t ON t.id = tu.task_id
JOIN services s ON s.id = t.service_id
WHERE s.client_id = '" + str(client_id) + "'
AND tu.external_status IN ('New', 'Open');
</code>```

Here's my conversion attempt, still not working:

```<code>sub = SESSION.query(TaskUpdate).distinct(TaskUpdate.task_id).order_by(TaskUpdate.task_id.desc().nullslast(), TaskUpdate.external_updated_at.desc().nullslast()).subquery()
tasks = SESSION.query(Task).join(Service).join(sub.c.task_id==Task.id).filter(TaskUpdate.external_status.in_(['New', 'Open']))
</code>```

Update 2: The query I have below works, but when I do .count() it returns the total number of TaskUpdates, not tasks and I suspect the query will need to be redone a different way, unless someone knows a way to handle this?

答:
On way to do this:

```<code>SELECT t.*
FROM  (
   SELECT DISTINCT ON (task_id)
          task_id, external_status
   FROM   task_updates
   ORDER  BY task_id, external_updated_at DESC NULLS LAST
   ) tu
JOIN   tasks t ON t.id = tu.task_id
WHERE  tu.external_status IN ('New', 'Open');
</code>```

First get the last row per task, then only pick tasks wit the right external_status.

Detailed explanation for DISTINCT ON:

Select first row in each GROUP BY group?

If you have many row per task, there are faster query techniques:

Optimize GROUP BY query to retrieve latest record per user

Body:
I currently have 3 tables roughly described as the following SQLAlchemy mapping:

class Task(BASE):
    __tablename__ = 'tasks'
    id = Column(Integer, primary_key=True)

    service_id = Column(Integer, ForeignKey('services.id'))
    service = relationship('Service', back_populates="tasks")

    updates = relationship("TaskUpdate")

class TaskUpdate(BASE):
    __tablename__ = 'task_updates'

    id = Column(Integer, primary_key=True)
    external_status = Column(String(32))
    external_updated_at = Column(DateTime(timezone=True))

    task_id = Column(Integer, ForeignKey('tasks.id'))
    task = relationship('Task', back_populates="updates")

class Service(BASE):
    __tablename__ = 'services'

    id = Column(Integer, primary_key=True)

    client_id = Column(Integer, ForeignKey('clients.id'))
    client = relationship('Client', back_populates='services')

So I have one-to-many relationship from Task to TaskUpdates and a many-to-one from Task to Service.

I'm trying to create a query to get all Tasks where their latest TaskUpdate (by timestamp) has an external_status that is "New", or "Open."

Here's what I got:

sub = SESSION.query(
        TaskUpdate.task_id,
        TaskUpdate.external_status.label('last_status'),
        func.max(TaskUpdate.external_updated_at).label('last_update')
        ).group_by(TaskUpdate.task_id
        ).subquery()
tasks = SESSION.query(Task
        ).join(Service
        ).filter(Service.client_id == client_id
        ).join((sub, sub.c.task_id == Task.id)
        ).filter(sub.c.last_status.in_(['New', 'Open']))

When I run this, I get this error:

ProgrammingError: (psycopg2.ProgrammingError) column "task_updates.external_status" must appear in the GROUP BY clause or be used in an aggregate function

I'd appreciate any help you can give. This is important.

Update 1 (this is the SQL that ended up working (as far as I can tell, I can't test the frontend until I get this working in SQLAlchemy though:

SELECT t.* FROM (
  SELECT DISTINCT ON (task_id) task_id, external_status
  FROM task_updates
  ORDER BY task_id, external_updated_at DESC NULLS LAST) tu
JOIN tasks t ON t.id = tu.task_id
JOIN services s ON s.id = t.service_id
WHERE s.client_id = '" + str(client_id) + "'
AND tu.external_status IN ('New', 'Open');

Here's my conversion attempt, still not working:

sub = SESSION.query(TaskUpdate).distinct(TaskUpdate.task_id).order_by(TaskUpdate.task_id.desc().nullslast(), TaskUpdate.external_updated_at.desc().nullslast()).subquery()
tasks = SESSION.query(Task).join(Service).join(sub.c.task_id==Task.id).filter(TaskUpdate.external_status.in_(['New', 'Open']))

Update 2: The query I have below works, but when I do .count() it returns the total number of TaskUpdates, not tasks and I suspect the query will need to be redone a different way, unless someone knows a way to handle this?

Body:
On way to do this:

SELECT t.*
FROM  (
   SELECT DISTINCT ON (task_id)
          task_id, external_status
   FROM   task_updates
   ORDER  BY task_id, external_updated_at DESC NULLS LAST
   ) tu
JOIN   tasks t ON t.id = tu.task_id
WHERE  tu.external_status IN ('New', 'Open');

First get the last row per task, then only pick tasks wit the right external_status.

Detailed explanation for DISTINCT ON:

Select first row in each GROUP BY group?

If you have many row per task, there are faster query techniques:

Optimize GROUP BY query to retrieve latest record per user


问:
Retrofit Convert Post to Get request
i have post request which i want to convert to get request any way i can do . as of now i know is i have to change all stuff like

```<code> @POST("apiname")
Call<ResponseBody> getBasic(@Body DataRequest data);
</code>```

and DataRequest is having say 5 params . now

```<code> @GET("apiname")
Call<ResponseBody> getBasic(
        @Query("one") String one,
        @Query("two") String two,
        @Query("three") String three)..;
</code>```

so in this way i have to add number of variables to  @Query but problem is if its 10 then i have to add 10 time . is any other workaround where i can convert POST to GET

any way i can pass POJO model and it converted to get request format

答:
You can use @QueryMap to pass multiple query params dynamically. So in your case:

```<code>@GET("apiname")
Call<ResponseBody> getBasic(@QueryMap Map<String, String> options);
</code>```

You can then define a method in your pojo to convert it to a Map<String, String>

Title: Retrofit Convert Post to Get request

Body:
i have post request which i want to convert to get request any way i can do . as of now i know is i have to change all stuff like

 @POST("apiname")
Call<ResponseBody> getBasic(@Body DataRequest data);

and DataRequest is having say 5 params . now

 @GET("apiname")
Call<ResponseBody> getBasic(
        @Query("one") String one,
        @Query("two") String two,
        @Query("three") String three)..;

so in this way i have to add number of variables to  @Query but problem is if its 10 then i have to add 10 time . is any other workaround where i can convert POST to GET

any way i can pass POJO model and it converted to get request format

Body:
You can use @QueryMap to pass multiple query params dynamically. So in your case:

@GET("apiname")
Call<ResponseBody> getBasic(@QueryMap Map<String, String> options);

You can then define a method in your pojo to convert it to a Map<String, String>


问:
Python for Loop - how to save every iteration under different variables
I have a for loop, used to mark circles under Hough function from OpenCV:

```<code>   for i in circles[0,:]:
        x=i[0]
        y=i[1]
        cv2.circle(cimg,(i[o],i[1]),i[2],(0,255,0),2)
        cv2.circle(cimg,(i[o],i[1]),2,(0,0,255),3)
        text='x='+str(x)
        text2='y='+str(y)
        cv2.puttext(img, text,(10,90),font,1,(0,0,255),cv2.line_aa)
</code>```

The thing i want to do is to save every x-y coords of the circle under different variables, like a=x1, b=y1 (for iteration 1) so i would be able to call a,b and use them later. Any ideas?

If i just print i[0] it will output just the x1 (first iteration for the first circle) and x2 (second iteration from the second circle), just like this:
22
42

Thanks!

答:
If you only want to assign each element in "elemente" to a different variable, list unpacking is all you need:</p>

```<code>a,b = elemente
</code>```

Body:
I have a for loop, used to mark circles under Hough function from OpenCV:

   for i in circles[0,:]:
        x=i[0]
        y=i[1]
        cv2.circle(cimg,(i[o],i[1]),i[2],(0,255,0),2)
        cv2.circle(cimg,(i[o],i[1]),2,(0,0,255),3)
        text='x='+str(x)
        text2='y='+str(y)
        cv2.puttext(img, text,(10,90),font,1,(0,0,255),cv2.line_aa)

The thing i want to do is to save every x-y coords of the circle under different variables, like a=x1, b=y1 (for iteration 1) so i would be able to call a,b and use them later. Any ideas?

If i just print i[0] it will output just the x1 (first iteration for the first circle) and x2 (second iteration from the second circle), just like this:
22
42

Thanks!

Body:
If you only want to assign each element in "elemente" to a different variable, list unpacking is all you need:

a,b = elemente


问:
Which is better: Several SQL queries or one sql data with lots of data?
I am making a quiz and I am expecting a lot of players for it. The quiz has a fixed number of questions.The quiz system can either fetch individual questions one by one from the MySql database and display it to the user. Or alternatively  I can fetch all the questions when he/she logs in and display them one by one. Can the second method significantly help in reducing the load on the server due to large number of SQL queries? Here I am talking about 500-600 users simultaneously playing the game.</p>

答: A well indexed database should have no problems at all with single queries, which is what I would prefer. Bonus: those small queries will remain in the server's query cache and thus be delivered way faster if requested again.</p>


问:
Is there a way of fixing a maximum value for an element in an array?
```<code>list = [5, 10, 20, 40, 50, 42, 35, 26, 18]
</code>```

So in this example, I don't want an element to exceed the value 40 and if it does, I want the element to have a value of 40, e.g. the element with the value 50 will become 40.

Body:
list = [5, 10, 20, 40, 50, 42, 35, 26, 18]

So in this example, I don't want an element to exceed the value 40 and if it does, I want the element to have a value of 40, e.g. the element with the value 50 will become 40.

Body:
If 40 is the max, you need the min from 40 and the element ;)

list = [5, 10, 20, 40, 50, 42, 35, 26, 18]
list.map{ |v| [40, v].min }
# => [5, 10, 20, 40, 40, 40, 35, 26, 18]


答:
As @ZdaR commented,</p>

```<code>output = []
elemente = [0, 1]
for x in elemente:
    output.append(x)

print(output)     # [0, 1]
print(output[0])  # 0
print(output[1])  # 1
</code>```

Title: Python for Loop - how to save every iteration under different variables

Body:
As @ZdaR commented,

output = []
elemente = [0, 1]
for x in elemente:
    output.append(x)

print(output)     # [0, 1]
print(output[0])  # 0
print(output[1])  # 1


问:
Regex matching and printing string issue

In Perl, I am trying to match three groups. Some groups have two question marks around them, others have one. I need to be able to distinguish between the two.

Sample Input:

The box is ?Red? in colour.
The box is ??green?? in colour.
```

<p><strong>Current Output:</strong></p>

<pre class="lang-none prettyprint-override"><code>The box isRedin colour.

The box is green in colour.
</code>```

Desired Output:

The box is Red in colour.

The box is green in colour.
```

<p>Here is what is almost working perfectly:</p>

<pre class="lang-perl prettyprint-override"><code>my $pattern_q  = '(.*\s?)[^\?]\?(\w.*)\?[^\?](.*)';
my $pattern_qq = '(.*\s?)\?\?(\w.*)\?\?(.*)';

if ( $line =~ /$pattern_q/ ) {
    print "\n" . $1 . $2 . $3 . "\n";
}

if ( $line =~ /$pattern_qq/ ) {
    print "\n" . $1 . $2 . $3 . "\n";
</code>```

When I get a match against $pattern_qq - it handles everything correctly, except for the \n at the end, which I can live with.

When I get a match against $pattern_q - It removes the spaces between the three groups, which I want to retain.

答:
Pure regex substitution example here.

Perl script code (may test it here):

```<code>#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @strings = (
    'The box is ?Red? in colour.',
    'The box is ??green?? in colour.'
);

local $" = "\n\t";

print "Before:\n\t @strings\n";

s/\?+(\w+)\?+/$1/ for @strings;

print "After:\n\t @strings\n";
</code>```

Body:
In Perl, I am trying to match three groups. Some groups have two question marks around them, others have one. I need to be able to distinguish between the two.

Sample Input:

The box is ?Red? in colour.
The box is ??green?? in colour.

Current Output:

The box isRedin colour.

The box is green in colour.

Desired Output:

The box is Red in colour.

The box is green in colour.

Here is what is almost working perfectly:

my $pattern_q  = '(.*\s?)[^\?]\?(\w.*)\?[^\?](.*)';
my $pattern_qq = '(.*\s?)\?\?(\w.*)\?\?(.*)';

if ( $line =~ /$pattern_q/ ) {
    print "\n" . $1 . $2 . $3 . "\n";
}

if ( $line =~ /$pattern_qq/ ) {
    print "\n" . $1 . $2 . $3 . "\n";

When I get a match against $pattern_qq - it handles everything correctly, except for the \n at the end, which I can live with.

When I get a match against $pattern_q - It removes the spaces between the three groups, which I want to retain.

Body:
Pure regex substitution example here.

Perl script code (may test it here):

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @strings = (
    'The box is ?Red? in colour.',
    'The box is ??green?? in colour.'
);

local $" = "\n\t";

print "Before:\n\t @strings\n";

s/\?+(\w+)\?+/$1/ for @strings;

print "After:\n\t @strings\n";


问:
Tag-it Autocomplete: Make li.tagit-new cover rest of ul.tagit
I tried to get the 'li.tagit-new input' to cover the full width of the rest of the parent ul.tagit with:

```<code>ul.tagit li {
    display:table-cell;
    white-space:nowrap;
    vertical-align:top;
    float: none;
}

ul.tagit li.tagit-new {
    width: 100%;
    border: 1px solid #ddd;
}
ul.tagit li.tagit-new input {
    width: 100%;
}
</code>```

It works fine if there is at least one tag. But not if there no tag:

http://jsfiddle.net/bus9dgx5/

答:
i cant write this as a comment. as i understand ur problem , u can display it with the flex proprety

```<code>ul.tagit {
  margin-bottom: 0px;
  display: flex;
}
</code>```

here is a demo

http://jsfiddle.net/4eusrdbf/1/

Body:
I tried to get the 'li.tagit-new input' to cover the full width of the rest of the parent ul.tagit with:

ul.tagit li {
    display:table-cell;
    white-space:nowrap;
    vertical-align:top;
    float: none;
}

ul.tagit li.tagit-new {
    width: 100%;
    border: 1px solid #ddd;
}
ul.tagit li.tagit-new input {
    width: 100%;
}

It works fine if there is at least one tag. But not if there no tag:

http://jsfiddle.net/bus9dgx5/

Body:
i cant write this as a comment. as i understand ur problem , u can display it with the flex proprety

ul.tagit {
  margin-bottom: 0px;
  display: flex;
}

here is a demo

http://jsfiddle.net/4eusrdbf/1/


问:
Plotting Interpolated 3D Data As A 2D Image using Matplotlib
The data set is made of a list dfList containing pandas DataFrames, each DataFrame consisting of the column Y and an identical index column. I am trying to plot all the DataFrames as a 2D plot with pixel color representing the Y values.

Example of the Style of Plot Needed

Problem: However, using scipy.interpolate.griddata with matplotlib.pyplot.imshow produces a blank plot! What might be the problem?

I have added a link to the pickle.dump of dfList for reproducing the problem. Any help appreciated!!

Matploblib Image

Code

```<code>import scipy

# Meshgrid
xgrid = dfList[0].index.tolist()
ygrid = np.linspace(266, 1, 532)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)

# Points
xo = dfList[0].index.tolist()
yo = [266, 300, 350, 400, 450, 500, 532]    # one for each DataFrame
points = [ [x, y] for y in yo for x in xo]
points = np.array(points)

# Values
values = []
for df in dfList:
    values.extend(df['Y'].real)
# values = [ item for item in df['Y'].real for df in dfList]    # faster way of collapsing list
values = np.array(values)

# Griddata
resampled = scipy.interpolate.griddata(points, values, (Xgrid, Ygrid), method='cubic')

plt.imshow(resampled.T, extent=[365,1099,266,532], origin='lower')
</code>```

dfList: Pickle Dump

https://gist.githubusercontent.com/anonymous/06076ecda9afcacfffd92b965996fe3e/raw/658e6157388ddedfe8882c2ad6c8f89af1eee5ac/dfList%2520(pickle%2520dump)

答:
To make this answer somehow useful for other people, find here first a general explanation. Below there is a more concrete solution to the question.

The general explanation, np.meshgrid vs. np.mgrid in the use with scipy.interpolate.griddata.

I here provide an example which compares the use of np.meshgrid with np.mgrid when it comes to interpolation with scipy.interpolate.griddata. Gnerally speaking, the returns of np.meshgrid are the transposed returns of np.mgrid for the same grid.

```<code>import numpy as np; np.random.seed(0)
import scipy.interpolate
import matplotlib.pyplot as plt

# np. meshgrid
xgrid = np.arange(21)[::2]
ygrid = np.linspace(0,5,6)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)

# np. mgrid
Xgrid2, Ygrid2 = np.mgrid[0:20:11j,0:5:6j]

# points for interpolation
points = np.random.rand(200, 2)
points[:,0] *= 20
points[:,1] *= 5

# values
f = lambda x,y: np.sin(x)+ y
values = f(points[:,0], points[:,1])

# initerpolation using grid defined with np.meshgrid
resampled = scipy.interpolate.griddata(points, values, (Xgrid2, Ygrid2), method='cubic')

# interpolation using grid defined with np.mgrid
resampled2 = scipy.interpolate.griddata(points, values, (Xgrid.T, Ygrid.T), method='cubic')

fig, (ax1, ax2, ax3) = plt.subplots(3,1)
kws = dict( extent=[-1,21,-0.5,5.5], vmin=-1, vmax=6, origin="lower")
ax1.set_title("function evaluated on grid")
ax1.imshow(f(Xgrid, Ygrid), **kws)

ax2.set_title("interpolation using grid defined with np.meshgrid")
ax2.imshow(resampled.T, **kws)

ax3.set_title("interpolation using grid defined with np.mgrid")
ax3.imshow(resampled2.T, **kws)

for ax in (ax1, ax2, ax3):
    ax.set_yticks(range(6))
    ax.set_xticks(range(21)[::2])

plt.tight_layout()
plt.show()
</code>```

Now to the question and its solution.

Step 1. Create a MCVE

(can be omitted, since more experienced users create those themselves when asking a question)

```<code>import numpy as np; np.random.seed(0)
import scipy.interpolate
import matplotlib.pyplot as plt
import pandas as pd

a = np.random.rand(532, 7)
dfList = [pd.DataFrame(a[:,i], columns=["Y"]) for i in range(7)]

# Meshgrid
xgrid = dfList[0].index.tolist()
ygrid = np.linspace(266, 1, 532)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)

# Points
xo = dfList[0].index.tolist()
yo = [266, 300, 350, 400, 450, 500, 532]    # one for each DataFrame
points = [ [x, y] for y in yo for x in xo]
points = np.array(points)

# Values
values = []
for df in dfList:
    values.extend(df['Y'].real)

values = np.array(values)

# Griddata
resampled = scipy.interpolate.griddata(points, values, (Xgrid, Ygrid), method='cubic')

plt.imshow(resampled.T, extent=[365,1099,266,532], origin='lower')
plt.show()
</code>```

creates

Step 2. The Problem.

We see a blank plot with only a small line of dots in the left handside of the image, while we would expect the complete graph to be filled with an image of shape (266, 532).

Step 3. The solution.

Using scipy.interpolate.griddata we need to supply the grids to the xi argument as a tuple (Xgrid.T, Ygrid.T), where the grids are generated via numpy.meshgrid: Xgrid, Ygrid = np.meshgrid(xgrid, ygrid). Note that meshgrid is different from numpy.mgrid.

There are some other inconsistencies with the points of the meshgrid compared to the sample points, so here I assume that you want to have the values between 266 and 532 being interpolated.

```<code>import numpy as np; np.random.seed(0)
import scipy.interpolate
import matplotlib.pyplot as plt
import pandas as pd

a = np.random.rand(532, 7)
dfList = [pd.DataFrame(a[:,i], columns=["Y"]) for i in range(7)]

# Meshgrid
xgrid = dfList[0].index.values
ygrid = np.arange(266,532)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)

# Points
xo = dfList[0].index.tolist()
yo = [266, 300, 350, 400, 450, 500, 532]    # one for each DataFrame
points = [ [x, y] for y in yo for x in xo]
points = np.array(points)
print points.shape

# Values
values = []
for df in dfList:
    values.extend(df['Y'].real)
values = np.array(values)

# Griddata
resampled = scipy.interpolate.griddata(points, values, (Xgrid.T, Ygrid.T), method='cubic')
print resampled.T.shape
plt.imshow(resampled.T, extent=[365,1099,266,532], origin='lower') #,

plt.show()
</code>```

Body:
The data set is made of a list dfList containing pandas DataFrames, each DataFrame consisting of the column Y and an identical index column. I am trying to plot all the DataFrames as a 2D plot with pixel color representing the Y values.

Example of the Style of Plot Needed

Problem: However, using scipy.interpolate.griddata with matplotlib.pyplot.imshow produces a blank plot! What might be the problem?

I have added a link to the pickle.dump of dfList for reproducing the problem. Any help appreciated!!

Matploblib Image

Code

import scipy

# Meshgrid
xgrid = dfList[0].index.tolist()
ygrid = np.linspace(266, 1, 532)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)

# Points
xo = dfList[0].index.tolist()
yo = [266, 300, 350, 400, 450, 500, 532]    # one for each DataFrame
points = [ [x, y] for y in yo for x in xo]
points = np.array(points)

# Values
values = []
for df in dfList:
    values.extend(df['Y'].real)
# values = [ item for item in df['Y'].real for df in dfList]    # faster way of collapsing list
values = np.array(values)

# Griddata
resampled = scipy.interpolate.griddata(points, values, (Xgrid, Ygrid), method='cubic')

plt.imshow(resampled.T, extent=[365,1099,266,532], origin='lower')

dfList: Pickle Dump

https://gist.githubusercontent.com/anonymous/06076ecda9afcacfffd92b965996fe3e/raw/658e6157388ddedfe8882c2ad6c8f89af1eee5ac/dfList%2520(pickle%2520dump)

Body:
To make this answer somehow useful for other people, find here first a general explanation. Below there is a more concrete solution to the question.

The general explanation, np.meshgrid vs. np.mgrid in the use with scipy.interpolate.griddata.

I here provide an example which compares the use of np.meshgrid with np.mgrid when it comes to interpolation with scipy.interpolate.griddata. Gnerally speaking, the returns of np.meshgrid are the transposed returns of np.mgrid for the same grid.

import numpy as np; np.random.seed(0)
import scipy.interpolate
import matplotlib.pyplot as plt

# np. meshgrid
xgrid = np.arange(21)[::2]
ygrid = np.linspace(0,5,6)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)

# np. mgrid
Xgrid2, Ygrid2 = np.mgrid[0:20:11j,0:5:6j]

# points for interpolation
points = np.random.rand(200, 2)
points[:,0] *= 20
points[:,1] *= 5

# values
f = lambda x,y: np.sin(x)+ y
values = f(points[:,0], points[:,1])

# initerpolation using grid defined with np.meshgrid
resampled = scipy.interpolate.griddata(points, values, (Xgrid2, Ygrid2), method='cubic')

# interpolation using grid defined with np.mgrid
resampled2 = scipy.interpolate.griddata(points, values, (Xgrid.T, Ygrid.T), method='cubic')

fig, (ax1, ax2, ax3) = plt.subplots(3,1)
kws = dict( extent=[-1,21,-0.5,5.5], vmin=-1, vmax=6, origin="lower")
ax1.set_title("function evaluated on grid")
ax1.imshow(f(Xgrid, Ygrid), **kws)

ax2.set_title("interpolation using grid defined with np.meshgrid")
ax2.imshow(resampled.T, **kws)

ax3.set_title("interpolation using grid defined with np.mgrid")
ax3.imshow(resampled2.T, **kws)

for ax in (ax1, ax2, ax3):
    ax.set_yticks(range(6))
    ax.set_xticks(range(21)[::2])

plt.tight_layout()
plt.show()

Now to the question and its solution.

Step 1. Create a MCVE

(can be omitted, since more experienced users create those themselves when asking a question)

import numpy as np; np.random.seed(0)
import scipy.interpolate
import matplotlib.pyplot as plt
import pandas as pd

a = np.random.rand(532, 7)
dfList = [pd.DataFrame(a[:,i], columns=["Y"]) for i in range(7)]

# Meshgrid
xgrid = dfList[0].index.tolist()
ygrid = np.linspace(266, 1, 532)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)

# Points
xo = dfList[0].index.tolist()
yo = [266, 300, 350, 400, 450, 500, 532]    # one for each DataFrame
points = [ [x, y] for y in yo for x in xo]
points = np.array(points)

# Values
values = []
for df in dfList:
    values.extend(df['Y'].real)

values = np.array(values)

# Griddata
resampled = scipy.interpolate.griddata(points, values, (Xgrid, Ygrid), method='cubic')

plt.imshow(resampled.T, extent=[365,1099,266,532], origin='lower')
plt.show()

creates

Step 2. The Problem.

We see a blank plot with only a small line of dots in the left handside of the image, while we would expect the complete graph to be filled with an image of shape (266, 532).

Step 3. The solution.

Using scipy.interpolate.griddata we need to supply the grids to the xi argument as a tuple (Xgrid.T, Ygrid.T), where the grids are generated via numpy.meshgrid: Xgrid, Ygrid = np.meshgrid(xgrid, ygrid). Note that meshgrid is different from numpy.mgrid.

There are some other inconsistencies with the points of the meshgrid compared to the sample points, so here I assume that you want to have the values between 266 and 532 being interpolated.

import numpy as np; np.random.seed(0)
import scipy.interpolate
import matplotlib.pyplot as plt
import pandas as pd

a = np.random.rand(532, 7)
dfList = [pd.DataFrame(a[:,i], columns=["Y"]) for i in range(7)]

# Meshgrid
xgrid = dfList[0].index.values
ygrid = np.arange(266,532)
Xgrid, Ygrid = np.meshgrid(xgrid, ygrid)

# Points
xo = dfList[0].index.tolist()
yo = [266, 300, 350, 400, 450, 500, 532]    # one for each DataFrame
points = [ [x, y] for y in yo for x in xo]
points = np.array(points)
print points.shape

# Values
values = []
for df in dfList:
    values.extend(df['Y'].real)
values = np.array(values)

# Griddata
resampled = scipy.interpolate.griddata(points, values, (Xgrid.T, Ygrid.T), method='cubic')
print resampled.T.shape
plt.imshow(resampled.T, extent=[365,1099,266,532], origin='lower') #,

plt.show()


问:
Bitmap loading very slow
I'm using this method for loading albumArt in list

```<code> long thisAlbum = musicCursor.getLong(albumColumn);

          Bitmap artWork = null;

            Uri sArtworkUri = Uri
                    .parse("content://media/external/audio/albumart");
            Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, thisAlbum);

            try {
                artWork = MediaStore.Images.Media.getBitmap(
                        musicResolver, albumArtUri);
                artWork = Bitmap.createScaledBitmap(artWork, 150, 150, true);

            } catch (FileNotFoundException exception) {
                exception.printStackTrace();
                artWork = BitmapFactory.decodeResource(getResources(),
                        R.drawable.no_cover);
            } catch (IOException e) {
                e.printStackTrace();
            }

            songsList.add(new Songs(thisId, thisTitle, thisArtist, artWork));
        }
</code>```

everything is working fine but when i open my activity it takes more then 10 seconds to load the activity and when i remove this bunch of code activity open as normally ,can anyone tell me please why it is happening and please tell me also what to do or any update for code

答:
Instead of Bitmap I always use glide library(It gives smoothness to app)

So just add it in build.gradle(Module App)

```<code>compile 'com.github.bumptech.glide:glide:3.7.0
</code>```

code to load image in imageview using glide

```<code> Glide.with(context).load(imagePath).crossFade().diskCacheStrategy(DiskCacheStrategy.ALL).thumbnail(0.5f).into(imageView);
</code>```

I Hope It will Help You :)

Title: Bitmap loading very slow

Body:
I'm using this method for loading albumArt in list

 long thisAlbum = musicCursor.getLong(albumColumn);

          Bitmap artWork = null;

            Uri sArtworkUri = Uri
                    .parse("content://media/external/audio/albumart");
            Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, thisAlbum);

            try {
                artWork = MediaStore.Images.Media.getBitmap(
                        musicResolver, albumArtUri);
                artWork = Bitmap.createScaledBitmap(artWork, 150, 150, true);

            } catch (FileNotFoundException exception) {
                exception.printStackTrace();
                artWork = BitmapFactory.decodeResource(getResources(),
                        R.drawable.no_cover);
            } catch (IOException e) {
                e.printStackTrace();
            }

            songsList.add(new Songs(thisId, thisTitle, thisArtist, artWork));
        }

everything is working fine but when i open my activity it takes more then 10 seconds to load the activity and when i remove this bunch of code activity open as normally ,can anyone tell me please why it is happening and please tell me also what to do or any update for code

Body:
Instead of Bitmap I always use glide library(It gives smoothness to app)

So just add it in build.gradle(Module App)

compile 'com.github.bumptech.glide:glide:3.7.0

code to load image in imageview using glide

 Glide.with(context).load(imagePath).crossFade().diskCacheStrategy(DiskCacheStrategy.ALL).thumbnail(0.5f).into(imageView);

I Hope It will Help You :)


问:
Radio Button form to change variables on PHP file
Basically what I'm trying to achieve is a simple PHP on/off where I have PHP code which is set to 0 but have the ability to change it to a 1 or 0 from a form.</p>

```<code> PHP file| $settingon = 1 //1 for active, 0 for inactive
HTML file| <form action="php/settingfile.php">
       <input type="radio" name="settingon" value="1"> Active<br>
       <input type="radio" name="settingon" value="0"> Inactive<br>
       <button type="submit">Save Settings</button>
       </form>
</code>```

答:
If you want to disable the input:

```<code><form action="php/settingfile.php">
    <input type="radio" name="settingon" <?php $settingon? "":"disabled" ?>> Active<br>
    <button type="submit">Save Settings</button>
</form>
</code>```

or create a class that displays the input as you want:

```<code><form action="php/settingfile.php">
    <input type="radio" name="settingon" class="<?php $settingon? "active":"inactive" ?>"> Active<br>
    <button type="submit">Save Settings</button>
</form>
</code>```

Body:
Basically what I'm trying to achieve is a simple PHP on/off where I have PHP code which is set to 0 but have the ability to change it to a 1 or 0 from a form.

 PHP file| $settingon = 1 //1 for active, 0 for inactive
HTML file| <form action="php/settingfile.php">
       <input type="radio" name="settingon" value="1"> Active

       <input type="radio" name="settingon" value="0"> Inactive

       <button type="submit">Save Settings</button>
       </form>

Body:
If you want to disable the input:

<form action="php/settingfile.php">
    <input type="radio" name="settingon" <?php $settingon? "":"disabled" ?>> Active<br>
    <button type="submit">Save Settings</button>
</form>

or create a class that displays the input as you want:

<form action="php/settingfile.php">
    <input type="radio" name="settingon" class="<?php $settingon? "active":"inactive" ?>"> Active<br>
    <button type="submit">Save Settings</button>
</form>


问:
How to disable future date with Datepicker
I am trying to disable date picker for future date but getting not idea...

Here is the what I have tried:

```<code> bday.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

             Calendar mcurrentDate=Calendar.getInstance();
                year=mcurrentDate.get(Calendar.YEAR);
                month=mcurrentDate.get(Calendar.MONTH);
                day=mcurrentDate.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog   mDatePicker =new DatePickerDialog(CreateAccountActivity.this, new OnDateSetListener()
                {
                    @Override
                    public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
                    {
                            year = selectedyear;
                            month = selectedmonth;
                            day = selectedday;

                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            Calendar cal = Calendar.getInstance();

                            String currenttime = new String(dateFormat.format(cal.getTime()));
                            String selectedtime = new String (new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
                            String futuretime = new String (dateFormat.format(System.currentTimeMillis()));

                           if(selectedtime==currenttime)
                        {
                            Toast.makeText(getApplicationContext(), "you were not born in the future", Toast.LENGTH_SHORT).show();
                            bday.setText("");
                        }
                        else
                        {
                     bday.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
                    }}
                },year, month, day);
                mDatePicker.setTitle("Please select date");
                mDatePicker.show();
        }
    });
</code>```

Stackoverflow suggested to use:

```<code>mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());
</code>```

but in above condition how should I use this.?
I am trying to disable future date. But not getting any idea :(

答:
```<code>package com.keshav.datePicker_With_Hide_Future_Past_Date;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    EditText ed_date;
    int year;
    int month;
    int day;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ed_date=(EditText) findViewById(R.id.et_date);

        ed_date.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Calendar mcurrentDate=Calendar.getInstance();
                year=mcurrentDate.get(Calendar.YEAR);
                month=mcurrentDate.get(Calendar.MONTH);
                day=mcurrentDate.get(Calendar.DAY_OF_MONTH);

                final DatePickerDialog   mDatePicker =new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener()
                {
                    @Override
                    public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
                    {
                              ed_date.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
                            int month_k=selectedmonth+1;

                    }
                },year, month, day);
                mDatePicker.setTitle("Please select date");
                // TODO Hide Future Date Here
                mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());

                // TODO Hide Past Date Here
                //  mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis());
                mDatePicker.show();
            }
        });
    }
}
</code>```

Body:
I am trying to disable date picker for future date but getting not idea...

Here is the what I have tried:

 bday.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

             Calendar mcurrentDate=Calendar.getInstance();
                year=mcurrentDate.get(Calendar.YEAR);
                month=mcurrentDate.get(Calendar.MONTH);
                day=mcurrentDate.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog   mDatePicker =new DatePickerDialog(CreateAccountActivity.this, new OnDateSetListener()
                {
                    @Override
                    public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
                    {
                            year = selectedyear;
                            month = selectedmonth;
                            day = selectedday;

                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            Calendar cal = Calendar.getInstance();

                            String currenttime = new String(dateFormat.format(cal.getTime()));
                            String selectedtime = new String (new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
                            String futuretime = new String (dateFormat.format(System.currentTimeMillis()));

                           if(selectedtime==currenttime)
                        {
                            Toast.makeText(getApplicationContext(), "you were not born in the future", Toast.LENGTH_SHORT).show();
                            bday.setText("");
                        }
                        else
                        {
                     bday.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
                    }}
                },year, month, day);
                mDatePicker.setTitle("Please select date");
                mDatePicker.show();
        }
    });

Stackoverflow suggested to use:

mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());

but in above condition how should I use this.?
I am trying to disable future date. But not getting any idea :(


问:
Unable to subclass UILabel: Unrecognized selector sent to UILabel
I'm using CocoaPods to import some things. Right now I'm trying to use TTTAttributedLabel, which is a rich subclass of UILabel, allowing for URL-clicking etc.

Now, I'm having trouble getting my app to recognise that my labels are actually instances of TTTAttributedLabel, and not regular UILabel's.

In my .xib, I have dragged a regular UILabel into my view, then edited the class of the label like this:

It did autocomplete the name for me, so I know it knows about the class. Then, I have dragged a connection from the xib to the view's class, like this:

It specifies itself as a TTTAttributedLabel automatically, because it recognises that that's what it is, or else it would've said UILabel.

Since I've specified use_frameworks! in my podfile, I have to import the class, so in the top of my view's class, I have import TTTAttributedLabel.

Now, when I try to use the label, it autocompletes likes this:

With the correct class, TTTAttributedLabel.
But when I do this:

```<code>print("labBody: ", labBody)
</code>```

it prints out this:

```<code>labBody:  <UILabel: 0x7fa754c86710; frame = (16 459; 42 21); text = 'Label'; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x60000029cf20>>
</code>```

thinking it's a UILabel. If I try to access any of the TTTAttributedLabel-specific variables or functions, it still autocompletes them for me:

```<code>labBody.enabledTextCheckingTypes = NSTextCheckingResult.CheckingType.link.rawValue
</code>```

But when using these on runtime, the entire app crashes, saying this:

```<code> -[UILabel setEnabledTextCheckingTypes:]: unrecognized selector sent to instance 0x7fdfc7c59300
</code>```

Am I blind? Why is this not working? This is what I've always been doing. I might be having a hard Tuesday..
I have tried all the regular stuff, cleaning, deleting derived data, restarting Xcode, deleting the app from the device before running again..

I have even used TTTAttributedLabel before, I know it works. The only thing that's new is that this is my first time using use_frameworks!.. Does that affect the .xib? Making it unable to know about the subclass, or something..?

答:
I have no idea exactly why this worked, but I assume it has something to do with this pod being in Objective-C and something about binding and loading Obj-C stuff..

Anyway, all I had to do was to wrap the object in a new local class.

and then change the class of my labels in the .xib-file to this class instead of TTTAttributedLabel (and the outlets in my view's class, obviously).

No need to do anything else than creating this class, it doesn't need to contain anything.

I did read something about setting a flag, like a load ObjC-flag, I didn't try it. I thought that that solution might also load a lot of other Object-C stuff I didn't need/want to load..

Body:
I'm using CocoaPods to import some things. Right now I'm trying to use TTTAttributedLabel, which is a rich subclass of UILabel, allowing for URL-clicking etc.

Now, I'm having trouble getting my app to recognise that my labels are actually instances of TTTAttributedLabel, and not regular UILabel's.

In my .xib, I have dragged a regular UILabel into my view, then edited the class of the label like this:

It did autocomplete the name for me, so I know it knows about the class. Then, I have dragged a connection from the xib to the view's class, like this:

It specifies itself as a TTTAttributedLabel automatically, because it recognises that that's what it is, or else it would've said UILabel.

Since I've specified use_frameworks! in my podfile, I have to import the class, so in the top of my view's class, I have import TTTAttributedLabel.

Now, when I try to use the label, it autocompletes likes this:

With the correct class, TTTAttributedLabel.
But when I do this:

print("labBody: ", labBody)

it prints out this:

labBody:  <UILabel: 0x7fa754c86710; frame = (16 459; 42 21); text = 'Label'; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x60000029cf20>>

thinking it's a UILabel. If I try to access any of the TTTAttributedLabel-specific variables or functions, it still autocompletes them for me:

labBody.enabledTextCheckingTypes = NSTextCheckingResult.CheckingType.link.rawValue

But when using these on runtime, the entire app crashes, saying this:

 -[UILabel setEnabledTextCheckingTypes:]: unrecognized selector sent to instance 0x7fdfc7c59300

Am I blind? Why is this not working? This is what I've always been doing. I might be having a hard Tuesday..
I have tried all the regular stuff, cleaning, deleting derived data, restarting Xcode, deleting the app from the device before running again..

I have even used TTTAttributedLabel before, I know it works. The only thing that's new is that this is my first time using use_frameworks!.. Does that affect the .xib? Making it unable to know about the subclass, or something..?


问:
Cannot push an element in attribute of an object
I'm building a stack but I don't know why when try to push I get: "Cannot read property 'push' of undefined".

```<code>function stack(n) {
  return {
    size: n,
    elements: [],
    push: (item) => {
      if ( this.elements.length < this.size) {
        this.elements.push(item);
        return this.elements;
      } else {
        return this.elements.length !== n ? true : 'Stack Overflow';
      }
    },
    pop: () => {
      if (n !== 0) {
        return n !== 0 ? this.elements.pop() : 'Stack Underflow';
      }
    },
    isEmpty: () => {
      return this.elements === undefined;
    },
    isFull: () => {
      return elements.length === n ? true : false;
    },
  };
};
</code>```

What is happening? Thanks a lot.

答:
In your code below, if this.elements === undefined, you then try this.elements.push(1). this.elements will need to be instantiated before you use .push().

```<code>if (this.elements === undefined || this.elements.length < this.size) {
    this.elements.push(1);
    return this.elements;
</code>```

I don't really understand what you're trying to do, but you need to do something like this

```<code>if (this.elements === undefined || this.elements.length < this.size) {
    this.elements = <instantiate it here>;
    this.elements.push(1);
    return this.elements;
</code>```

Body:
I'm building a stack but I don't know why when try to push I get: "Cannot read property 'push' of undefined".

function stack(n) {
  return {
    size: n,
    elements: [],
    push: (item) => {
      if ( this.elements.length < this.size) {
        this.elements.push(item);
        return this.elements;
      } else {
        return this.elements.length !== n ? true : 'Stack Overflow';
      }
    },
    pop: () => {
      if (n !== 0) {
        return n !== 0 ? this.elements.pop() : 'Stack Underflow';
      }
    },
    isEmpty: () => {
      return this.elements === undefined;
    },
    isFull: () => {
      return elements.length === n ? true : false;
    },
  };
};

What is happening? Thanks a lot.

Body:
In your code below, if this.elements === undefined, you then try this.elements.push(1). this.elements will need to be instantiated before you use .push().

if (this.elements === undefined || this.elements.length < this.size) {
    this.elements.push(1);
    return this.elements;

I don't really understand what you're trying to do, but you need to do something like this

if (this.elements === undefined || this.elements.length < this.size) {
    this.elements = <instantiate it here>;
    this.elements.push(1);
    return this.elements;


问:
ArrayIndexOutOfBoundsException,
I created an array of integers. I tried to return an even array from the original array, but it says "ArrayIndexOutOfBoundsException " pointing at this section of the code "evenArr[size++] = arry[i];". I know d size of d array is 5.
Thank you </p>

```<code>package practice;

import java.util.*;

class Testt {

    int[] myArr = {4, 6, 6, 7, 2};
    int size = 0;
    int[] evenArr;

    Testt() {
        this.evenArr = new int[size];
    }

    public int[] arr(int[] arry) {
        for (int i = 0; i < arry.length; i++) {
            if (arry[i] % 2 == 0) {
                evenArr[size++] = arry[i];

            }
        }
        return evenArr;
    }
}

public class ReturnStatement {

    public static void main(String[] args) {

        Testt t = new Testt();
        System.out.println("Size: " + t.myArr.length);

        int[] result = t.arr(t.myArr);
        for (int i = 0; i < result.length; i++) {
            System.out.println(result + ", ");
        }

    }

}
</code>```

答:
In your code, on instantiation, size == 0, so your evenArr has a max size of 0. The second you try to add any value to the array you will get that error. Try making it myArr.size()

Or more ideally, use a list which can be dynamically sized so you don't end up with an oversized array.

ContentLicense: CC BY-SA 4.0

Title: ArrayIndexOutOfBoundsException,

Body:
I created an array of integers. I tried to return an even array from the original array, but it says "ArrayIndexOutOfBoundsException " pointing at this section of the code "evenArr[size++] = arry[i];". I know d size of d array is 5.
Thank you

package practice;

import java.util.*;

class Testt {

    int[] myArr = {4, 6, 6, 7, 2};
    int size = 0;
    int[] evenArr;

    Testt() {
        this.evenArr = new int[size];
    }

    public int[] arr(int[] arry) {
        for (int i = 0; i < arry.length; i++) {
            if (arry[i] % 2 == 0) {
                evenArr[size++] = arry[i];

            }
        }
        return evenArr;
    }
}

public class ReturnStatement {

    public static void main(String[] args) {

        Testt t = new Testt();
        System.out.println("Size: " + t.myArr.length);

        int[] result = t.arr(t.myArr);
        for (int i = 0; i < result.length; i++) {
            System.out.println(result + ", ");
        }

    }

}


问:
Using WITH CTE in IF NOT EXISTS
I have a table-valued function that selects rows as part of a CTE, and I then want to perform a different select/insert into the returned table if no rows were selected in the CTE:

```<code>WITH myCte AS (SELECT * FROM abc WHERE xyz = 123)

IF NOT EXISTS (SELECT * FROM myCte)
BEGIN
    ...
END
</code>```

However I'm getting a syntax error whenever I go to use CTE tables in the NOT EXISTS condition. My myCte is a lot more complex than the example, so it will be awkward to place the whole query in the condition.

How can I use the CTE result in the condition check?

答:
You need to declare your common table expression in the context where it will be used and it can only be used for the statement that follows with. If you want to use the results multiple times, you can either repeat the common table expression multiple times, or you can use a table variable or temporary table to hold the results instead.

```<code>WITH myCte AS (SELECT * FROM abc WHERE xyz = 123)

select *
into #myTempTable
from myCte

IF NOT EXISTS (SELECT * FROM #myTempTable)
BEGIN
    ...
END
</code>```

Title: Using WITH CTE in IF NOT EXISTS

Body:
I have a table-valued function that selects rows as part of a CTE, and I then want to perform a different select/insert into the returned table if no rows were selected in the CTE:

WITH myCte AS (SELECT * FROM abc WHERE xyz = 123)

IF NOT EXISTS (SELECT * FROM myCte)
BEGIN
    ...
END

However I'm getting a syntax error whenever I go to use CTE tables in the NOT EXISTS condition. My myCte is a lot more complex than the example, so it will be awkward to place the whole query in the condition.

How can I use the CTE result in the condition check?

Body:
You need to declare your common table expression in the context where it will be used and it can only be used for the statement that follows with. If you want to use the results multiple times, you can either repeat the common table expression multiple times, or you can use a table variable or temporary table to hold the results instead.

WITH myCte AS (SELECT * FROM abc WHERE xyz = 123)

select *
into #myTempTable
from myCte

IF NOT EXISTS (SELECT * FROM #myTempTable)
BEGIN
    ...
END


问:
Retrieving data from famous movie websites
I am currently prototyping a university project and I need to know whether it is possible to fetch the rating of a movie from imdb.com or rottentomatoes.com, using C++. If so, would that be possible to somehow search for that rating based on a title alone? </p>

答:
The quickest way is to use website https://www.omdbapi.com/.
You can query informations about movie just by sending HTTP request. Site will return JSON with informations about movie.

Example:

HTTP request
https://www.omdbapi.com/?t=Ghost
will return JSON

{
  "Title":"Ghost",
  "Year":"1990",
  "Rated":"PG-13",
  "Released":"13 Jul 1990",
  "Runtime":"127 min",
  "Genre":"Drama, Fantasy, Romance",
  "Director":"Jerry Zucker",
  "Writer":"Bruce Joel Rubin",
  "Actors":"Patrick Swayze, Demi Moore, Whoopi Goldberg, Tony Goldwyn",
  "Plot":"After a young man is murdered, his spirit stays behind to warn his lover of impending danger, with the help of a reluctant psychic.",
  "Language":"English",
  "Country":"USA",
  "Awards":"Won 2 Oscars. Another 16 wins & 22 nominations.",
  "Poster":"https://images-na.ssl-images-amazon.com/images/M/MV5BMTU0NzQzODUzNl5BMl5BanBnXkFtZTgwMjc5NTYxMTE@._V1_SX300.jpg",
  "Ratings":[
    {
      "Source":"Internet Movie Database",
      "Value":"7.0/10"
    },
    {
      "Source":"Rotten Tomatoes",
      "Value":"74%"
    },
    {
      "Source":"Metacritic",
      "Value":"52/100"
    }
  ],
  "Metascore":"52",
  "imdbRating":"7.0",
  "imdbVotes":"160,136",
  "imdbID":"tt0099653",
  "Type":"movie",
  "DVD":"24 Apr 2001",
  "BoxOffice":"N/A",
  "Production":"Paramount Pictures",
  "Website":"N/A",
  "Response":"True"
}

To send HTTP request you may use Boost Asio or cpp-netlib (https://github.com/cpp-netlib/cpp-netlib)


问:
What are the trade-offs when denormalizing for a computed column?
I hope I am not asking a too obvious question here.

For my current project I am designing a relatively simple database using sql server 2008. For one of the tables I have decided to introduce a 'Computed Column' (not persisted). Its expression is simply the product of 2 other numeric columns and its sole reason for existence is convenience (I am doing some one-way databinding to a webpage).

I realized however that using a computed column violates the first normal form. This got me wondering: Wat are the trade-offs? If my only reason for the computed column is convenience, does it outweigh the denormalization?

答: "using a computed column violates the first normal form": not at all ! It's not stored, it is re-calculated with the latest data at all time. So it is an excellent solution, just like having a calculated column in a view.</p>