问:
Store MD5 hash in SQLITE3 database in python
Currently my database stores the 'password' as text, but this says it does not work as shown below (The password is also converted into MD5 hash):

Password 'function':

```<code>user_in = input("Please enter a password next to this text: \n")
Password = hashlib.md5()
Password.update(user_in.encode("utf-8"))
</code>```

Error message:

```<code>sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
</code>```

What I want to know is how I store the hash in a database in SQLITE3

Edit:

```<code>cursor=db.cursor()
sql="insert into Accounts (Username, Password) values(?,?)"
cursor.execute(sql, (Username, Password))
db.commit()
</code>```

Edit 2:

```<code>user_in = input("Please enter a password next to this text: \n")
Password = hashlib.md5()
Password.update(user_in.encode("utf-8"))
Password.hexdigest()
</code>```

答:
Make sure arguments for cursor.execute functions are actually strings and you'll be golden! :)

```<code>cursor.execute(sql, (str(Username), str(Password)))
</code>```

This is done by casting them during the argument pass

Body:
Currently my database stores the 'password' as text, but this says it does not work as shown below (The password is also converted into MD5 hash):

Password 'function':

user_in = input("Please enter a password next to this text: \n")
Password = hashlib.md5()
Password.update(user_in.encode("utf-8"))

Error message:

sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.

What I want to know is how I store the hash in a database in SQLITE3

Edit:

cursor=db.cursor()
sql="insert into Accounts (Username, Password) values(?,?)"
cursor.execute(sql, (Username, Password))
db.commit()

Edit 2:

user_in = input("Please enter a password next to this text: \n")
Password = hashlib.md5()
Password.update(user_in.encode("utf-8"))
Password.hexdigest()

Body:
Make sure arguments for cursor.execute functions are actually strings and you'll be golden! :)

cursor.execute(sql, (str(Username), str(Password)))

This is done by casting them during the argument pass


来源: stackexchange

问:
Page is downloaded instead of rendered over SSL
I have my checkout page secured on my site with the Bluehost SSL certificate and quite frequently the page will be downloaded instead of rendered.

This only happens when I use ssl, if I run the site without it the page loads fine.

Is there anything i can do to prevent this, I have tried placing

```<code><?php header("Content-type: text/html"); ?>
</code>```

at the top of the page but this doesn't solve the issue. Here is an example of the file headers that are downloaded when the issue occurs:

```<code>     HTTP/1.1 200 OK
Date: Sun, 12 Dec 2010 23:42:18 GMT
Server: Apache
X-Powered-By: PHP/5.2.14
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Encoding: gzip
Vary: Accept-Encoding
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html
</code>```

Here is an example of the headers when it loads correctly:

```<code>HTTP/1.1 200 OK
Date: Mon, 13 Dec 2010 03:04:08 GMT
Server: Apache
X-Powered-By: PHP/5.2.14
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Encoding: gzip
Vary: Accept-Encoding
Keep-Alive: timeout=10, max=28
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html
</code>```

答: I found the issue was being caused by my css and javascript minifier script, "CSS and Javascript Combinator". When I swapped it out to use "Minify" the issue was resolved.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have my checkout page secured on my site with the Bluehost SSL certificate and quite frequently the page will be downloaded instead of rendered.

This only happens when I use ssl, if I run the site without it the page loads fine.

Is there anything i can do to prevent this, I have tried placing

<?php header("Content-type: text/html"); ?>

at the top of the page but this doesn't solve the issue. Here is an example of the file headers that are downloaded when the issue occurs:

     HTTP/1.1 200 OK
Date: Sun, 12 Dec 2010 23:42:18 GMT
Server: Apache
X-Powered-By: PHP/5.2.14
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Encoding: gzip
Vary: Accept-Encoding
Connection: close
Transfer-Encoding: chunked
Content-Type: text/html

Here is an example of the headers when it loads correctly:

HTTP/1.1 200 OK
Date: Mon, 13 Dec 2010 03:04:08 GMT
Server: Apache
X-Powered-By: PHP/5.2.14
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Encoding: gzip
Vary: Accept-Encoding
Keep-Alive: timeout=10, max=28
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html


问:
Django: Outlook email smtp timeout in production server
i'm trying to send a SMTP email from Django, using my credentials of Outlook. My code works in localhost, but when I upload my code to production server, it doesn't.

If I use my Gmail credential, it also works in production, but it doesn't with Outlook. So, I think Outlook is configured in a different way, but I dont know.

This is my view code:

```<code>def send_my_custom_email():

    connection = mail.get_connection(
        host = 'smtp-mail.outlook.com',
        port = 25,
        username = 'myemail@outlook.com',
        password = 'mypassword' ,
        )
    connection.open()

    email2send  = mail.EmailMessage('hello', 'hello', 'myemail@outlook.com', to=['receiveremail'], connection=connection)

    email2send.send()
    connection.close()
</code>```

I know that my configuration setting are right because it can send emails from localhost. These are my settings.py:

```<code>EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
</code>```

I already try to check the Outlook settings, but I couldn't find anything about SMTP use.

My exact questions are:

Outlook need aditional settings in production?

The problem is in my code or in Outlook settings?

Why it works in localhost but it does not in production server?

答: Outlook.com only allows encrypted SMTP TLS connections on port 587. It does not even listen on port 25, that is why you get a timeout. </p>

ContentLicense: CC BY-SA 3.0

Body:
i'm trying to send a SMTP email from Django, using my credentials of Outlook. My code works in localhost, but when I upload my code to production server, it doesn't.

If I use my Gmail credential, it also works in production, but it doesn't with Outlook. So, I think Outlook is configured in a different way, but I dont know.

This is my view code:

def send_my_custom_email():

    connection = mail.get_connection(
        host = 'smtp-mail.outlook.com',
        port = 25,
        username = 'myemail@outlook.com',
        password = 'mypassword' ,
        )
    connection.open()

    email2send  = mail.EmailMessage('hello', 'hello', 'myemail@outlook.com', to=['receiveremail'], connection=connection)

    email2send.send()
    connection.close()

I know that my configuration setting are right because it can send emails from localhost. These are my settings.py:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True

I already try to check the Outlook settings, but I couldn't find anything about SMTP use.

My exact questions are:

Outlook need aditional settings in production?

The problem is in my code or in Outlook settings?

Why it works in localhost but it does not in production server?


问:
Resize animated base64 with JavaScript
Is it possible to resize an animated base64 with JavaScript on the client side.</p>

答: A gif is just an image, so yes you can use vanilla javascript to resize it, without the need for an npm package. </p>

Title: Resize animated base64 with JavaScript


问:
What am I doing wrong in the below Prolog code
The Program aims at checking whether a student has taken a specified list of courses or not. But it displays false even if the student has taken that list of courses. What am I doing wrong?

Code:

 %Structure  Of facts

 %student(ID,FirstName,LastName,Advisor,CreditsPassed,GPA,CourseTakenList).
 %courses_taken(CourseId,CourseTitle, Credit,Grade, NoOfTimesRepeated).

   %Fact
   student(20135639,'Sara','Haider','Mr. Hussain Al-Arrayed',98,3.95,
   [courses_taken('ITCE418', 'PRODUCTIVITY WITH IS TECHNOLOGY',3,'A', 0),
    courses_taken('MATHS101', 'CALCULUS I', 3,'A', 0),
    courses_taken('ACC112', 'FINANCIAL ACCOUNTING I', 3, 'A', 0),
    courses_taken('ECON140', 'MICROECONOMICS', 3,'A', 0),
    courses_taken('ENGL219', 'TECHNICAL REPORT WRITING', 3,'A', 0)  ]  ).

 check_prereq([],Id):- !.
 check_prereq([course(P)]|T,Id):-
     student(Id,_,_,_,_,_, CoursesTakenList),
     member( courses_taken(P,_,_,_,_), CoursesTakenList),
     check_prereq(T,Id).
```

<p>The following query should return true, since the student has taken those courses</p>

<pre class="lang-erlang prettyprint-override"><code> ?- check_prereq([course('ITCE418'), course('ACC112')],20135639).
 false.
</code>```

Am I doing something wrong?

答:
You need to replace : [course(P)]|T with [course(P)|T]

```<code> check_prereq([],_):- !.
 check_prereq([course(P)|T],Id):-
     student(Id,_,_,_,_,_, CoursesTakenList),
     member( courses_taken(P,_,_,_,_), CoursesTakenList),
     check_prereq(T,Id).
</code>```

Also in the first line replaced Id with _ (anonymous variable) in order to get rid of warnings(Singleton variable). Now it is working fine:

```<code>?- check_prereq([course('ITCE418'), course('ACC112')],20135639).
true ;
false.
</code>```

Note that it returns true and asking for more solutions returns false but it succeeds as we expected.

Body:
The Program aims at checking whether a student has taken a specified list of courses or not. But it displays false even if the student has taken that list of courses. What am I doing wrong?

Code:

 %Structure  Of facts

 %student(ID,FirstName,LastName,Advisor,CreditsPassed,GPA,CourseTakenList).
 %courses_taken(CourseId,CourseTitle, Credit,Grade, NoOfTimesRepeated).

   %Fact
   student(20135639,'Sara','Haider','Mr. Hussain Al-Arrayed',98,3.95,
   [courses_taken('ITCE418', 'PRODUCTIVITY WITH IS TECHNOLOGY',3,'A', 0),
    courses_taken('MATHS101', 'CALCULUS I', 3,'A', 0),
    courses_taken('ACC112', 'FINANCIAL ACCOUNTING I', 3, 'A', 0),
    courses_taken('ECON140', 'MICROECONOMICS', 3,'A', 0),
    courses_taken('ENGL219', 'TECHNICAL REPORT WRITING', 3,'A', 0)  ]  ).

 check_prereq([],Id):- !.
 check_prereq([course(P)]|T,Id):-
     student(Id,_,_,_,_,_, CoursesTakenList),
     member( courses_taken(P,_,_,_,_), CoursesTakenList),
     check_prereq(T,Id).

The following query should return true, since the student has taken those courses

 ?- check_prereq([course('ITCE418'), course('ACC112')],20135639).
 false.

Am I doing something wrong?

Body:
You need to replace : [course(P)]|T with [course(P)|T]

 check_prereq([],_):- !.
 check_prereq([course(P)|T],Id):-
     student(Id,_,_,_,_,_, CoursesTakenList),
     member( courses_taken(P,_,_,_,_), CoursesTakenList),
     check_prereq(T,Id).

Also in the first line replaced Id with _ (anonymous variable) in order to get rid of warnings(Singleton variable). Now it is working fine:

?- check_prereq([course('ITCE418'), course('ACC112')],20135639).
true ;
false.

Note that it returns true and asking for more solutions returns false but it succeeds as we expected.


问:
Exception: cvc-complex-type.2.4.a: Invalid content was found starting with eleme nt 'employee'. One of '{contractemployee}' is expected
So ..I have this ER diagram:

Hence I wrote an company.xml as:

```<code><?xml version="1.0" encoding="UTF-8"?>

<company xmlns="urn:company.Namespace" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:schemaLocation="urn:company.Namespace companyxsd.xsd">
    <companyname>ABC company</companyname>
    <address>xyz street, India.</address>

    <department>
        <dname>Marketing</dname>
        <deptphoneno>9876543210</deptphoneno>
        <deptfaxno>0442456879</deptfaxno>
        <deptemail>marketing@abc.com</deptemail>

        <employee>
            <empid>101</empid>
            <ename>Rishie</ename>
            <emailid>rishie@abc.com</emailid>
            <phoneno>9876543211</phoneno>
        </employee>

        <contractemployee>
            <name>Ravi</name>
            <phoneno>9874563214</phoneno>
        </contractemployee>
    </department>

</company>
</code>```

and my companyxsd.xsd as follows:

```<code>    <?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="urn:company.Namespace" xmlns="urn:company.Namespace">

    <xs:element name="company">
     <xs:complexType>
      <xs:sequence>
       <xs:element name="companyname" type="xs:string"/>
       <xs:element name="address" type="xs:string"/>

       <xs:element name="department">
        <xs:complexType>
         <xs:sequence>
          <xs:element name="dname" type="xs:string"/>
          <xs:element name="deptphoneno" type="xs:integer"/>
          <xs:element name="deptfaxno" type="xs:integer"/>
          <xs:element name="deptemail" type="xs:string"/>

          <xs:element name="employee">
           <xs:complexType>
            <xs:sequence>
             <xs:element name="empid" type="xs:integer"/>
             <xs:element name="ename" type="xs:string"/>
             <xs:element name="emailid" type="xs:string"/>
             <xs:element name="phoneno" type="xs:integer"/>
            </xs:sequence>
           </xs:complexType>
          </xs:element>

          <xs:element name="contractemployee">
           <xs:complexType>
            <xs:sequence>
             <xs:element name="name" type="xs:string"/>
             <xs:element name="phoneno" type="xs:integer"/>
            </xs:sequence>
           </xs:complexType>
          </xs:element>

         </xs:sequence>
        </xs:complexType>
       </xs:element>
      </xs:sequence>
     </xs:complexType>
    </xs:element>

</xs:schema>
</code>```

I am not sure whether my xml represents the ER diagram as it is. If not please help me out with the correct xml template.

Since Iam a beginner..I have doubts on the XSd I have written. ':(

For the above, I keep getting errors as such

```<code>Exception: cvc-complex-type.2.4.a: Invalid content was found starting with eleme
nt 'employee'. One of '{contractemployee}' is expected.
</code>```

The new error:

```<code>Exception: cvc-elt.1.a: Cannot find the declaration of element 'company'.
</code>```

Help me out here pals!

答:
The XML + XSD you posted do not create the error you mentioned, the XML is not actually valid xml. However you are very close, there is a problem with your namespace declaration in the XML and also in the XSD.

In the XSD you need to set the target namespace, like this:

```<code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="company.namespace">
</code>```

Now to make sure the document validates, the namespace in the xml needs to be the same as the one you put in the XSD. In the XML the formatting of the namespace declaration is also invalid. Make it as follows:

```<code><company xmlns="company.namespace">
</code>```

Keep in mind this is just a namespace, it is not an actual reference to the xsd file, a lot of namespaces look like URI's, however most are not actual functional URI's either.

I replaced the namespace with an example "company.namespace" just to make it clearer. Using filenames might create the suggestion they actually point to files.

When using the schemaLocation in the XML to identify the corresponding XSD file you need to add the namespace/prefix declaration. Currently the xml parser does not recognise the xs prefix because it is unknown in the XML file. You can solve this as follows:

```<code><company xmlns="urn:company.Namespace"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
 xs:schemaLocation="urn:company.Namespace companyxsd.xsd">
</code>```

Here are the resulting files:
XML

```<code><?xml version="1.0" encoding="UTF-8"?>

<company xmlns="urn:company.Namespace"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
 xs:schemaLocation="urn:company.Namespace companyxsd.xsd">    <companyname>ABC company</companyname>
    <address>xyz street, India.</address>

    <department>
        <dname>Marketing</dname>
        <deptphoneno>9876543210</deptphoneno>
        <deptfaxno>0442456879</deptfaxno>
        <deptemail>marketing@abc.com</deptemail>

        <employee>
            <empid>101</empid>
            <ename>Rishie</ename>
            <emailid>rishie@abc.com</emailid>
            <phoneno>9876543211</phoneno>
        </employee>

        <contractemployee>
            <name>Ravi</name>
            <phoneno>9874563214</phoneno>
        </contractemployee>
    </department>

</company>
</code>```

XSD

```<code><?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="urn:company.Namespace" xmlns="urn:company.Namespace">

    <xs:element name="company">
     <xs:complexType>
      <xs:sequence>
       <xs:element name="companyname" type="xs:string"/>
       <xs:element name="address" type="xs:string"/>

       <xs:element name="department">
        <xs:complexType>
         <xs:sequence>
          <xs:element name="dname" type="xs:string"/>
          <xs:element name="deptphoneno" type="xs:integer"/>
          <xs:element name="deptfaxno" type="xs:integer"/>
          <xs:element name="deptemail" type="xs:string"/>

          <xs:element name="employee">
           <xs:complexType>
            <xs:sequence>
             <xs:element name="empid" type="xs:integer"/>
             <xs:element name="ename" type="xs:string"/>
             <xs:element name="emailid" type="xs:string"/>
             <xs:element name="phoneno" type="xs:integer"/>
            </xs:sequence>
           </xs:complexType>
          </xs:element>

          <xs:element name="contractemployee">
           <xs:complexType>
            <xs:sequence>
             <xs:element name="name" type="xs:string"/>
             <xs:element name="phoneno" type="xs:integer"/>
            </xs:sequence>
           </xs:complexType>
          </xs:element>

         </xs:sequence>
        </xs:complexType>
       </xs:element>
      </xs:sequence>
     </xs:complexType>
    </xs:element>

</xs:schema>
</code>```

Body:
So ..I have this ER diagram:

Hence I wrote an company.xml as:

<?xml version="1.0" encoding="UTF-8"?>

<company xmlns="urn:company.Namespace" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:schemaLocation="urn:company.Namespace companyxsd.xsd">
    <companyname>ABC company</companyname>
    <address>xyz street, India.</address>

    <department>
        <dname>Marketing</dname>
        <deptphoneno>9876543210</deptphoneno>
        <deptfaxno>0442456879</deptfaxno>
        <deptemail>marketing@abc.com</deptemail>

        <employee>
            <empid>101</empid>
            <ename>Rishie</ename>
            <emailid>rishie@abc.com</emailid>
            <phoneno>9876543211</phoneno>
        </employee>

        <contractemployee>
            <name>Ravi</name>
            <phoneno>9874563214</phoneno>
        </contractemployee>
    </department>

</company>

and my companyxsd.xsd as follows:

    <?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="urn:company.Namespace" xmlns="urn:company.Namespace">

    <xs:element name="company">
     <xs:complexType>
      <xs:sequence>
       <xs:element name="companyname" type="xs:string"/>
       <xs:element name="address" type="xs:string"/>

       <xs:element name="department">
        <xs:complexType>
         <xs:sequence>
          <xs:element name="dname" type="xs:string"/>
          <xs:element name="deptphoneno" type="xs:integer"/>
          <xs:element name="deptfaxno" type="xs:integer"/>
          <xs:element name="deptemail" type="xs:string"/>

          <xs:element name="employee">
           <xs:complexType>
            <xs:sequence>
             <xs:element name="empid" type="xs:integer"/>
             <xs:element name="ename" type="xs:string"/>
             <xs:element name="emailid" type="xs:string"/>
             <xs:element name="phoneno" type="xs:integer"/>
            </xs:sequence>
           </xs:complexType>
          </xs:element>

          <xs:element name="contractemployee">
           <xs:complexType>
            <xs:sequence>
             <xs:element name="name" type="xs:string"/>
             <xs:element name="phoneno" type="xs:integer"/>
            </xs:sequence>
           </xs:complexType>
          </xs:element>

         </xs:sequence>
        </xs:complexType>
       </xs:element>
      </xs:sequence>
     </xs:complexType>
    </xs:element>

</xs:schema>

I am not sure whether my xml represents the ER diagram as it is. If not please help me out with the correct xml template.

Since Iam a beginner..I have doubts on the XSd I have written. ':(

For the above, I keep getting errors as such

Exception: cvc-complex-type.2.4.a: Invalid content was found starting with eleme
nt 'employee'. One of '{contractemployee}' is expected.

The new error:

Exception: cvc-elt.1.a: Cannot find the declaration of element 'company'.

Help me out here pals!

Body:
The XML + XSD you posted do not create the error you mentioned, the XML is not actually valid xml. However you are very close, there is a problem with your namespace declaration in the XML and also in the XSD.

In the XSD you need to set the target namespace, like this:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="company.namespace">

Now to make sure the document validates, the namespace in the xml needs to be the same as the one you put in the XSD. In the XML the formatting of the namespace declaration is also invalid. Make it as follows:

<company xmlns="company.namespace">

Keep in mind this is just a namespace, it is not an actual reference to the xsd file, a lot of namespaces look like URI's, however most are not actual functional URI's either.

I replaced the namespace with an example "company.namespace" just to make it clearer. Using filenames might create the suggestion they actually point to files.

When using the schemaLocation in the XML to identify the corresponding XSD file you need to add the namespace/prefix declaration. Currently the xml parser does not recognise the xs prefix because it is unknown in the XML file. You can solve this as follows:

<company xmlns="urn:company.Namespace"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
 xs:schemaLocation="urn:company.Namespace companyxsd.xsd">

Here are the resulting files:
XML

<?xml version="1.0" encoding="UTF-8"?>

<company xmlns="urn:company.Namespace"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
 xs:schemaLocation="urn:company.Namespace companyxsd.xsd">    <companyname>ABC company</companyname>
    <address>xyz street, India.</address>

    <department>
        <dname>Marketing</dname>
        <deptphoneno>9876543210</deptphoneno>
        <deptfaxno>0442456879</deptfaxno>
        <deptemail>marketing@abc.com</deptemail>

        <employee>
            <empid>101</empid>
            <ename>Rishie</ename>
            <emailid>rishie@abc.com</emailid>
            <phoneno>9876543211</phoneno>
        </employee>

        <contractemployee>
            <name>Ravi</name>
            <phoneno>9874563214</phoneno>
        </contractemployee>
    </department>

</company>

XSD

<?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="urn:company.Namespace" xmlns="urn:company.Namespace">

    <xs:element name="company">
     <xs:complexType>
      <xs:sequence>
       <xs:element name="companyname" type="xs:string"/>
       <xs:element name="address" type="xs:string"/>

       <xs:element name="department">
        <xs:complexType>
         <xs:sequence>
          <xs:element name="dname" type="xs:string"/>
          <xs:element name="deptphoneno" type="xs:integer"/>
          <xs:element name="deptfaxno" type="xs:integer"/>
          <xs:element name="deptemail" type="xs:string"/>

          <xs:element name="employee">
           <xs:complexType>
            <xs:sequence>
             <xs:element name="empid" type="xs:integer"/>
             <xs:element name="ename" type="xs:string"/>
             <xs:element name="emailid" type="xs:string"/>
             <xs:element name="phoneno" type="xs:integer"/>
            </xs:sequence>
           </xs:complexType>
          </xs:element>

          <xs:element name="contractemployee">
           <xs:complexType>
            <xs:sequence>
             <xs:element name="name" type="xs:string"/>
             <xs:element name="phoneno" type="xs:integer"/>
            </xs:sequence>
           </xs:complexType>
          </xs:element>

         </xs:sequence>
        </xs:complexType>
       </xs:element>
      </xs:sequence>
     </xs:complexType>
    </xs:element>

</xs:schema>


问:
Trouble configuring Presto's memory allocation on AWS EMR
I am really hoping to use Presto in an ETL pipeline on AWS EMR, but I am having trouble configuring it to fully utilize the cluster's resources.  This cluster would exist solely for this one query, and nothing more, then die.  Thus, I would like to claim the maximum available memory for each node and the one query by increasing query.max-memory-per-node and query.max-memory.  I can do this when I'm configuring the cluster by adding these settings in the "Edit software settings" box of the cluster creation view in the AWS console.  But the Presto server doesn't start, reporting in the server.log file an IllegalArgumentException, saying that max-memory-per-node exceeds the useable heap space (which, by default, is far too small for my instance type and use case).

I have tried to use the session setting set session resource_overcommit=true, but that only seems to override query.max-memory, not query.max-memory-per-node, because in the Presto UI, I see that very little of the available memory on each node is being used for the query.

Through Google, I've been led to believe that I need to also increase the JVM heap size by changing the -Xmx and -Xms properties in /etc/presto/conf/jvm.config, but it says here (http://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-presto.html) that it is not possible to alter the JVM settings in the cluster creation phase.

To change these properties after the EMR cluster is active and the Presto server has been started, do I really have to manually ssh into each node and alter jvm.config and config.properties, and restart the Presto server?  While I realize it'd be possible to manually install Presto with a custom configuration on an EMR cluster through a bootstrap script or something, this would really be a deal-breaker.

Is there something I'm missing here?  Is there not an easier way to make Presto allocate all of a cluster to one query?

答:
As advertised, increasing query.max-memory-per-node, and also by necessity the -Xmx property, indeed cannot be achieved on EMR until after Presto has already started with the default options.  To increase these, the jvm.config and config.properties found in /etc/presto/conf/ have to be changed, and the Presto server restarted on each node (core and coordinator).

One can do this with a bootstrap script using commands like

```<code>sudo sed -i "s/query.max-memory-per-node=.*GB/query.max-memory-per-node=20GB/g" /etc/presto/conf/config.properties
sudo restart presto-server
</code>```

and similarly for /etc/presto/jvm.conf.  The only caveats are that one needs to include the logic in the bootstrap action to execute only after Presto has been installed, and that the server on the coordinating node needs to be restarted last (and possibly with different settings if the master node's instance type is different than the core nodes).

You might also need to change resources.reserved-system-memory from the default by specifying a value for it in config.properties.  By default, this value is .4*(Xmx value), which is how much memory is claimed by Presto for the system pool.  In my case, I was able to safely decrease this value and give more memory to each node for executing the query.

Body:
As advertised, increasing query.max-memory-per-node, and also by necessity the -Xmx property, indeed cannot be achieved on EMR until after Presto has already started with the default options.  To increase these, the jvm.config and config.properties found in /etc/presto/conf/ have to be changed, and the Presto server restarted on each node (core and coordinator).

One can do this with a bootstrap script using commands like

sudo sed -i "s/query.max-memory-per-node=.*GB/query.max-memory-per-node=20GB/g" /etc/presto/conf/config.properties
sudo restart presto-server

and similarly for /etc/presto/jvm.conf.  The only caveats are that one needs to include the logic in the bootstrap action to execute only after Presto has been installed, and that the server on the coordinating node needs to be restarted last (and possibly with different settings if the master node's instance type is different than the core nodes).

You might also need to change resources.reserved-system-memory from the default by specifying a value for it in config.properties.  By default, this value is .4*(Xmx value), which is how much memory is claimed by Presto for the system pool.  In my case, I was able to safely decrease this value and give more memory to each node for executing the query.


问:
ASP.NET: User won't stay logged in for more than 30 mins
This is really irritating me, and is probably causing the waning usership on my website. I'm using Forms Authentication to log my user in.

I have the "Persist" parameter set to true by default when the user logs in:

```<code>RedirectFromLoginPage(userString, True)
</code>```

and

```<code>SetAuthCookie(userString, True)
</code>```

In my web.Config file I have the "timeout" attribute set to "129600":

```<code><authentication mode="Forms">
    <forms loginUrl="/registration/login.aspx"
    timeout="129600" slidingExpiration="true" />
</authentication>
</code>```

I called my hosting company and they said the problem has to be with my code. I don't believe this is the case.

What the #(@%&@(#%&@(#*% could be wrong??

EDIT This used to work fine until I switched hosts. That led me to believe that it was not my code, but in fact the host.

EDIT 2 In response to a comment to use Fiddler, here's what I get from Fiddler when I load the page:

```
Set-Cookie: .ASPXAUTH=; expires=Tue, 12-Oct-1999 07:00:00 GMT; path=/; HttpOnly
Set-Cookie: .ASPXAUTH=[some gobbledygook];
  expires=Sun, 15-Nov-2009 20:46:29 GMT; path=/; HttpOnly
Set-Cookie: ASP.NET_SessionId=vudqghfplqnh5hz1qw1cwebt; path=/; HttpOnly
```

答:
As you know I have a similar problem. What might be happening is the application pool is shutting down.

Do a test: open your session in 2 different browsers and in one of them reload the web page in less than 20 minutes, while in the other do nothing.

What might happen is that you won't get logged off of any of them because the app pool is kept alive.

edit:

Try this: http://authors.aspalliance.com/paulwilson/articles/?id=12

Body:
This is really irritating me, and is probably causing the waning usership on my website. I'm using Forms Authentication to log my user in.

I have the "Persist" parameter set to true by default when the user logs in:

RedirectFromLoginPage(userString, True)

and

SetAuthCookie(userString, True)

In my web.Config file I have the "timeout" attribute set to "129600":

<authentication mode="Forms">
    <forms loginUrl="/registration/login.aspx"
    timeout="129600" slidingExpiration="true" />
</authentication>

I called my hosting company and they said the problem has to be with my code. I don't believe this is the case.

What the #(@%&@(#%&@(#*% could be wrong??

EDIT This used to work fine until I switched hosts. That led me to believe that it was not my code, but in fact the host.

EDIT 2 In response to a comment to use Fiddler, here's what I get from Fiddler when I load the page:

Set-Cookie: .ASPXAUTH=; expires=Tue, 12-Oct-1999 07:00:00 GMT; path=/; HttpOnly
Set-Cookie: .ASPXAUTH=[some gobbledygook];
  expires=Sun, 15-Nov-2009 20:46:29 GMT; path=/; HttpOnly
Set-Cookie: ASP.NET_SessionId=vudqghfplqnh5hz1qw1cwebt; path=/; HttpOnly


问:
How to replace character at even position by ( and odd position by )
Is it possible to write down a regular expression such that the first $ sign will be replaced by a (, the second with a ), the third with a (, etc ?

For instance, the string

```<code>This is an $example$ of what I want, $ 1+1=2 $ and $ 2+2=4$.
</code>```

should become

```<code>This is an (example) of what I want, ( 1+1=2 ) and ( 2+2=4).
</code>```

答:
According to an answer already posted here https://stackoverflow.com/a/13947249/6332575 in Ruby you can use

yourstring.gsub("$").with_index(1){|_, i| i.odd? ? "(" : ")"}

Body:
Is it possible to write down a regular expression such that the first $ sign will be replaced by a (, the second with a ), the third with a (, etc ?

For instance, the string

This is an $example$ of what I want, $ 1+1=2 $ and $ 2+2=4$.

should become

This is an (example) of what I want, ( 1+1=2 ) and ( 2+2=4).


问:
Regex Match All Except Leading and Trailing Spaces Around Commas (including comma)
I'm trying to match everything except commas and any spaces around them. However, I would like it to match spaces between words. This is what I have so far:

```<code>/[^,\s][a-zA-Z0-9_ !@#$%^&*()]+/gi
</code>```

It's matching everything except commas and trailing spaces, but it's including the leading spaces. Here's the link to test it regex101.

I'm trying to wrap span tags around key terms. This is what I would want the end result to be:

```<code><span>Some text</span>   ,    <span>Some more     text</span>
</code>```

I'm currently using

```<code>.replace(/([^,\s][a-zA-Z0-9_ !@#$%^&*()]+)/gi, "<span>$1</span>")
</code>```

and it updates the span tags in a contenteditable div. I'm using it to place bubbles using CSS around key terms, and are updated after every input. Any help would be greatly appreciated! Thanks!

Body:
I'm trying to match everything except commas and any spaces around them. However, I would like it to match spaces between words. This is what I have so far:

/[^,\s][a-zA-Z0-9_ !@#$%^&*()]+/gi

It's matching everything except commas and trailing spaces, but it's including the leading spaces. Here's the link to test it regex101.

I'm trying to wrap span tags around key terms. This is what I would want the end result to be:

Some text   ,    Some more     text

I'm currently using

.replace(/([^,\s][a-zA-Z0-9_ !@#$%^&*()]+)/gi, "$1")

and it updates the span tags in a contenteditable div. I'm using it to place bubbles using CSS around key terms, and are updated after every input. Any help would be greatly appreciated! Thanks!

Body:
Does this do the trick ?

/((?:(\w|[-!@#$%^&*()])+( (\w|[-!@#$%^&*()]))*)+)/g

Or

/((?:(\w|[-!@#$%^&*()])+( {1,MAX_NUMBER_OF_SPACES}(\w|[-!@#$%^&*()]))*)+)/g


问:
Extracting hours and minutes from UIDatePicker
I have a UIDatePicker set in time mode, and have a property referencing that date picker. I don't know how to extract hour and minutes components from UIDatePicker when set to time mode in Swift 3.
Please help</p>

答:
Even in .time mode the date property returns a Date instance.

Get hour and minute with Calendar and DateComponents

```<code>let picker = UIDatePicker()
picker.datePickerMode = .time

let date = picker.date
let components = Calendar.current.dateComponents([.hour, .minute], from: date)
let hour = components.hour!
let minute = components.minute!
</code>```

Body:
Even in .time mode the date property returns a Date instance.

Get hour and minute with Calendar and DateComponents

let picker = UIDatePicker()
picker.datePickerMode = .time

let date = picker.date
let components = Calendar.current.dateComponents([.hour, .minute], from: date)
let hour = components.hour!
let minute = components.minute!


问:
How to track virus on WordPress site
I run a dedicated server with WHM/cPanel CentOS Apache.

One of my accounts on cPanel have a WordPress site that some how got a virus.
They use it to send mails / inject affiliate links etc.

I have ran AV scanners and also manually cleaned everything i can find, but the virus keep coming back. Is there any way i can log when someone uploads a file via PHP or even create or modify a file?

I have been going trough log files but i keep always seems to miss something so i want to try back-trace it and find the file they use to upload the PHP files with.

答: Use wordfence security plugin that will scan your whole wordpress site and also stop any type of injection. You will not face any trouble after this.</p>

Title: How to track virus on WordPress site


问:
Django: cannot migrate due to object reference in form
I am having trouble running the django migrations on a new database because of the get_or_create() function in a form.

form.py

```<code>class EmployeeForm(...):
    # Make sure that we have a directory before initializing the form
    default_upload_directory = Directory.objects.get_or_create(name='Employee', parent=None)[0]
</code>```

This is the important part of a custom form I wrote. It will link the Employee's uploaded files to a default directory. Everything works fine except for the migration. When I run it on a new database it will complain with django.db.utils.OperationalError: no such table: filemanager_directory. It also happens if I use a standard objects.get(..) to access the Directory object.

I am not sure how to solve this. Obviously the table does not exist, yet. On an existing database with the tables already in place everything works fine.

EDIT: The migrations I am trying to run are not related to this app. Furthermore, as a workaround, you can comment out the line, run the migrations and reactivate it... But this is not a neat solution...

答:
This is, quite simply, not a thing you should do. You shouldn't run any kind of database access in any code that runs at import time, which this does.

There should never be a need to do this in any case. If your goal is to ensure an object exists when the form is instantiated, put it in the __init__ method.

But you should also reflect that ensuring that database objects exist is the job of migrations in the first place. Write a data migration with a RunPython method to do this.

Body:
I am having trouble running the django migrations on a new database because of the get_or_create() function in a form.

form.py

class EmployeeForm(...):
    # Make sure that we have a directory before initializing the form
    default_upload_directory = Directory.objects.get_or_create(name='Employee', parent=None)[0]

This is the important part of a custom form I wrote. It will link the Employee's uploaded files to a default directory. Everything works fine except for the migration. When I run it on a new database it will complain with django.db.utils.OperationalError: no such table: filemanager_directory. It also happens if I use a standard objects.get(..) to access the Directory object.

I am not sure how to solve this. Obviously the table does not exist, yet. On an existing database with the tables already in place everything works fine.

EDIT: The migrations I am trying to run are not related to this app. Furthermore, as a workaround, you can comment out the line, run the migrations and reactivate it... But this is not a neat solution...


问:
Deployed project cannot load the default document and lists the directory instead
Below are my project specifications :

ASP.NET MVC 5

Windows Server 2012 R2

IIS 8.5

I deployed my project on a server composed of above specifications. Now, When I try to load the project, it lists the directory of my project instead of loading the default document as below :

What could possibly be the thing I'm doing wrong here? Why is it not loading the initial page of the application?

答:
So, I figured it out, goes this way :

Click "Server Manager"

Click "Manage" at the top right

Go to "Add Roles and Features"

Proceed until "Server Roles"

In the "Server Roles" tab of the "Roles" section Check "Web Server (IIS)" > "Web Server" > "Application Development" > Check all except "CGI"

Click "Next" & "Install"

You are good to go.


问:
Unable to convert my existing scraper to xmlhttp request
I have written a script to get Title from any random websites. It works flawlessly. I have written this using Internet Explorer. I've tried a lot but can't make the same using xmlhttp request as performance is a big issue to consider. What I've tried so far is:

```<code>Sub Title_scraping()
Dim IE As Object
Dim doc As Object, cel As Range

For Each cel In Range("A1:A5")
    Set IE = CreateObject("InternetExplorer.Application")
    IE.navigate cel.Value

    While IE.Busy
        DoEvents
    Wend

    Set doc = IE.document
    x = x + 1
    Cells(x, 2) = doc.title
Next cel
End Sub
</code>```

Sites I've tried with and got results:

```<code>https://stackoverflow.com/documentation/
https://codereview.stackexchange.com/
https://yts.ag/browse-movies
</code>```

答:
Combining your code and the code posted here, here is your final code:</p>

```<code>Sub GetData()
Dim title As String
Dim objHttp As Object, cel As Range, x As Long
Set objHttp = CreateObject("MSXML2.ServerXMLHTTP")

For Each cel In Range("A1:A5")
    objHttp.Open "GET", cel.Value, False
    On Error Resume Next
    objHttp.send ""

    title = objHttp.responseText
    If InStr(1, UCase(title), "<TITLE>") Then
        title = Mid(title, InStr(1, UCase(title), "<TITLE>") + Len("<TITLE>"))
        title = Mid(title, 1, InStr(1, UCase(title), "</TITLE>") - 1)
    Else
        title = ""
    End If
    x = x + 1
    Cells(x, 2) = title
Next cel

End Sub
</code>```

Body:
I have written a script to get Title from any random websites. It works flawlessly. I have written this using Internet Explorer. I've tried a lot but can't make the same using xmlhttp request as performance is a big issue to consider. What I've tried so far is:

Sub Title_scraping()
Dim IE As Object
Dim doc As Object, cel As Range

For Each cel In Range("A1:A5")
    Set IE = CreateObject("InternetExplorer.Application")
    IE.navigate cel.Value

    While IE.Busy
        DoEvents
    Wend

    Set doc = IE.document
    x = x + 1
    Cells(x, 2) = doc.title
Next cel
End Sub

Sites I've tried with and got results:

https://stackoverflow.com/documentation/
https://codereview.stackexchange.com/
https://yts.ag/browse-movies

Body:
Combining your code and the code posted here, here is your final code:

Sub GetData()
Dim title As String
Dim objHttp As Object, cel As Range, x As Long
Set objHttp = CreateObject("MSXML2.ServerXMLHTTP")

For Each cel In Range("A1:A5")
    objHttp.Open "GET", cel.Value, False
    On Error Resume Next
    objHttp.send ""

    title = objHttp.responseText
    If InStr(1, UCase(title), "<TITLE>") Then
        title = Mid(title, InStr(1, UCase(title), "<TITLE>") + Len("<TITLE>"))
        title = Mid(title, 1, InStr(1, UCase(title), "</TITLE>") - 1)
    Else
        title = ""
    End If
    x = x + 1
    Cells(x, 2) = title
Next cel

End Sub


问:
Android error activity manager type 3 (Eclipse, using jni)
I've been doing an app for a week in cocos2d-x (jni, in c++)

The problem is now I can't run it, can't test it on my device..

I get this error:

```<code>[2013-05-25 21:09:07 - PaperAgeAndroid] ------------------------------
[2013-05-25 21:09:07 - PaperAgeAndroid] Android Launch!
[2013-05-25 21:09:07 - PaperAgeAndroid] adb is running normally.
[2013-05-25 21:09:07 - PaperAgeAndroid] Performing es.rks.paperage.PaperAgeAndroid     activity launch
[2013-05-25 21:09:07 - PaperAgeAndroid] Uploading PaperAgeAndroid.apk onto device '0123456789ABCDEF'
[2013-05-25 21:09:44 - PaperAgeAndroid] Installing PaperAgeAndroid.apk...
[2013-05-25 21:09:48 - PaperAgeAndroid] Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE
[2013-05-25 21:09:48 - PaperAgeAndroid] Please check logcat output for more details.
[2013-05-25 21:09:48 - PaperAgeAndroid] Launch failed on device: 0123456789ABCDEF
[2013-05-25 21:09:48 - PaperAgeAndroid] Starting activity es.rks.paperage.PaperAgeAndroid on device 0123456789ABCDEF
[2013-05-25 21:09:49 - PaperAgeAndroid] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=es.rks.paperage/.PaperAgeAndroid }
[2013-05-25 21:09:49 - PaperAgeAndroid] New package not yet registered with the system. Waiting 3 seconds before next attempt.
[2013-05-25 21:09:52 - PaperAgeAndroid] Starting activity es.rks.paperage.PaperAgeAndroid on device 0123456789ABCDEF
[2013-05-25 21:09:52 - PaperAgeAndroid] New package not yet registered with the system. Waiting 3 seconds before next attempt.
[2013-05-25 21:09:55 - PaperAgeAndroid] Starting activity es.rks.paperage.PaperAgeAndroid on device 0123456789ABCDEF
[2013-05-25 21:09:56 - PaperAgeAndroid] New package not yet registered with the system. Waiting 3 seconds before next attempt.
[2013-05-25 21:09:59 - PaperAgeAndroid] Starting activity es.rks.paperage.PaperAgeAndroid on device 0123456789ABCDEF
[2013-05-25 21:09:59 - PaperAgeAndroid] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=es.rks.paperage/.PaperAgeAndroid }
[2013-05-25 21:09:59 - PaperAgeAndroid] New package not yet registered with the system. Waiting 3 seconds before next attempt.
[2013-05-25 21:10:02 - PaperAgeAndroid] Starting activity es.rks.paperage.PaperAgeAndroid on device 0123456789ABCDEF
[2013-05-25 21:10:02 - PaperAgeAndroid] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=es.rks.paperage/.PaperAgeAndroid }
[2013-05-25 21:10:02 - PaperAgeAndroid] ActivityManager: Error type 3
[2013-05-25 21:10:02 - PaperAgeAndroid] ActivityManager: Error: Activity class {es.rks.paperage/es.rks.paperage.PaperAgeAndroid} does not exist.
</code>```

I had this errors ago but deleting the app from my device fixed that :S Now I can't run the app

Yes, I have tried to clean the project and run it and I still have the same problem

My Android Manifest is :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="es.rks.paperage"
      android:versionCode="1"
      android:versionName="1.0">

    <uses-sdk android:minSdkVersion="9"/>
    <uses-feature android:glEsVersion="0x00020000" />

    <application android:label="@string/app_name"
        android:icon="@drawable/icon">

        <activity android:name="PaperAgeAndroid"
                  android:label="@string/app_name"
                  android:screenOrientation="landscape"
                  android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                  android:configChanges="orientation">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <supports-screens android:largeScreens="true"
                      android:smallScreens="true"
                      android:anyDensity="true"
                      android:normalScreens="true"/>
</manifest>
</code>```

I'm using Eclipse Juno on mac

This is the project structure

答:
In Manifest.xml

```<code><application android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:name=".App" android:enabled="false">
</code>```

//.....

Change the value of android:enable="true" will work

Body:
I've been doing an app for a week in cocos2d-x (jni, in c++)

The problem is now I can't run it, can't test it on my device..

I get this error:

[2013-05-25 21:09:07 - PaperAgeAndroid] ------------------------------
[2013-05-25 21:09:07 - PaperAgeAndroid] Android Launch!
[2013-05-25 21:09:07 - PaperAgeAndroid] adb is running normally.
[2013-05-25 21:09:07 - PaperAgeAndroid] Performing es.rks.paperage.PaperAgeAndroid     activity launch
[2013-05-25 21:09:07 - PaperAgeAndroid] Uploading PaperAgeAndroid.apk onto device '0123456789ABCDEF'
[2013-05-25 21:09:44 - PaperAgeAndroid] Installing PaperAgeAndroid.apk...
[2013-05-25 21:09:48 - PaperAgeAndroid] Installation error: INSTALL_FAILED_INSUFFICIENT_STORAGE
[2013-05-25 21:09:48 - PaperAgeAndroid] Please check logcat output for more details.
[2013-05-25 21:09:48 - PaperAgeAndroid] Launch failed on device: 0123456789ABCDEF
[2013-05-25 21:09:48 - PaperAgeAndroid] Starting activity es.rks.paperage.PaperAgeAndroid on device 0123456789ABCDEF
[2013-05-25 21:09:49 - PaperAgeAndroid] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=es.rks.paperage/.PaperAgeAndroid }
[2013-05-25 21:09:49 - PaperAgeAndroid] New package not yet registered with the system. Waiting 3 seconds before next attempt.
[2013-05-25 21:09:52 - PaperAgeAndroid] Starting activity es.rks.paperage.PaperAgeAndroid on device 0123456789ABCDEF
[2013-05-25 21:09:52 - PaperAgeAndroid] New package not yet registered with the system. Waiting 3 seconds before next attempt.
[2013-05-25 21:09:55 - PaperAgeAndroid] Starting activity es.rks.paperage.PaperAgeAndroid on device 0123456789ABCDEF
[2013-05-25 21:09:56 - PaperAgeAndroid] New package not yet registered with the system. Waiting 3 seconds before next attempt.
[2013-05-25 21:09:59 - PaperAgeAndroid] Starting activity es.rks.paperage.PaperAgeAndroid on device 0123456789ABCDEF
[2013-05-25 21:09:59 - PaperAgeAndroid] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=es.rks.paperage/.PaperAgeAndroid }
[2013-05-25 21:09:59 - PaperAgeAndroid] New package not yet registered with the system. Waiting 3 seconds before next attempt.
[2013-05-25 21:10:02 - PaperAgeAndroid] Starting activity es.rks.paperage.PaperAgeAndroid on device 0123456789ABCDEF
[2013-05-25 21:10:02 - PaperAgeAndroid] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=es.rks.paperage/.PaperAgeAndroid }
[2013-05-25 21:10:02 - PaperAgeAndroid] ActivityManager: Error type 3
[2013-05-25 21:10:02 - PaperAgeAndroid] ActivityManager: Error: Activity class {es.rks.paperage/es.rks.paperage.PaperAgeAndroid} does not exist.

I had this errors ago but deleting the app from my device fixed that :S Now I can't run the app

Yes, I have tried to clean the project and run it and I still have the same problem

My Android Manifest is :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="es.rks.paperage"
      android:versionCode="1"
      android:versionName="1.0">

    <uses-sdk android:minSdkVersion="9"/>
    <uses-feature android:glEsVersion="0x00020000" />

    <application android:label="@string/app_name"
        android:icon="@drawable/icon">

        <activity android:name="PaperAgeAndroid"
                  android:label="@string/app_name"
                  android:screenOrientation="landscape"
                  android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                  android:configChanges="orientation">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <supports-screens android:largeScreens="true"
                      android:smallScreens="true"
                      android:anyDensity="true"
                      android:normalScreens="true"/>
</manifest>

I'm using Eclipse Juno on mac

This is the project structure

Body:
In Manifest.xml

<application android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:name=".App" android:enabled="false">

//.....

Change the value of android:enable="true" will work


问:
JS Need to add value every 1.5 sec
This is my code that is unfortunately not working.

It is taking value from html (600) and then dividing it (var f = 600/20). It should start onclick button (which already has onclick function).

function enemy() {
  var iFrequency = 2500;
  var myInterval = 0;
  var e = document.getElementById('stre').innerHTML;
  var f = e / 20;

  function startLoop() {
    if (myInterval > 0) clearInterval(myInterval); // stop
    myInterval = setInterval("doSomething()", iFrequency);
  }

  function doSomething() {
    var label = document.getElementById('wallvalue');
    label.innerHTML = parseInt(label.innerHTML) + f;
    document.getElementById('wallvalue').style.color = 'red';
    document.getElementById('resultr').innerHTML = f;
    document.getElementById('resultr').style.color = 'red';
    document.getElementById('resultrc').innerHTML = f;
    document.getElementById('resultrc').style.color = 'red';
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><BUTTON class="doit" onclick="damagec(); iFrequency+=1000; startLoop(); return false;"><b>FIGHT</b></BUTTON></code>```

答:
I managed to get it done. Thank you all for the answers!</p>

```<code>function enemy(){
    var e=600;
    var f=600/20;
    document.getElementById('resultr').innerHTML = f;
    document.getElementById('resultr').style.color = 'red';
    document.getElementById('resultrc').innerHTML = f;
    document.getElementById('resultrc').style.color = 'red';

    var intervalID = window.setInterval(myCallback, 3000);

    function myCallback() {
    var label = document.getElementById('wallvalue');
    label.innerHTML = parseInt(label.innerHTML) + f;
    document.getElementById('wallvalue').style.color = 'red';
    }
}
</code>```

Title: JS Need to add value every 1.5 sec

Body:
This is my code that is unfortunately not working.

It is taking value from html (600) and then dividing it (var f = 600/20). It should start onclick button (which already has onclick function).

function enemy() {
  var iFrequency = 2500;
  var myInterval = 0;
  var e = document.getElementById('stre').innerHTML;
  var f = e / 20;

  function startLoop() {
    if (myInterval > 0) clearInterval(myInterval); // stop
    myInterval = setInterval("doSomething()", iFrequency);
  }

  function doSomething() {
    var label = document.getElementById('wallvalue');
    label.innerHTML = parseInt(label.innerHTML) + f;
    document.getElementById('wallvalue').style.color = 'red';
    document.getElementById('resultr').innerHTML = f;
    document.getElementById('resultr').style.color = 'red';
    document.getElementById('resultrc').innerHTML = f;
    document.getElementById('resultrc').style.color = 'red';
  }

<BUTTON class="doit" onclick="damagec(); iFrequency+=1000; startLoop(); return false;">FIGHT</BUTTON>

Body:
I managed to get it done. Thank you all for the answers!

function enemy(){
    var e=600;
    var f=600/20;
    document.getElementById('resultr').innerHTML = f;
    document.getElementById('resultr').style.color = 'red';
    document.getElementById('resultrc').innerHTML = f;
    document.getElementById('resultrc').style.color = 'red';

    var intervalID = window.setInterval(myCallback, 3000);

    function myCallback() {
    var label = document.getElementById('wallvalue');
    label.innerHTML = parseInt(label.innerHTML) + f;
    document.getElementById('wallvalue').style.color = 'red';
    }
}


问:
How can i re write the null checking line since it's not supporting in unity?
```<code>XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");
            XNamespace ns = "http://www.w3.org/2000/svg";

            var list = document.Root.Descendants(ns + "rect").Select(e => new {
                Style = e.Attribute("style").Value.Substring(15, 7),
                Transform = e.Attribute("transform")?.Value,
                Width = e.Attribute("width").Value,
                Height = e.Attribute("height").Value,
                X = e.Attribute("x").Value
            });
</code>```

In csharp it's working fine.
But in unity visual studio i'm getting error on the line:

```<code>e.Attribute("transform")?.Value.Substring(18, 43)
</code>```

Feature 'null propagating operator' is not available in C# 4.  Please use language version 6 or greater.

In csharp i didn't have to change anything.

The visual studio i'm using in unity (same as for csharp) is: 14.0.24531.01 Update 3 and visual c# 2015

Maybe i need to change the line checking for null for something else ?

答:
You already know why you can't use ?. and that's because Unity does not support that version of C# that supports ?..

UnholySheep comment suggests using if statement but I don't think you can use that here.

You can check for null with the ternary operator.

Use:

```<code>Transform = e.Attribute("transform") != null ? e.Attribute("transform").Value : "",
</code>```

If you are still confused. Here is the whole code:

```<code>XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");
XNamespace ns = "http://www.w3.org/2000/svg";

var list = document.Root.Descendants(ns + "rect").Select(e => new
{
    Style = e.Attribute("style").Value.Substring(15, 7),
    Transform = e.Attribute("transform") != null ? e.Attribute("transform").Value : "",
    Width = e.Attribute("width").Value,
    Height = e.Attribute("height").Value,
    X = e.Attribute("x").Value
});
</code>```

Body:
XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");
            XNamespace ns = "http://www.w3.org/2000/svg";

            var list = document.Root.Descendants(ns + "rect").Select(e => new {
                Style = e.Attribute("style").Value.Substring(15, 7),
                Transform = e.Attribute("transform")?.Value,
                Width = e.Attribute("width").Value,
                Height = e.Attribute("height").Value,
                X = e.Attribute("x").Value
            });

In csharp it's working fine.
But in unity visual studio i'm getting error on the line:

e.Attribute("transform")?.Value.Substring(18, 43)

Feature 'null propagating operator' is not available in C# 4.  Please use language version 6 or greater.

In csharp i didn't have to change anything.

The visual studio i'm using in unity (same as for csharp) is: 14.0.24531.01 Update 3 and visual c# 2015

Maybe i need to change the line checking for null for something else ?

Body:
You already know why you can't use ?. and that's because Unity does not support that version of C# that supports ?..

UnholySheep comment suggests using if statement but I don't think you can use that here.

You can check for null with the ternary operator.

Use:

Transform = e.Attribute("transform") != null ? e.Attribute("transform").Value : "",

If you are still confused. Here is the whole code:

XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");
XNamespace ns = "http://www.w3.org/2000/svg";

var list = document.Root.Descendants(ns + "rect").Select(e => new
{
    Style = e.Attribute("style").Value.Substring(15, 7),
    Transform = e.Attribute("transform") != null ? e.Attribute("transform").Value : "",
    Width = e.Attribute("width").Value,
    Height = e.Attribute("height").Value,
    X = e.Attribute("x").Value
});


问:
vb.net escape reserved keywords in sql statement
I'm trying to execute an sql statement in vb.net to an Access database, I am escaping the reserverd word using square brackets []. This has worked in all my SELECT statements within the program.

The reserved word is level

But the SQL statement below fails saying

Syntax error in INSERT INTO statement.

If I directly copy the statement and execute this in Access it works fine

```<code>datalayer.getDataTable(String.Format("INSERT INTO users (username, password, [level]) VALUES ({0}, {1}, {2})", username, password, level))
</code>```

The above statement works if I remove [level] and replace this with another column name.

Thanks.

答:
Always use parameters. What you're doing is very dangerous and leaves the door open to SQL injection.

Then you won't have to worry about escaping the values you're inserting into the database.

Body:
I'm trying to execute an sql statement in vb.net to an Access database, I am escaping the reserverd word using square brackets []. This has worked in all my SELECT statements within the program.

The reserved word is level

But the SQL statement below fails saying

Syntax error in INSERT INTO statement.

If I directly copy the statement and execute this in Access it works fine

datalayer.getDataTable(String.Format("INSERT INTO users (username, password, [level]) VALUES ({0}, {1}, {2})", username, password, level))

The above statement works if I remove [level] and replace this with another column name.

Thanks.


问:
Rails get status from all checkboxes via jquery and send it to controller
So far I have the following setup:

My Checkboxes are declared like this:

```<code><label id="cb2" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="checkbox-1">
     <input type="checkbox" id="checkbox-1" class="mdl-checkbox__input">
     <span class="mdl-checkbox__label">Meal</span>
</label>
</code>```

And I have the following JQuery Code:

```<code><script>
   $(document).ready(function() {
   $("input[type='checkbox']").change(function() {
       $("#change_me").html("<%= j render(partial: 'dynamic_test') %>");
     });
   });
</script>
</code>```

So as soon as I check or uncheck a checkbox I want to get the check attribute of all checkboxes and send them to my controller(ajax?), where I then want to execute some select queries and render it in "dynamic_test". Could someone give me an idea on how to implement the data sending to my controller.

Edit:

My _dynamic_test.html.erb contains:

```<code>Some Test!
<%= @check_box_val %>
</code>```

Edit2:

I got it to work like this:

```<code><script>
 $(document).ready(function() {
 $("input[type='checkbox']").change(function() {
   var selected_checkbox_val = [];
    $("input[type='checkbox']").each(function() {
        if ( this.checked ) {
            selected_checkbox_val.push(this.getAttribute("name"));
        }
    });
    $.ajax({
      url: "/meals/dynamic_test",
      type: "POST",
      data: {
        value: selected_checkbox_val
      },
      dataType: 'script'
    });
   });
 });
</script>
</code>```

If you see a better way, I'm open for changes.

答:
This is how you should do it

```<code><script>
$("input[type='checkbox']").change(function() {
  var selected_checkbox_val = $(this).val();
  $.ajax({
    url: "/meals/dynamic_test",
    type: "POST",
    data: {
      value: selected_checkbox_val
    },
    dataType: 'script'
  });
}
</script>
</code>```

In the controllers dynamic_test method

```<code>def dynamic_test
  @check_box_val = params[:value]
  respond_to do |format|
    format.js
    format.html
  end
end
</code>```

And you should have a file called dynamic_test.js.erb with the following code

```<code>$("#change_me").html("<%= j render(partial: 'dynamic_test', locals: {check_box_val: @check_box_val}) %>");
</code>```

Also you should defind a route for this method

```<code>post "/meals/dynamic_test" => "meals#dynamic_test"
</code>```

Note:

You can change the name of the partial to avoid confusion between main template and partial template.

Body:
So far I have the following setup:

My Checkboxes are declared like this:

     <input type="checkbox" id="checkbox-1" class="mdl-checkbox__input">
     Meal

And I have the following JQuery Code:

So as soon as I check or uncheck a checkbox I want to get the check attribute of all checkboxes and send them to my controller(ajax?), where I then want to execute some select queries and render it in "dynamic_test". Could someone give me an idea on how to implement the data sending to my controller.

Edit:

My _dynamic_test.html.erb contains:

Some Test!
<%= @check_box_val %>

Edit2:

I got it to work like this:

If you see a better way, I'm open for changes.

Body:
This is how you should do it

<script>
$("input[type='checkbox']").change(function() {
  var selected_checkbox_val = $(this).val();
  $.ajax({
    url: "/meals/dynamic_test",
    type: "POST",
    data: {
      value: selected_checkbox_val
    },
    dataType: 'script'
  });
}
</script>

In the controllers dynamic_test method

def dynamic_test
  @check_box_val = params[:value]
  respond_to do |format|
    format.js
    format.html
  end
end

And you should have a file called dynamic_test.js.erb with the following code

$("#change_me").html("<%= j render(partial: 'dynamic_test', locals: {check_box_val: @check_box_val}) %>");

Also you should defind a route for this method

post "/meals/dynamic_test" => "meals#dynamic_test"

Note:

You can change the name of the partial to avoid confusion between main template and partial template.


问:
How to iterate word by word in array in bash
i have a simple script, where i make search of words from file

```<code>words="you are hogan"

for i in $words; do
if grep -q "$i" text.txt; then
        echo "word(s) are exists"
        grep "$i" text.txt
else
        echo "word(s) are not exists"
fi
done
</code>```

it works, i can make grep word by word. My script is is the same:

```<code>grep "you" text.txt
grep "are" text.txt
grep "hogan" text.txt
</code>```

but, the i received another task. i want to search and replace word by word text.
so, i should create second variable, with words, what i should use instead words from first variable $words. how i understand, that i should in one loop use two variables. i know, that i can use array in this case.
ok, let's do it, i tries to make grep, like first example:

```<code>words="you are hogan"
words2="wwe wwf nukem"

for ((i=0;i<${#words[@]};++i)); do
if grep -q "${words[i]}" text.txt; then
        echo "word(s) are exists"
        echo "${words[i]}"
else
        echo "word(s) are not exists"
fi
done
</code>```

result is not good.

```<code>+ (( i=0 ))
+ (( i<1 ))
+ grep -q 'you are hogan' text.txt
+ echo 'word(s) are not exists'
word(s) are not exists
</code>```

How you can see, it tries to make grep of all phraza, not for each word. how can i do grep command for each word, like first example ?

答:
Your second syntax you're trying to treat words like it's an array, but it's a string.  If you wanted it to be an array you could initialize it differently:

```<code>words=("you" "are" "hogan")
for word in "${words[@]}"; do
    if grep -q "$word" text.txt; then
        printf 'Word exists: %s\n' "$word"
    else
        printf 'Word not found: %s\n' "$word"
    fi
done
</code>```

or use your approach if you want the indexes so you can access the same index in the other field.

Body:
i have a simple script, where i make search of words from file

words="you are hogan"

for i in $words; do
if grep -q "$i" text.txt; then
        echo "word(s) are exists"
        grep "$i" text.txt
else
        echo "word(s) are not exists"
fi
done

it works, i can make grep word by word. My script is is the same:

grep "you" text.txt
grep "are" text.txt
grep "hogan" text.txt

but, the i received another task. i want to search and replace word by word text.
so, i should create second variable, with words, what i should use instead words from first variable $words. how i understand, that i should in one loop use two variables. i know, that i can use array in this case.
ok, let's do it, i tries to make grep, like first example:

words="you are hogan"
words2="wwe wwf nukem"

for ((i=0;i<${#words[@]};++i)); do
if grep -q "${words[i]}" text.txt; then
        echo "word(s) are exists"
        echo "${words[i]}"
else
        echo "word(s) are not exists"
fi
done

result is not good.

+ (( i=0 ))
+ (( i<1 ))
+ grep -q 'you are hogan' text.txt
+ echo 'word(s) are not exists'
word(s) are not exists

How you can see, it tries to make grep of all phraza, not for each word. how can i do grep command for each word, like first example ?

Body:
Your second syntax you're trying to treat words like it's an array, but it's a string.  If you wanted it to be an array you could initialize it differently:

words=("you" "are" "hogan")
for word in "${words[@]}"; do
    if grep -q "$word" text.txt; then
        printf 'Word exists: %s\n' "$word"
    else
        printf 'Word not found: %s\n' "$word"
    fi
done

or use your approach if you want the indexes so you can access the same index in the other field.


问:
How to auto layout an app for different devices.
Apologies in advance for the basic nature of this question. I'm happy to be redirected to a previously answered version of this question, but haven't found it yet.

I just finished up the majority of my first app, and am concerned I might have set it up in the wrong way.

My app looks "good" on an iphone7, but when I change the device to a 7+ there is empty space on the bottom and right edges of the view controllers, and when I run it on an iphone 5, the view doesn't fit.

Is there a way to make the view of my app automatically stretch/condense to any device? Or, is this way more complicated that I anticipated? I want to believe there's an easy solution but I haven't found it yet.

Thanks!

答:
Ok so this is gonna be a long task for you. I'll list down the topics you will need to learn in order to get it right.

StackView

Content Hugging Priorities / Compression Resistance Priorities

Constraint priorities

Size Classes for different UI elements

Useful links:

Official Tutorials on some mysteries of Autolayout(Part 1 and Part 2).

Official Guide on Autolayout.

other online resources

as rightly mentioned by J. Doe, The answer is in your question


问:
How to make a div 100% height of the browser window
I have a layout with two columns - a left div and a right div.

The right div has a grey background-color, and I need it to expand vertically depending on the height of the user's browser window. Right now, the background-color ends at the last piece of content in that div.

I've tried height:100%, min-height:100%;, etc.

答:
You can use vh in this case which is relative to 1% of the height of the viewport...

That means if you want to cover off the height, just simply use 100vh.

Look at the image below I draw for you here:

Try the snippet I created for you as below:

.left {
  height: 100vh;
  width: 50%;
  background-color: grey;
  float: left;
}

.right {
  height: 100vh;
  width: 50%;
  background-color: red;
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="left"></div>
<div class="right"></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use vh in this case which is relative to 1% of the height of the viewport...

That means if you want to cover off the height, just simply use 100vh.

Look at the image below I draw for you here:

Try the snippet I created for you as below:

.left {
  height: 100vh;
  width: 50%;
  background-color: grey;
  float: left;
}

.right {
  height: 100vh;
  width: 50%;
  background-color: red;
  float: right;
}

<div class="left"></div>
<div class="right"></div>


问:
Fetch Stored procedure log from system tables in SQL - Server
i am looking to retrieve the SP execution log from system table.

I looking to retrieve the parameters passed for the sp at the time of execution.

答:
You can't. There is no such thing available without running a trace or capturing system events.

There are NO logs that Sql Server maintains itself that will help you.

Your best course of action in the future would be to log this inside the procedure when it's call. Profile traces might help you, but depending on how the procedure was called, it also might not.

Not the answer you were looking for, but it's the answer none the less.


问:
awk - if condition is met, print specific lines before and after
Having the following blastout.txt:

blastout.txt

I need to search all lines that contain Identities = [>=50] and

print the one line above that contains Query=

print the 5th line below

example output (only first lines shown here):

```<code>Query= HWI-ST863:386:C5Y8UACXX:3:1307:8061:42115 1:N:0:ACACGAAT
Sbjct  2030309  ATGACGCTCACCTTGGTGTCGATATCCTCACCTGCGGTGCCAATGCCGCTGCCCGCGGTC  2030250
Query= HWI-ST863:386:C5Y8UACXX:3:2209:19756:21341 1:N:0:ACACGAAT
Sbjct  2418742  CAGGCGTTCCGGCAGTTTGTGCTGGAAGAGGCCCGTGGCCTGGCGGAGCCTCTGCCGGCG  2418683
Query= HWI-ST863:386:C5Y8UACXX:3:1302:8580:7972 1:N:0:ACACGAAT
Sbjct  3178017  CCAGTTATGCTTGGGGCAGGTGAGCTTGTTGCCTTCCAGGGCGAGCTCGGGGATATCCGT  3178076
</code>```

I solved 2.:

```<code>awk 'c&&!--c;/Identities =/ && ($3+0)>=50 {c=5}' blastout.txt
</code>```

that was feasable for me because the structure of the file is always the same. But for the 1. the number of lines is changing, and it can also happen that for one entry of Query=, there is more than one line that match the pattern.

Your help in implementing this is very much appreciated!

答:
Well I cannot tell you how to do it with awk, but I can do it with sed.

The blastout.sed script is:

```<code># place 'Query=' line in hold space
/^Query=/h
# If we find an Identity line
/^ Identities = \([5-9][0-9]\|[1-9][0-9][0-9]\)/{
# Exchange pattern with hold space (the Query= line) and print
x
p
# Exchange pattern with hold space (the Identities = line) and print
x
p
# Get the fifth line and print
n
n
n
n
n
p
}
</code>```

Run it with the command sed -n -f blastout.sed blastout.txt.

Here are some results:

```<code>$ sed -n -f blastout.sed blastout.txt | head -12
Query= HWI-ST863:386:C5Y8UACXX:3:1307:8061:42115 1:N:0:ACACGAAT
 Identities = 100/100 (100%), Gaps = 0/100 (0%)
Sbjct  2030309  ATGACGCTCACCTTGGTGTCGATATCCTCACCTGCGGTGCCAATGCCGCTGCCCGCGGTC  2030250
Query= HWI-ST863:386:C5Y8UACXX:3:2209:19756:21341 1:N:0:ACACGAAT
 Identities = 99/100 (99%), Gaps = 0/100 (0%)
Sbjct  2418742  CAGGCGTTCCGGCAGTTTGTGCTGGAAGAGGCCCGTGGCCTGGCGGAGCCTCTGCCGGCG  2418683
Query= HWI-ST863:386:C5Y8UACXX:3:1302:8580:7972 1:N:0:ACACGAAT
 Identities = 100/100 (100%), Gaps = 0/100 (0%)
Sbjct  3178017  CCAGTTATGCTTGGGGCAGGTGAGCTTGTTGCCTTCCAGGGCGAGCTCGGGGATATCCGT  3178076
Query= HWI-ST863:386:C5Y8UACXX:3:1106:4759:9532 1:N:0:ACACGAAT
 Identities = 100/100 (100%), Gaps = 0/100 (0%)
Sbjct  32627  CGAGGCCGCGGTTTTGGACCTGGACGAGGGGAGTCGGCGTGTGAGTCTTGCGACCCTGGA  32686
</code>```

(Corrected to print the fifth line down.)

Body:
Having the following blastout.txt:

blastout.txt

I need to search all lines that contain Identities = [>=50] and

print the one line above that contains Query=

print the 5th line below

example output (only first lines shown here):

Query= HWI-ST863:386:C5Y8UACXX:3:1307:8061:42115 1:N:0:ACACGAAT
Sbjct  2030309  ATGACGCTCACCTTGGTGTCGATATCCTCACCTGCGGTGCCAATGCCGCTGCCCGCGGTC  2030250
Query= HWI-ST863:386:C5Y8UACXX:3:2209:19756:21341 1:N:0:ACACGAAT
Sbjct  2418742  CAGGCGTTCCGGCAGTTTGTGCTGGAAGAGGCCCGTGGCCTGGCGGAGCCTCTGCCGGCG  2418683
Query= HWI-ST863:386:C5Y8UACXX:3:1302:8580:7972 1:N:0:ACACGAAT
Sbjct  3178017  CCAGTTATGCTTGGGGCAGGTGAGCTTGTTGCCTTCCAGGGCGAGCTCGGGGATATCCGT  3178076

I solved 2.:

awk 'c&&!--c;/Identities =/ && ($3+0)>=50 {c=5}' blastout.txt

that was feasable for me because the structure of the file is always the same. But for the 1. the number of lines is changing, and it can also happen that for one entry of Query=, there is more than one line that match the pattern.

Your help in implementing this is very much appreciated!

Body:
Well I cannot tell you how to do it with awk, but I can do it with sed.

The blastout.sed script is:

# place 'Query=' line in hold space
/^Query=/h
# If we find an Identity line
/^ Identities = \([5-9][0-9]\|[1-9][0-9][0-9]\)/{
# Exchange pattern with hold space (the Query= line) and print
x
p
# Exchange pattern with hold space (the Identities = line) and print
x
p
# Get the fifth line and print
n
n
n
n
n
p
}

Run it with the command sed -n -f blastout.sed blastout.txt.

Here are some results:

$ sed -n -f blastout.sed blastout.txt | head -12
Query= HWI-ST863:386:C5Y8UACXX:3:1307:8061:42115 1:N:0:ACACGAAT
 Identities = 100/100 (100%), Gaps = 0/100 (0%)
Sbjct  2030309  ATGACGCTCACCTTGGTGTCGATATCCTCACCTGCGGTGCCAATGCCGCTGCCCGCGGTC  2030250
Query= HWI-ST863:386:C5Y8UACXX:3:2209:19756:21341 1:N:0:ACACGAAT
 Identities = 99/100 (99%), Gaps = 0/100 (0%)
Sbjct  2418742  CAGGCGTTCCGGCAGTTTGTGCTGGAAGAGGCCCGTGGCCTGGCGGAGCCTCTGCCGGCG  2418683
Query= HWI-ST863:386:C5Y8UACXX:3:1302:8580:7972 1:N:0:ACACGAAT
 Identities = 100/100 (100%), Gaps = 0/100 (0%)
Sbjct  3178017  CCAGTTATGCTTGGGGCAGGTGAGCTTGTTGCCTTCCAGGGCGAGCTCGGGGATATCCGT  3178076
Query= HWI-ST863:386:C5Y8UACXX:3:1106:4759:9532 1:N:0:ACACGAAT
 Identities = 100/100 (100%), Gaps = 0/100 (0%)
Sbjct  32627  CGAGGCCGCGGTTTTGGACCTGGACGAGGGGAGTCGGCGTGTGAGTCTTGCGACCCTGGA  32686

(Corrected to print the fifth line down.)


问:
How to run Scala script using spark-submit (similarly to Python script)?
I try to execute a simple Scala script using Spark as described in the Spark Quick Start Tutorial. I have not troubles to execute the following Python code:

```<code>"""SimpleApp.py"""
from pyspark import SparkContext

logFile = "tmp.txt"  # Should be some file on your system
sc = SparkContext("local", "Simple App")
logData = sc.textFile(logFile).cache()

numAs = logData.filter(lambda s: 'a' in s).count()
numBs = logData.filter(lambda s: 'b' in s).count()

print "Lines with a: %i, lines with b: %i" % (numAs, numBs)
</code>```

I execute this code using the following command:

```<code>/home/aaa/spark/spark-2.1.0-bin-hadoop2.7/bin/spark-submit hello_world.py
</code>```

However, if I try to do the same using Scala, I have technical problems. In more detail, the code that I try to execute is:

```<code>* SimpleApp.scala */
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf

object SimpleApp {
  def main(args: Array[String]) {
    val logFile = "tmp.txt" // Should be some file on your system
    val conf = new SparkConf().setAppName("Simple Application")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()
    val numAs = logData.filter(line => line.contains("a")).count()
    val numBs = logData.filter(line => line.contains("b")).count()
    println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
  }
}
</code>```

I try to execute it in the following way:

```<code>/home/aaa/spark/spark-2.1.0-bin-hadoop2.7/bin/spark-submit hello_world.scala
</code>```

As the result I get the following error message:

```<code>Error: Cannot load main class from JAR file
</code>```

Does anybody know what I am doing wrong?

答:
Use spark-submit --help to know the options and arguments.

```<code>$ ./bin/spark-submit --help
Usage: spark-submit [options] <app jar | python file> [app arguments]
Usage: spark-submit --kill [submission ID] --master [spark://...]
Usage: spark-submit --status [submission ID] --master [spark://...]
Usage: spark-submit run-example [options] example-class [example args]
</code>```

As you can see in the first Usage spark-submit requires <app jar | python file>.

The app jar argument is a Spark application's jar with the main object (SimpleApp in your case).

You can build the app jar using sbt or maven that you can read in the official documentation's Self-Contained Applications:

Suppose we wish to write a self-contained application using the Spark API. We will walk through a simple application in Scala (with sbt), Java (with Maven), and Python.

and later in the section:

we can create a JAR package containing the application’s code, then use the spark-submit script to run our program.

p.s. Use Spark 2.1.1.

Body:
I try to execute a simple Scala script using Spark as described in the Spark Quick Start Tutorial. I have not troubles to execute the following Python code:

"""SimpleApp.py"""
from pyspark import SparkContext

logFile = "tmp.txt"  # Should be some file on your system
sc = SparkContext("local", "Simple App")
logData = sc.textFile(logFile).cache()

numAs = logData.filter(lambda s: 'a' in s).count()
numBs = logData.filter(lambda s: 'b' in s).count()

print "Lines with a: %i, lines with b: %i" % (numAs, numBs)

I execute this code using the following command:

/home/aaa/spark/spark-2.1.0-bin-hadoop2.7/bin/spark-submit hello_world.py

However, if I try to do the same using Scala, I have technical problems. In more detail, the code that I try to execute is:

* SimpleApp.scala */
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf

object SimpleApp {
  def main(args: Array[String]) {
    val logFile = "tmp.txt" // Should be some file on your system
    val conf = new SparkConf().setAppName("Simple Application")
    val sc = new SparkContext(conf)
    val logData = sc.textFile(logFile, 2).cache()
    val numAs = logData.filter(line => line.contains("a")).count()
    val numBs = logData.filter(line => line.contains("b")).count()
    println("Lines with a: %s, Lines with b: %s".format(numAs, numBs))
  }
}

I try to execute it in the following way:

/home/aaa/spark/spark-2.1.0-bin-hadoop2.7/bin/spark-submit hello_world.scala

As the result I get the following error message:

Error: Cannot load main class from JAR file

Does anybody know what I am doing wrong?

Body:
Use spark-submit --help to know the options and arguments.

$ ./bin/spark-submit --help
Usage: spark-submit [options] <app jar | python file> [app arguments]
Usage: spark-submit --kill [submission ID] --master [spark://...]
Usage: spark-submit --status [submission ID] --master [spark://...]
Usage: spark-submit run-example [options] example-class [example args]

As you can see in the first Usage spark-submit requires <app jar | python file>.

The app jar argument is a Spark application's jar with the main object (SimpleApp in your case).

You can build the app jar using sbt or maven that you can read in the official documentation's Self-Contained Applications:

Suppose we wish to write a self-contained application using the Spark API. We will walk through a simple application in Scala (with sbt), Java (with Maven), and Python.

and later in the section:

we can create a JAR package containing the application’s code, then use the spark-submit script to run our program.

p.s. Use Spark 2.1.1.


问:
Twitter API: is it possible to get number of retweets and number of media images?
Is it possible through the Twitter API to get the total number of retweets a user has? Not just on a specific post, but the total number of retweets associated with a specific account? Or alternatively, what fraction of all tweets were retweeted content rather than original posts?

Also, is it possible to get the number of media images associated with an an account? What I mean is, if you go to a user's page, on the lefthand side it will say something like "2,200 Photos and Videos". Thanks!

答:
Actually you can. From Twitter REST APIs: GET statuses/user_timeline:

There is a parameter called include_rts:

When set to false , the timeline will strip any native retweets (though they will still count toward both the maximal length of the timeline and the slice selected by the count parameter). Note: If you’re using the trim_user parameter in conjunction with include_rts, the retweets will still contain a full user object.

So if you want to get count of all retweets you need to set that value to true count all entities and then set it to false and then subtract those values and then you get number of retweets.

NOTE: Also set trim_user to true to get less data(omitting user info of each tweet)

If you want to get count of media, then you need to count all media entities in those tweets: Entities in Objects. To separate them by type, you need to look at the type attribute of each element of media attribute.


问:
Custom output resolution DuplicateOutput DXGI
I'm using AcquireNextFrame to make a screenshot of my desktop. Is it possible to set a dimension of the output image I want on the setup ?
I saw on the documentation this function IDXGIOutput::SetDisplaySurface that could help.
Here is my code :

```<code>//Here I init a output texture with less resolution
    D3D11_TEXTURE2D_DESC desc;
    desc.Width = 1280;
    desc.Height = 720;
    desc.MipLevels = desc.ArraySize = 1;
    desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    desc.SampleDesc.Count = 1;
    desc.Usage = D3D11_USAGE_DYNAMIC;
    desc.BindFlags = 0;
    desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
    desc.MiscFlags = 0;

    ID3D11Texture2D *pTexture = NULL;
    gDevice->CreateTexture2D(&desc, NULL, &pTexture);
    IDXGISurface *surface = nullptr;
    hr = gDevice->QueryInterface(__uuidof(IDXGISurface), reinterpret_cast<void **>(&pTexture));
    if (FAILED(hr))
        return;
    // Here I should make lDxgiOutput->setDisplaySurface(surface)
    hr = lDxgiOutput->GetDesc(&gOutputDesc);
    if (FAILED(hr))
        return;
    IDXGIOutput1 *lDxgiOutput1 = nullptr;
    hr = lDxgiOutput->QueryInterface(IID_PPV_ARGS(&lDxgiOutput1));
    if (FAILED(hr))
        return;
    lDxgiOutput->Release();
    hr = lDxgiOutput1->DuplicateOutput(gDevice, &gDeskDupl);
    if (FAILED(hr))
        return;
</code>```

My screen is 1920x1080 and I would like to get image in 1280x720 for example.
I'm getting an error on queryinterface function.
Can someone tell me what I'm missing ? Or is there any solution to customize the resolution easier ?
Thanks

答:
Desktop Duplication API gets you a copy of desktop as a texture with least overhead. That is, no scaling is included. You can grab frames and scale them down as you wish, but this is not what Desktop Duplication does or expected to do for you.

This question suggests a few ways (and the question is also related to Desktop Duplication):

Resizing a DXGI Resource or Texture2D in SharpDX

Additionally, you can use Media Foundation's Video Processor MFT, which is somewhat inflexible and has a possibly inconvenient form factor if you don't use Media Foundation otherwise, but properly set up scales using Direct3D 11 in efficient way performance-wise.

See also on another related API for GPU-enabled scaling:

DXVA Video Processing - Example 7: Stretching and Cropping Video

Body:
I'm using AcquireNextFrame to make a screenshot of my desktop. Is it possible to set a dimension of the output image I want on the setup ?
I saw on the documentation this function IDXGIOutput::SetDisplaySurface that could help.
Here is my code :

//Here I init a output texture with less resolution
    D3D11_TEXTURE2D_DESC desc;
    desc.Width = 1280;
    desc.Height = 720;
    desc.MipLevels = desc.ArraySize = 1;
    desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    desc.SampleDesc.Count = 1;
    desc.Usage = D3D11_USAGE_DYNAMIC;
    desc.BindFlags = 0;
    desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
    desc.MiscFlags = 0;

    ID3D11Texture2D *pTexture = NULL;
    gDevice->CreateTexture2D(&desc, NULL, &pTexture);
    IDXGISurface *surface = nullptr;
    hr = gDevice->QueryInterface(__uuidof(IDXGISurface), reinterpret_cast<void **>(&pTexture));
    if (FAILED(hr))
        return;
    // Here I should make lDxgiOutput->setDisplaySurface(surface)
    hr = lDxgiOutput->GetDesc(&gOutputDesc);
    if (FAILED(hr))
        return;
    IDXGIOutput1 *lDxgiOutput1 = nullptr;
    hr = lDxgiOutput->QueryInterface(IID_PPV_ARGS(&lDxgiOutput1));
    if (FAILED(hr))
        return;
    lDxgiOutput->Release();
    hr = lDxgiOutput1->DuplicateOutput(gDevice, &gDeskDupl);
    if (FAILED(hr))
        return;

My screen is 1920x1080 and I would like to get image in 1280x720 for example.
I'm getting an error on queryinterface function.
Can someone tell me what I'm missing ? Or is there any solution to customize the resolution easier ?
Thanks


问:
What is a "reference edge" in TensorBoard?
The TensorBoard UI shows something called a "Reference edge" as distinct from a data flow (Tensor) edge:

What distinguishes the former from the latter?

The documentation says that "the outgoing operation node can mutate the incoming tensor", but indicates different symbols that don't match the UI, so it's hard to tell what's meant by "incoming" and "outgoing":

For example how does this definition apply to

```<code>cs = tf.constant([1,2,3], name='const_share')
vs = tf.Variable([1,2,3], name='var_share')
tf.add(cs, vs, name='opVS1')
tf.add(vs, cs, name='opVS2')
</code>```

or to

```<code>tf.add([4],[3], name='opA')
</code>```

In both cases it just seems that the reference edge indicates that the value its tail fills the Tensor represented by the edge.

答:
In the graph that you showed, it looks like only edges connected to the "read" operator are undirected ones - dataflow edge, however, you can temporarily disconnect the read node by right click and "Remove from the main graph". Then it turned out that the edges turned from dataflow edge (undirected) to reference edge (directed), which does not make that much sense.

We probably need to count on someone who really understood javascript to figure out how this works by looking at the source code of tensorboard.

Body:
The TensorBoard UI shows something called a "Reference edge" as distinct from a data flow (Tensor) edge:

What distinguishes the former from the latter?

The documentation says that "the outgoing operation node can mutate the incoming tensor", but indicates different symbols that don't match the UI, so it's hard to tell what's meant by "incoming" and "outgoing":

For example how does this definition apply to

cs = tf.constant([1,2,3], name='const_share')
vs = tf.Variable([1,2,3], name='var_share')
tf.add(cs, vs, name='opVS1')
tf.add(vs, cs, name='opVS2')

or to

tf.add([4],[3], name='opA')

In both cases it just seems that the reference edge indicates that the value its tail fills the Tensor represented by the edge.


问:
show the values of string variables in a string array
I created an array of strings and I want to get the value of a given string at a given position, but the returned value is the character and not the string, eg:

```<code>myArray = ['string1' 'string2' 'string3'];
s = myArray(1); //returns the character at the position 1, instead of the string
</code>```

How can I get the value of these strings based on a given position i ?

答:
Try using a cell array:</p>

```<code>myArray = {'string1' 'string2' 'string3'};
s = myArray{1};
</code>```

Body:
I created an array of strings and I want to get the value of a given string at a given position, but the returned value is the character and not the string, eg:

myArray = ['string1' 'string2' 'string3'];
s = myArray(1); //returns the character at the position 1, instead of the string

How can I get the value of these strings based on a given position i ?

Body:
Try using a cell array:

myArray = {'string1' 'string2' 'string3'};
s = myArray{1};


问:
How can I schedule updates (f/e, to update a clock) in tkinter?
I'm writing a program with Python's tkinter library.

My major problem is that I don't know how to create a timer or a clock like hh:mm:ss.

I need it to update itself (that's what I don't know how to do); when I use time.sleep() in a loop the whole GUI freezes.

答:
I just created a simple timer using the MVP pattern (however it may be
overkill for that simple project). It has quit, start/pause and a stop button. Time is displayed in HH:MM:SS format. Time counting is implemented using a thread that is running several times a second and the difference between the time the timer has started and the current time.

Source code on github


问:
SQL Server Remote Tunnel Applications
I would like to know if there are some type of applications that allows me to access SQL Server in my local server remotely from a desktop application in one of my other branches through Internet;

I've already read about accessing it by using public IP; but that is too difficulty for me as I cant get public IP for my server easily. Plus I cant get access to the routers to set ports required;

Are there are other applications (even paid ones) that provide some sort of tunnels to access my SQL Server database remotely?

答:
You're not looking for a Sql Server solution here. Any generic correctly configured VPN solution will work. However that is not in and of itself an easy configuration and, depending on your business, your security department may expressly forbid.

Your best bet is to use some sort of Desktop sharing solution TBH, e.g. Splashtop, TeamViewer etc. Again, your security department may not be too happy with such a 'solution' either.

Title: SQL Server Remote Tunnel Applications


问:
Add a Custom Control reference in VS10
I recently created my first custom control. I attempted to add it in a separate project I have constructed.

I recieve this error:
  The type 'System.Windows.Controls.Control' is defined in an assembly that is not referenced. You must add a reference to assembly

Here are the steps I took to add the control.

Add the Custom Control as a Reference in project

Add the attribute   xmlns:MyNamespace="clr-namespace:CustomControls;assembly=CustomControls" to the root element of the markup file where it is being used

Rebuild the Controller and the project

答: You also need a reference to PresentationFramework.dll

Title: Add a Custom Control reference in VS10


问:
How to reload/refresh jQuery dataTable?
I am trying to implement functionality whereby clicking a button on the screen will cause my jQuery dataTable to refresh (as the server-side data source may have changed since the dataTable was created).

Here's what I have:

```<code>$(document).ready(function() {
    $("#my-button").click(function() {
        $("#my-datatable").dataTable().fnReloadAjax();
    });
});
</code>```

But when I run this, it does nothing. What's the proper way to refresh the dataTable when the button is clicked?

答:
```<code>function autoRefresh(){
    table.ajax.reload(null,false);
    alert('Refresh');//for test, uncomment
}

setInterval('autoRefresh()', 5000);
</code>```

Title: How to reload/refresh jQuery dataTable?

Body:
I am trying to implement functionality whereby clicking a button on the screen will cause my jQuery dataTable to refresh (as the server-side data source may have changed since the dataTable was created).

Here's what I have:

$(document).ready(function() {
    $("#my-button").click(function() {
        $("#my-datatable").dataTable().fnReloadAjax();
    });
});

But when I run this, it does nothing. What's the proper way to refresh the dataTable when the button is clicked?