问:
Java - Writing to XML file indents everything except the first element
Using JAVA, I am trying, after having opened a .xml file, to append the creation of a new node using a SWING Application. Every new node gets entered correctly EXCEPT the first element which always get stuck at the far left of the file, with no identation.

schedule.xml

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

<Schedule>
        <Lesson>
                <Title>Artificial Intelligence</Title>
                <Lecture>
                    <Day>Thursday</Day>
                </Lecture>
                <Professor>John Doe</Professor>
        </Lesson>
        <Lesson>
                <Title>Constraint Satisfaction Problems</Title>
                <Lecture>
                    <Day>Monday</Day>
                </Lecture>
        </Lesson>
</Schedule>
</code>```

My attempt to write to the file :

```<code>try {
                    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                    Document document = documentBuilder.parse("schedule.xml");
                    Element root = document.getDocumentElement();
                        Element newLesson = document.createElement("Lesson");

                        Element newTitle = document.createElement("Title");
                        newTitle.appendChild(document.createTextNode("myLesson"));
                        newLesson.appendChild(newTitle);

                        Element newLecture = document.createElement("Lecture");
                        newLesson.appendChild(newLecture);

                        Element newDay = document.createElement("Day");
                        newDay.appendChild(document.createTextNode("myDay"));
                        newLecture.appendChild(newDay);

                        Element newProfessor = document.createElement("Professor");
                        newProfessor.appendChild(document.createTextNode("myProfessor"));
                        newLesson.appendChild(newProfessor);

                        root.appendChild(newLesson);
                     DOMSource source = new DOMSource(document);
                     TransformerFactory transformerFactory = TransformerFactory.newInstance();
                     Transformer transformer = transformerFactory.newTransformer();
                     StreamResult result = new StreamResult("schedule.xml");
                     transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                     transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "8");
                     transformer.transform(source, result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
</code>```

Output

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Schedule>
        <Lesson>
                <Title>Artificial Intelligence</Title>
                <Lecture>
                    <Day>Thursday</Day>
                </Lecture>
                <Professor>John Doe</Professor>
        </Lesson>
        <Lesson>
                <Title>Constraint Satisfaction Problems</Title>
                <Lecture>
                    <Day>Monday</Day>
                </Lecture>
        </Lesson>
<Lesson>
            <Title>myLesson</Title>
            <Lecture>
                    <Day>myDay</Day>
            </Lecture>
            <Professor>myProfessor</Professor>
    </Lesson>
</Schedule>
</code>```

答:
Solution: used a function for space trimming from here

Function:

```<code>private static void removeEmptyText(Node node){
    Node child = node.getFirstChild();
    while(child!=null){
        Node sibling = child.getNextSibling();
        if(child.getNodeType()==Node.TEXT_NODE){
            if(child.getTextContent().trim().isEmpty())
                node.removeChild(child);
        }else
            removeEmptyText(child);
        child = sibling;
    }
}
</code>```

Body:
Using JAVA, I am trying, after having opened a .xml file, to append the creation of a new node using a SWING Application. Every new node gets entered correctly EXCEPT the first element which always get stuck at the far left of the file, with no identation.

schedule.xml

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

<Schedule>
        <Lesson>
                <Title>Artificial Intelligence</Title>
                <Lecture>
                    <Day>Thursday</Day>
                </Lecture>
                <Professor>John Doe</Professor>
        </Lesson>
        <Lesson>
                <Title>Constraint Satisfaction Problems</Title>
                <Lecture>
                    <Day>Monday</Day>
                </Lecture>
        </Lesson>
</Schedule>

My attempt to write to the file :

try {
                    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                    Document document = documentBuilder.parse("schedule.xml");
                    Element root = document.getDocumentElement();
                        Element newLesson = document.createElement("Lesson");

                        Element newTitle = document.createElement("Title");
                        newTitle.appendChild(document.createTextNode("myLesson"));
                        newLesson.appendChild(newTitle);

                        Element newLecture = document.createElement("Lecture");
                        newLesson.appendChild(newLecture);

                        Element newDay = document.createElement("Day");
                        newDay.appendChild(document.createTextNode("myDay"));
                        newLecture.appendChild(newDay);

                        Element newProfessor = document.createElement("Professor");
                        newProfessor.appendChild(document.createTextNode("myProfessor"));
                        newLesson.appendChild(newProfessor);

                        root.appendChild(newLesson);
                     DOMSource source = new DOMSource(document);
                     TransformerFactory transformerFactory = TransformerFactory.newInstance();
                     Transformer transformer = transformerFactory.newTransformer();
                     StreamResult result = new StreamResult("schedule.xml");
                     transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                     transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "8");
                     transformer.transform(source, result);
                } catch (Exception e) {
                    e.printStackTrace();
                }

Output

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Schedule>
        <Lesson>
                <Title>Artificial Intelligence</Title>
                <Lecture>
                    <Day>Thursday</Day>
                </Lecture>
                <Professor>John Doe</Professor>
        </Lesson>
        <Lesson>
                <Title>Constraint Satisfaction Problems</Title>
                <Lecture>
                    <Day>Monday</Day>
                </Lecture>
        </Lesson>
<Lesson>
            <Title>myLesson</Title>
            <Lecture>
                    <Day>myDay</Day>
            </Lecture>
            <Professor>myProfessor</Professor>
    </Lesson>
</Schedule>

Body:
Solution: used a function for space trimming from here

Function:

private static void removeEmptyText(Node node){
    Node child = node.getFirstChild();
    while(child!=null){
        Node sibling = child.getNextSibling();
        if(child.getNodeType()==Node.TEXT_NODE){
            if(child.getTextContent().trim().isEmpty())
                node.removeChild(child);
        }else
            removeEmptyText(child);
        child = sibling;
    }
}


来源: stackexchange

问:
Apple Enterprise app signing
How long the enterprise-signed ipa can be install on iOS devices?
A company which have enterprise developer account signed my app and charge me an amount. They said that this app can be installed on devices forever. Is this true or the app has a limited time for installing?</p>

答:
Assuming you are talking about the Enterprise In-House Distribution type, you have at most 1-3 years.  See details below, but with no other intervention, users will lose access to the app when the profile expires (at most 1 year).

The certificate used to sign an enterprise app will be valid for 3 years from time of creation. However, the provisioning profile that also is used to sign the app will be valid only for 1 year from when it is created.

If you take an app that is built and signed with a profile /cert both created on the day they sent it to you, you can run the app, as-is, on your device for 1 year.  Then the provisioning profile will expire, and if you have not somehow gotten a new provisioning profile on the device, the app will not launch.

There are multiple ways you can get a new provisioning profile on an iOS device without having to rebuild the app.  First, you can use an MDM prpduct to push a the new profile to the device.  Or, you could get another app, signed with the same certificate, but a newer provisioning profile, installed on the device.  As long as the profile is using a wildcard app ID, this will allow you to continue to run the app.  Note, however, that the original developer would need to provide you with either the new profile or another app signed with the new profile.

If you manage to renew your provisioning profile on the device to keep it running for 3 years, when the certificate expires, the only way to run the app will be to get a new application binary that has been signed with a new profile and certificate.  An expired certificate invalidates the binary and there will no way to ruin the app on the device without installing a new version that has been re-signed with a new cert / profile.  This also requires the original developer to provide you with the new signing identity files, or rebuild the app for you.

If you truly want to have the app build you an app that will run "forever" without signing problems, you should have them distribute the app through the App Store privately using Apple's B2B program: https://developer.apple.com/programs/volume/b2b/

Those apps will technically run on a device indefinitely, assuming you don't always update new versions of the OS / hardware. Note that when Apple releases major iOS updates, many apps will have problems where the apps will behave differently on iOS11 vs. iOS 10.  It is very unlikely that an app released in one year will still function properly 3 years later without some changes.  And they most certainly won't take advantage of new hardware / software features (like the iPhone X's taller screen).  Mobile app development is an ongoing cost / effort.

ContentLicense: CC BY-SA 3.0

Title: Apple Enterprise app signing


问:
Multilevel abstraction with interface and inheritance in Python
I'm not exactly sure how to phrase this question, hence the strange title. I also have not been able to find any information on this after searching, so hopefully this isn't a duplicate and I'm just searching for the wrong words. Anyhow, here is the situation, I have an abstract base class with some methods in it, which is inherited by a class. I don't want to set one of the methods in this base class, as this class is meant to be inherited by other classes to provide the common functionality they all share. Something like:

```<code>class A(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def fun1(self):
        pass

   @abc.abstractmethod
    def fun2(self):
        pass

class B(A):
    def fun1(self):
        #do work here

    @abc.abstractmethod
    def fun2(self):  # Intent to have the final classes define this
        pass

class C(B):
    def fun2(self):
        # do work here

class D(B):
    def fun2(self):
        # do work here
</code>```

I would like to keep the function as an ABC.meta to force implementation on the final children, but because there can be multiple types of class B in this case all inheriting from the interface, I want to keep the initial virtulization of the method at this root class, but have a way for class B to enforce that it's sub-classes must implement this. The code works just find if I don't add the abstract method to class B, but that is awkward since subclassess must implement the method and shouldn't have to look all the way up to the interface to figure out everything they need to implement. As written, it will error out because class B cannot declare the method as an abc.abstract. If I don't declare it as an abstract there is no way to enforce the child class has to implement the method.

I hope my convoluted way of writing this makes sense to someone out there...

Thanks!

答:
You probably should not redefine fun2 as an abstract method in the concrete class B.  You are creating a set of rules for your interface, but immediately violating them when you do that.

Instead, either define a mix-in class or an additional ABC that C and D can inherit.

```<code>class A(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def fun1(self):
        pass

class A2(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def fun2(self):
        pass

class B(A):
    def fun1(self):
        print('hello')

class B2(A2):
    def fun2(self):
        print('world')

class C(B, B2):
    pass

class D(B, B2):
    pass
</code>```

Body:
I'm not exactly sure how to phrase this question, hence the strange title. I also have not been able to find any information on this after searching, so hopefully this isn't a duplicate and I'm just searching for the wrong words. Anyhow, here is the situation, I have an abstract base class with some methods in it, which is inherited by a class. I don't want to set one of the methods in this base class, as this class is meant to be inherited by other classes to provide the common functionality they all share. Something like:

class A(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def fun1(self):
        pass

   @abc.abstractmethod
    def fun2(self):
        pass

class B(A):
    def fun1(self):
        #do work here

    @abc.abstractmethod
    def fun2(self):  # Intent to have the final classes define this
        pass

class C(B):
    def fun2(self):
        # do work here

class D(B):
    def fun2(self):
        # do work here

I would like to keep the function as an ABC.meta to force implementation on the final children, but because there can be multiple types of class B in this case all inheriting from the interface, I want to keep the initial virtulization of the method at this root class, but have a way for class B to enforce that it's sub-classes must implement this. The code works just find if I don't add the abstract method to class B, but that is awkward since subclassess must implement the method and shouldn't have to look all the way up to the interface to figure out everything they need to implement. As written, it will error out because class B cannot declare the method as an abc.abstract. If I don't declare it as an abstract there is no way to enforce the child class has to implement the method.

I hope my convoluted way of writing this makes sense to someone out there...

Thanks!

Body:
You probably should not redefine fun2 as an abstract method in the concrete class B.  You are creating a set of rules for your interface, but immediately violating them when you do that.

Instead, either define a mix-in class or an additional ABC that C and D can inherit.

class A(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def fun1(self):
        pass

class A2(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def fun2(self):
        pass

class B(A):
    def fun1(self):
        print('hello')

class B2(A2):
    def fun2(self):
        print('world')

class C(B, B2):
    pass

class D(B, B2):
    pass


问:
What's the influence of compiling ORACLE packages with DEBUG
we compile all our Oracle Packages with the DEBUG option enabled. This is the default for our IDE (PLSQLDeveloper). So when we compile a package in the background the following is executed:

```<code>ALTER PACKAGE emp_mgmt
   COMPILE DEBUG PACKAGE;
</code>```

I wonder if there are any performance consequences for this. The Oracle docs about ALTER PACKAGE do not mention anything about this.

答:
Oracle provides a Debug API for IDE developers. In the case that a Package is compiled with the DEBUG option, it is possible to set breaktpoints with that API. If you compiled all packages with the DEBUG option, someone can set a breakpoint via that API to manipulate the system!

So I think it is more an security issue than a preformance problem to compile Packages in debug mode.

EDIT:
SET_BREAKPOINT Function in the Oracle documentation

ContentLicense: CC BY-SA 2.5

Body:
we compile all our Oracle Packages with the DEBUG option enabled. This is the default for our IDE (PLSQLDeveloper). So when we compile a package in the background the following is executed:

ALTER PACKAGE emp_mgmt
   COMPILE DEBUG PACKAGE;

I wonder if there are any performance consequences for this. The Oracle docs about ALTER PACKAGE do not mention anything about this.


问:
Python script writes twice in to the tables
I am trying to automate this scenario. I have 2 .sql files (add1.sql and add2.sql) which has 1 insert script each.

My goal is to write one record to table1 by executing lines from add1.sql and one record to cm.cl by executing lines from add2.sql, waiting for about 5 mins so a backend service runs. This service writes from DB1 to DB2. I then connect to DB2 to see if the record from DB1 matches what was written to DB2. Depending no the results, an email is sent.

Below is my code. Everything works just fine except that it writes twice to DB1. So, basically 4 records are inserted instead of 2. Any idea why it writes 4 records?

```<code>import pypyodbc as pyodbc
import smtplib
sender = 'abc@abc.com'
receivers = ['abc@abc.com','xyz@abc.com']
import unittest
import time

class TestDB1(unittest.TestCase):

    def testing_master(self):

           Master_Conn = 'Driver=
 {SQLServer};Server=server\servername;Database=database;UID=userid;PWD=password'
           Master_db = pyodbc.connect(Master_Conn)
           Master_Cursor = Master_db.cursor()
           try:
               #Open, read and execute add_shell.sql
               file = open('C:\\aaa\\add1.sql', 'r')
               line = file.read()
               lines = line.replace('\n', ' ')
               file1 = open('C:\\aaa\\add2.sql', 'r')
               line1=file1.read()
               lines1=line1.replace('\n', ' ')
               Master_Cursor.execute(lines)
               time.sleep(1)
               Master_Cursor.execute(lines1)
               Master_db.commit()
               file.close()
               file1.close()

               #Get python object for latest record inserted in DB1
               Master_CID=Master_Cursor.execute("select col1 from tablename1 order by sequenceid desc").fetchone()
               #convert tuple to srting [0] gives first tuple element.
               Master_CID_str=str(Master_CID[0])
               #Get GUID by stripping first 2 chars and last char.
               Master_CID_str=Master_CID_str[2:len(Master_CID_str)-1]
               Master_CLID=Master_Cursor.execute("select col2 from tablename2 order by sequenceid desc").fetchone()
               Master_CLID_str=str(Master_CLID[0])
               Master_CLID_str=Master_CLID_str[2:len(Master_CLID_str) - 1]

           # Wait for service that transfers data from one db to another DB to run
               time.sleep(310)
           finally:
                Master_Cursor.close()
                Master_db.close()

           return Master_CID,Master_CID_str,Master_CLID,Master_CLID_str

    def testing_int_instance(self):
           #unpacking return value of tuple from testing_master() function
           Master_CID,Master_CID_str,Master_CLID,Master_CLID_str=self.testing_master()
           print ("printing from testing_int_instance {0}".format(Master_CID))
           Int_Instance_Conn = 'Driver={SQL Server};Server=server2\servername2;Database=database2;UID=uid;PWD=password;'
           Int_db = pyodbc.connect(Int_Instance_Conn)
           Int_Cursor = Int_db.cursor()
           #return Int_db, Int_Cursor
           #execute select from  db where col matches that of one inserted in master db.
           Int_Instance_CID=Int_Cursor.execute("select col1 from table1 where cartridgemodelid = '%s'" %(Master_CID_str)).fetchone()
           print(Int_Instance_CID)
           smtpObj = smtplib.SMTP('22.101.1.333', 25)
           if (Master_CID==Int_Instance_CID):
               print("Matched")
               content="This email confirms successful  data transfer from Master to  Instance for col1: \n"
               message = "\r\n".join(["From:" + sender,"To:" + str(receivers[:]),"Subject: Test Result","",content +Master_CID_str])
               #smtpObj = smtplib.SMTP('22.101.2.222', 25)
               smtpObj.sendmail(sender, receivers, message)
           elif (Master_CID!=Int_Instance_CID):
               print("no match")
               content = "This email confirms failure of  data transfer from DB1 to DB2 for COL1: \n"
               message = "\r\n".join(["From:" + sender, "To:" + str(receivers[:]), "Subject: Test Result", "",content +Master_CID_str])
               smtpObj.sendmail(sender, receivers, message)
           Int_Instance_CLID=Int_Cursor.execute("select COL2 from table2 where col= '%s'" %(Master_CLID_str)).fetchone()
           print (Int_Instance_CLID)
           if (Master_CLID == Int_Instance_CLID):
               print ("Printing int_instance CLID {0}".format(Int_Instance_CLID))
               content = "This email confirms successful data transfer from DB1 to DB2 for COL: \n"
               message = "\r\n".join(
                  ["From:" + sender, "To:" + str(receivers[:]), "Subject: Test Result", "", content + Master_CLID_str])
               #smtpObj = smtplib.SMTP('22.101.2.222', 25)
               smtpObj.sendmail(sender, receivers, message)
               print ("Ids Matched")
           elif (Master_CLID != Int_Instance_CLID):
DB1 to DB2 for COL: \n"
               message = "\r\n".join(
                  ["From:" + sender, "To:" + str(receivers[:]), "Subject: Test Result", "", content + Master_CLID_str])
               #smtpObj = smtplib.SMTP('22.101.2.222', 25)
               smtpObj.sendmail(sender, receivers, message)
           smtpObj.quit()

           Int_db.close()
</code>```

if name == 'main':
    unittest.main()

add1.sql is:

DECLARE @Name VARCHAR(2000)
DECLARE @PartNumber VARCHAR(2000)
SELECT @Name='test'+convert(varchar,getdate(),108)
SELECT @PartNumber='17_00001_'+convert(varchar,getdate(),108)
DECLARE @XML XML
DECLARE @FileName VARCHAR(1000)
DECLARE @Id UNIQUEIDENTIFIER
SELECT @Id = NEWID()
SELECT @FileName = 'test.xml'
SELECT @XML='<model>
   <xml tags go here>
BEGIN
  INSERT INTO table1
         (ID,Name,Type,Desc,Number,Revision,Model,status,Modifiedby,Modifiedon)
   VALUES(@Id,@Name,'xyz','',@partnumber,'01',@XML,'A','453454-4545-4545-4543-345342343',GETUTCDATE())
```

<p>add2.sql is:</p>

<pre class="lang-sql prettyprint-override"><code>DECLARE @XML XML
DECLARE @CM_Name VARCHAR(2000)
DECLARE @FileName VARCHAR(1000)
DECLARE @PartNumber VARCHAR(2000)
DECLARE @Id UNIQUEIDENTIFIER
SELECT @Id=NEWID()
DECLARE @Name VARCHAR(2000)
DECLARE @CMId VARCHAR(2000)
DECLARE @CM_PartName VARCHAR(2000)
DECLARE @CM_Partnumber VARCHAR(2000)
SELECT @Name='test'+convert(varchar,getdate(),108)
SELECT @PartNumber='test'+convert(varchar,getdate(),108)
DECLARE @RowCount INT
DECLARE @Message VARCHAR(100);

SELECT @FileName = 'test.xml'
SELECT @CMId = CM.CMID,
    @CM_Name = CM.CMName,
    @CM_PN  = CM.PN
    FROM cm.Model CM
    WHERE CM.MName LIKE 'test%'
    ORDER BY CM.ModifiedBy DESC
SELECT @XML='<Layout>
   other xml tags...

BEGIN
  INSERT INTO cm.CL(ID, ModelID, Layout, Description, PN, Revision, CLayout, Status, ModifiedBy, ModifiedOn)
    SELECT TOP 1 @Id, @CMId, @Name, '', @PartNumber, '01', @XML, 'A', '453454-345-4534-4534-4534543545', GETUTCDATE()
    FROM cm.table1 CM
    WHERE CM.Name=@CM_Name
    AND CM.Partnumber=@CM_Partnumber
</code>```

答:
Currently, you are calling test_master() twice! First as your named method and then in second method when you unpack the returned values. Below is a demonstration of defined methods outside of the Class object. If called as is, testing_master will run twice.

Consider also using a context manager to read .sql scripts using with() which handles open and close i/o operations shown below:

```<code># FIRST CALL
def testing_master():
    #...SAME CODE...
    try:
        with open('C:\\aaa\\add1.sql', 'r') as file:
            lines = file.read().replace('\n', ' ')
        Master_Cursor.execute(lines)
        Master_db.commit()

        time.sleep(1)

        with open('C:\\aaa\\add2.sql', 'r') as file1:
            lines1 = file1.read().replace('\n', ' ')
        Master_Cursor.execute(lines1)
        Master_db.commit()

    #...SAME CODE...
    return Master_CID, Master_CID_str, Master_CLID, Master_CLID_str

def testing_int_instance():
    # SECOND CALL
    Master_CID, Master_CID_str, Master_CLID, Master_CLID_str = testing_master()
    #...SAME CODE...

if __name__ == "__main__":
    testing_master()
    testing_int_instance()
</code>```

Commenting out the time(310) seems like it works but as you mention the background Windows service does not effectively run and so interrupts database transfer.

To resolve, consider calling the second method at the end of the first by passing the values as parameters without any return and remove unpacking line. Then, in the main global environment, only run testing_master(). Of course qualify with self when inside a Class definition.

```<code>def testing_master():
    #...SAME CODE...
    testing_int_instance(Master_CID, Master_CID_str, Master_CLID, Master_CLID_str)

def testing_int_instance(Master_CID, Master_CID_str, Master_CLID, Master_CLID_str):
    #...SKIP UNPACK LINE
    #...CONTINUE WITH SAME CODE...

if __name__ == "__main__":
    testing_master()
</code>```

Due to your unittest, consider slight adjustment to original setup where you qualify every variable with self:

```<code>def testing_master():
    ...
    self.Master_CID=Master_Cursor.execute("select col1 from tablename1 order by sequenceid desc").fetchone()
    self.Master_CID_str=str(Master_CID[0])
    self.Master_CID_str=Master_CID_str[2:len(Master_CID_str)-1]
    self.Master_CLID=Master_Cursor.execute("select col2 from tablename2 order by sequenceid desc").fetchone()
    self.Master_CLID_str=str(Master_CLID[0])
    self.Master_CLID_str=Master_CLID_str[2:len(Master_CLID_str) - 1]

def testing_int_instance(self):
    # NO UNPACK LINE
    # ADD self. TO EVERY Master_* VARIABLE
    ...
</code>```

Body:
I am trying to automate this scenario. I have 2 .sql files (add1.sql and add2.sql) which has 1 insert script each.

My goal is to write one record to table1 by executing lines from add1.sql and one record to cm.cl by executing lines from add2.sql, waiting for about 5 mins so a backend service runs. This service writes from DB1 to DB2. I then connect to DB2 to see if the record from DB1 matches what was written to DB2. Depending no the results, an email is sent.

Below is my code. Everything works just fine except that it writes twice to DB1. So, basically 4 records are inserted instead of 2. Any idea why it writes 4 records?

import pypyodbc as pyodbc
import smtplib
sender = 'abc@abc.com'
receivers = ['abc@abc.com','xyz@abc.com']
import unittest
import time

class TestDB1(unittest.TestCase):

    def testing_master(self):

           Master_Conn = 'Driver=
 {SQLServer};Server=server\servername;Database=database;UID=userid;PWD=password'
           Master_db = pyodbc.connect(Master_Conn)
           Master_Cursor = Master_db.cursor()
           try:
               #Open, read and execute add_shell.sql
               file = open('C:\\aaa\\add1.sql', 'r')
               line = file.read()
               lines = line.replace('\n', ' ')
               file1 = open('C:\\aaa\\add2.sql', 'r')
               line1=file1.read()
               lines1=line1.replace('\n', ' ')
               Master_Cursor.execute(lines)
               time.sleep(1)
               Master_Cursor.execute(lines1)
               Master_db.commit()
               file.close()
               file1.close()

               #Get python object for latest record inserted in DB1
               Master_CID=Master_Cursor.execute("select col1 from tablename1 order by sequenceid desc").fetchone()
               #convert tuple to srting [0] gives first tuple element.
               Master_CID_str=str(Master_CID[0])
               #Get GUID by stripping first 2 chars and last char.
               Master_CID_str=Master_CID_str[2:len(Master_CID_str)-1]
               Master_CLID=Master_Cursor.execute("select col2 from tablename2 order by sequenceid desc").fetchone()
               Master_CLID_str=str(Master_CLID[0])
               Master_CLID_str=Master_CLID_str[2:len(Master_CLID_str) - 1]

           # Wait for service that transfers data from one db to another DB to run
               time.sleep(310)
           finally:
                Master_Cursor.close()
                Master_db.close()

           return Master_CID,Master_CID_str,Master_CLID,Master_CLID_str

    def testing_int_instance(self):
           #unpacking return value of tuple from testing_master() function
           Master_CID,Master_CID_str,Master_CLID,Master_CLID_str=self.testing_master()
           print ("printing from testing_int_instance {0}".format(Master_CID))
           Int_Instance_Conn = 'Driver={SQL Server};Server=server2\servername2;Database=database2;UID=uid;PWD=password;'
           Int_db = pyodbc.connect(Int_Instance_Conn)
           Int_Cursor = Int_db.cursor()
           #return Int_db, Int_Cursor
           #execute select from  db where col matches that of one inserted in master db.
           Int_Instance_CID=Int_Cursor.execute("select col1 from table1 where cartridgemodelid = '%s'" %(Master_CID_str)).fetchone()
           print(Int_Instance_CID)
           smtpObj = smtplib.SMTP('22.101.1.333', 25)
           if (Master_CID==Int_Instance_CID):
               print("Matched")
               content="This email confirms successful  data transfer from Master to  Instance for col1: \n"
               message = "\r\n".join(["From:" + sender,"To:" + str(receivers[:]),"Subject: Test Result","",content +Master_CID_str])
               #smtpObj = smtplib.SMTP('22.101.2.222', 25)
               smtpObj.sendmail(sender, receivers, message)
           elif (Master_CID!=Int_Instance_CID):
               print("no match")
               content = "This email confirms failure of  data transfer from DB1 to DB2 for COL1: \n"
               message = "\r\n".join(["From:" + sender, "To:" + str(receivers[:]), "Subject: Test Result", "",content +Master_CID_str])
               smtpObj.sendmail(sender, receivers, message)
           Int_Instance_CLID=Int_Cursor.execute("select COL2 from table2 where col= '%s'" %(Master_CLID_str)).fetchone()
           print (Int_Instance_CLID)
           if (Master_CLID == Int_Instance_CLID):
               print ("Printing int_instance CLID {0}".format(Int_Instance_CLID))
               content = "This email confirms successful data transfer from DB1 to DB2 for COL: \n"
               message = "\r\n".join(
                  ["From:" + sender, "To:" + str(receivers[:]), "Subject: Test Result", "", content + Master_CLID_str])
               #smtpObj = smtplib.SMTP('22.101.2.222', 25)
               smtpObj.sendmail(sender, receivers, message)
               print ("Ids Matched")
           elif (Master_CLID != Int_Instance_CLID):
DB1 to DB2 for COL: \n"
               message = "\r\n".join(
                  ["From:" + sender, "To:" + str(receivers[:]), "Subject: Test Result", "", content + Master_CLID_str])
               #smtpObj = smtplib.SMTP('22.101.2.222', 25)
               smtpObj.sendmail(sender, receivers, message)
           smtpObj.quit()

           Int_db.close()

if name == 'main':
    unittest.main()

add1.sql is:

DECLARE @Name VARCHAR(2000)
DECLARE @PartNumber VARCHAR(2000)
SELECT @Name='test'+convert(varchar,getdate(),108)
SELECT @PartNumber='17_00001_'+convert(varchar,getdate(),108)
DECLARE @XML XML
DECLARE @FileName VARCHAR(1000)
DECLARE @Id UNIQUEIDENTIFIER
SELECT @Id = NEWID()
SELECT @FileName = 'test.xml'
SELECT @XML='<model>
   <xml tags go here>
BEGIN
  INSERT INTO table1
         (ID,Name,Type,Desc,Number,Revision,Model,status,Modifiedby,Modifiedon)
   VALUES(@Id,@Name,'xyz','',@partnumber,'01',@XML,'A','453454-4545-4545-4543-345342343',GETUTCDATE())

add2.sql is:

DECLARE @XML XML
DECLARE @CM_Name VARCHAR(2000)
DECLARE @FileName VARCHAR(1000)
DECLARE @PartNumber VARCHAR(2000)
DECLARE @Id UNIQUEIDENTIFIER
SELECT @Id=NEWID()
DECLARE @Name VARCHAR(2000)
DECLARE @CMId VARCHAR(2000)
DECLARE @CM_PartName VARCHAR(2000)
DECLARE @CM_Partnumber VARCHAR(2000)
SELECT @Name='test'+convert(varchar,getdate(),108)
SELECT @PartNumber='test'+convert(varchar,getdate(),108)
DECLARE @RowCount INT
DECLARE @Message VARCHAR(100);

SELECT @FileName = 'test.xml'
SELECT @CMId = CM.CMID,
    @CM_Name = CM.CMName,
    @CM_PN  = CM.PN
    FROM cm.Model CM
    WHERE CM.MName LIKE 'test%'
    ORDER BY CM.ModifiedBy DESC
SELECT @XML='<Layout>
   other xml tags...

BEGIN
  INSERT INTO cm.CL(ID, ModelID, Layout, Description, PN, Revision, CLayout, Status, ModifiedBy, ModifiedOn)
    SELECT TOP 1 @Id, @CMId, @Name, '', @PartNumber, '01', @XML, 'A', '453454-345-4534-4534-4534543545', GETUTCDATE()
    FROM cm.table1 CM
    WHERE CM.Name=@CM_Name
    AND CM.Partnumber=@CM_Partnumber

Body:
Currently, you are calling test_master() twice! First as your named method and then in second method when you unpack the returned values. Below is a demonstration of defined methods outside of the Class object. If called as is, testing_master will run twice.

Consider also using a context manager to read .sql scripts using with() which handles open and close i/o operations shown below:

# FIRST CALL
def testing_master():
    #...SAME CODE...
    try:
        with open('C:\\aaa\\add1.sql', 'r') as file:
            lines = file.read().replace('\n', ' ')
        Master_Cursor.execute(lines)
        Master_db.commit()

        time.sleep(1)

        with open('C:\\aaa\\add2.sql', 'r') as file1:
            lines1 = file1.read().replace('\n', ' ')
        Master_Cursor.execute(lines1)
        Master_db.commit()

    #...SAME CODE...
    return Master_CID, Master_CID_str, Master_CLID, Master_CLID_str

def testing_int_instance():
    # SECOND CALL
    Master_CID, Master_CID_str, Master_CLID, Master_CLID_str = testing_master()
    #...SAME CODE...

if __name__ == "__main__":
    testing_master()
    testing_int_instance()

Commenting out the time(310) seems like it works but as you mention the background Windows service does not effectively run and so interrupts database transfer.

To resolve, consider calling the second method at the end of the first by passing the values as parameters without any return and remove unpacking line. Then, in the main global environment, only run testing_master(). Of course qualify with self when inside a Class definition.

def testing_master():
    #...SAME CODE...
    testing_int_instance(Master_CID, Master_CID_str, Master_CLID, Master_CLID_str)

def testing_int_instance(Master_CID, Master_CID_str, Master_CLID, Master_CLID_str):
    #...SKIP UNPACK LINE
    #...CONTINUE WITH SAME CODE...

if __name__ == "__main__":
    testing_master()

Due to your unittest, consider slight adjustment to original setup where you qualify every variable with self:

def testing_master():
    ...
    self.Master_CID=Master_Cursor.execute("select col1 from tablename1 order by sequenceid desc").fetchone()
    self.Master_CID_str=str(Master_CID[0])
    self.Master_CID_str=Master_CID_str[2:len(Master_CID_str)-1]
    self.Master_CLID=Master_Cursor.execute("select col2 from tablename2 order by sequenceid desc").fetchone()
    self.Master_CLID_str=str(Master_CLID[0])
    self.Master_CLID_str=Master_CLID_str[2:len(Master_CLID_str) - 1]

def testing_int_instance(self):
    # NO UNPACK LINE
    # ADD self. TO EVERY Master_* VARIABLE
    ...


问:
Converting XML to CSV
I am new to go and trying to write a script to convert a SOAP response (currently stored as an xml file) and convert it to CSV.

Here is a copy of my xml

```<code><?xml version="1.0" encoding="UTF-8" ?>
<Data>
    <Results>
        <Client>
            <ID>72rere341</ID>
        </Client>
        <PartnerKey xsi:nil="true" />
        <PartnerProperties>
            <Name>email</Name>
            <Value>example1@test1.com</Value>
        </PartnerProperties>
        <ID>755454475</ID>
        <ObjectID xsi:nil="true" />
        <UserID>5fd0acfc-6crerfrgrfe6e9a675f65</UserID>
        <ActiveFlag>true</ActiveFlag>
        <Delete>0</Delete>
        <LastSuccessfulLogin>2014-11-07T16:00:46.747</LastSuccessfulLogin>
    </Results>
    <Results>
        <Client>
            <ID>72rere5341</ID>
        </Client>
        <PartnerKey xsi:nil="true" />
        <PartnerProperties>
            <Name>email</Name>
            <Value>example2@test1.com</Value>
        </PartnerProperties>
        <ID>7225483</ID>
        <ObjectID xsi:nil="true" />
        <UserID>example2@test1.com</UserID>
        <ActiveFlag>false</ActiveFlag>
        <Delete>0</Delete>
        <LastSuccessfulLogin>2015-04-29T05:01:27.85</LastSuccessfulLogin>
    </Results>
</Data>
</code>```

Here is a copy of my code

```<code>package main

import (
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "log"
    "os"

)

type AccountUser struct {
    UserID              string
    ActiveFlag          string
    LastSuccessfulLogin string
    //PartnerProperties   Partner `xml:"PartnerProperties"`
}

type Partner struct {
    Name  string
    Value string
}

type Query struct {
    ResultList []AccountUser `xml:"Results"`
}

func main() {
    xmlFile, err := os.Open("ActiveUsers.xml")
    if err != nil {
        fmt.Println("Error opening file:", err)

        return
    }
    defer xmlFile.Close()

    b, err := ioutil.ReadAll(xmlFile)
    if err != nil {
        log.Fatal(err)
    }

    var q Query
    err = xml.Unmarshal(b, &q)
    if err != nil {
        log.Fatal(err)
    }

     file, err := os.Create("result.csv")
    checkError("Cannot create file", err)
    defer file.Close()

    writer := csv.NewWriter(file)
    defer writer.Flush()

    for _, result := range q.ResultList  {
        err := writer.Write(result)
        checkError("Cannot write to file", err)
    }

}

func checkError(message string, err error) {
    if err != nil {
        log.Fatal(message, err)
    }

}
</code>```

When I run this, I get this error:

./ActiveUsers.go:73:28: cannot use result (type AccountUser) as type
  []string in argument to writer.Write

I have a feel I might need to covert this to bytes or another data structure but unsure of how to do so.

I will appreciate any pointers on this.

答:
csv.Writer writes rows to a CSV file, which it receives as a slice of strings ([]string). If you want to write a struct as a row in a CSV file, you must create a []string containing whatever fields you want included, converted to strings, in the order you want them to appear in columns in the CSV file, e.g.:

```<code>for _, result := range q.ResultList  {
    err := writer.Write([]string{result.UserID, result.ActiveFlag, result.LastSuccessfulLogin})
    checkError("Cannot write to file", err)
}
</code>```

Title: Converting XML to CSV

Body:
I am new to go and trying to write a script to convert a SOAP response (currently stored as an xml file) and convert it to CSV.

Here is a copy of my xml

<?xml version="1.0" encoding="UTF-8" ?>
<Data>
    <Results>
        <Client>
            <ID>72rere341</ID>
        </Client>
        <PartnerKey xsi:nil="true" />
        <PartnerProperties>
            <Name>email</Name>
            <Value>example1@test1.com</Value>
        </PartnerProperties>
        <ID>755454475</ID>
        <ObjectID xsi:nil="true" />
        <UserID>5fd0acfc-6crerfrgrfe6e9a675f65</UserID>
        <ActiveFlag>true</ActiveFlag>
        <Delete>0</Delete>
        <LastSuccessfulLogin>2014-11-07T16:00:46.747</LastSuccessfulLogin>
    </Results>
    <Results>
        <Client>
            <ID>72rere5341</ID>
        </Client>
        <PartnerKey xsi:nil="true" />
        <PartnerProperties>
            <Name>email</Name>
            <Value>example2@test1.com</Value>
        </PartnerProperties>
        <ID>7225483</ID>
        <ObjectID xsi:nil="true" />
        <UserID>example2@test1.com</UserID>
        <ActiveFlag>false</ActiveFlag>
        <Delete>0</Delete>
        <LastSuccessfulLogin>2015-04-29T05:01:27.85</LastSuccessfulLogin>
    </Results>
</Data>

Here is a copy of my code

package main

import (
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "log"
    "os"

)

type AccountUser struct {
    UserID              string
    ActiveFlag          string
    LastSuccessfulLogin string
    //PartnerProperties   Partner `xml:"PartnerProperties"`
}

type Partner struct {
    Name  string
    Value string
}

type Query struct {
    ResultList []AccountUser `xml:"Results"`
}

func main() {
    xmlFile, err := os.Open("ActiveUsers.xml")
    if err != nil {
        fmt.Println("Error opening file:", err)

        return
    }
    defer xmlFile.Close()

    b, err := ioutil.ReadAll(xmlFile)
    if err != nil {
        log.Fatal(err)
    }

    var q Query
    err = xml.Unmarshal(b, &q)
    if err != nil {
        log.Fatal(err)
    }

     file, err := os.Create("result.csv")
    checkError("Cannot create file", err)
    defer file.Close()

    writer := csv.NewWriter(file)
    defer writer.Flush()

    for _, result := range q.ResultList  {
        err := writer.Write(result)
        checkError("Cannot write to file", err)
    }

}

func checkError(message string, err error) {
    if err != nil {
        log.Fatal(message, err)
    }

}

When I run this, I get this error:

./ActiveUsers.go:73:28: cannot use result (type AccountUser) as type
  []string in argument to writer.Write

I have a feel I might need to covert this to bytes or another data structure but unsure of how to do so.

I will appreciate any pointers on this.

Body:
csv.Writer writes rows to a CSV file, which it receives as a slice of strings ([]string). If you want to write a struct as a row in a CSV file, you must create a []string containing whatever fields you want included, converted to strings, in the order you want them to appear in columns in the CSV file, e.g.:

for _, result := range q.ResultList  {
    err := writer.Write([]string{result.UserID, result.ActiveFlag, result.LastSuccessfulLogin})
    checkError("Cannot write to file", err)
}


问:
Eclipse always Building workspace
Normally when we check Project->Build automatically, it will build when our project's source has change, But when i check this option my eclipse is always building-- about every 2 or 3 seconds-- no matter it has changes or not. I can see from the right bottom state bar show "building workspace...".

It's annoying that this behavior drive my eclispe really slow and the CPU is always in high usage.

I'm using eclipse 3.7 for java EE developers, m2e, maven integration for WTP, git plugin, subclipse and Google plugin for eclipse, checkstyle, findbugs, etc.

Any ideas?

P.S I'm on Win 7 with 8GB RAM

答:
I just disabled my project to build automatically. Really annoying to be in that endless loop.

Goto:

Project->Build automatically

Title: Eclipse always Building workspace


问:
Xcode 8.2.1+ Fails Building : Invalid bitcode signature
So after updating my Xcode from 8.2.1 to any new version, I'm unable to build/run my project. This is the error that I'm getting..

```<code>Ld Smash_Anarchy.build/Deployment-iphoneos/Smash\ Anarchy.build/Objects-normal/arm64/Smash\ Anarchy normal arm64
cd /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS
export IPHONEOS_DEPLOYMENT_TARGET=8.0
export PATH="/Users/henrik/Desktop/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Users/henrik/Desktop/Xcode-beta.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Users/henrik/Desktop/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -arch arm64 -isysroot /Users/henrik/Desktop/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.1.sdk -L/Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS -F/Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS -filelist /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/Smash_Anarchy.build/Deployment-iphoneos/Smash\ Anarchy.build/Objects-normal/arm64/Smash\ Anarchy.LinkFileList -miphoneos-version-min=8.0 -dead_strip -Xlinker -object_path_lto -Xlinker /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/Smash_Anarchy.build/Deployment-iphoneos/Smash\ Anarchy.build/Objects-normal/arm64/Smash\ Anarchy_lto.o -Xlinker -final_output -Xlinker /Applications/Smash\ Anarchy.app/Smash\ Anarchy -fobjc-link-runtime -ObjC -framework SafariServices -weak_framework GLKit -weak_framework CoreBluetooth -weak_framework JavaScriptCore -weak_framework WebKit -licucore -weak_framework AddressBook -lsqlite3 -lc++ -weak_framework GoogleToolboxForMac -weak_framework FirebaseAnalytics -weak_framework FirebaseAuth -weak_framework FirebaseCore -weak_framework FirebaseCoreDiagnostics -weak_framework FirebaseCrash -weak_framework FirebaseDatabase -weak_framework FirebaseDynamicLinks -weak_framework FirebaseInstanceID -weak_framework FirebaseNanoPB -weak_framework GTMSessionFetcher -weak-lxml2 -weak-lz -weak_framework Accelerate -weak_framework Accounts -weak_framework AddressBookUI -weak_framework AdSupport -weak_framework AssetsLibrary -framework AudioToolbox -weak_framework CoreAudio -lGoogleAnalyticsServices -weak_framework CoreData -weak_framework CoreFoundation -weak_framework CoreImage -weak_framework CoreMIDI -framework Appodeal -weak_framework CoreMotion -weak_framework CoreTelephony -weak_framework CoreText -framework CoreVideo -weak_framework EventKit -weak_framework EventKitUI -weak_framework ExternalAccessory -weak_framework iAd -weak_framework ImageIO -weak_framework MediaToolbox -weak_framework MobileCoreServices -weak_framework NewsstandKit -framework OpenAL -weak_framework QuickLook -weak_framework Security -weak_framework Social -weak_framework StoreKit -weak_framework SystemConfiguration -weak_framework Twitter -weak_framework AVFoundation -framework CFNetwork -framework CoreGraphics -weak_framework CoreLocation -weak_framework CoreMedia -framework Foundation -framework FirebaseRemoteConfig -weak_framework GameKit -framework MediaPlayer -weak_framework MessageUI -weak_framework OpenGLES -framework QuartzCore -framework UIKit /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/S3DClient_iOS.a -framework Protobuf /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/Plugins/jpCloudEnvironment_iOS.a /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/Plugins/jpEventQueue_iOS.a -Xlinker -dependency_info -Xlinker /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/Smash_Anarchy.build/Deployment-iphoneos/Smash\ Anarchy.build/Objects-normal/arm64/Smash\ Anarchy_dependency_info.dat -o /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/Smash_Anarchy.build/Deployment-iphoneos/Smash\ Anarchy.build/Objects-normal/arm64/Smash\ Anarchy

error: Invalid bitcode signature
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Any idea how to get rid of this error? My bitcode isn't even on. I've tried enabling, disabling it, cleaning the derived data, cleaning project, restarting Xcode, setting the "Build Active Architecture Only" to YES, and NO.. nothing helped... I'm not using pod...
Any idea how to find the reason of this error?
Thanks!

答:
Here's what I did to fix this (Xcode 9.0):

"Update project to recommended settings" - for both the project and Cococapods. I was seeing this when trying to build for iOS 8 and 9 only so I think it had something to do with my old project's cocoapods having iOS 7 as a deployment target.

Clean

Quit Xcode

Delete build folder

Delete derived data

When I reopened Xcode it built fine.

Body:
So after updating my Xcode from 8.2.1 to any new version, I'm unable to build/run my project. This is the error that I'm getting..

Ld Smash_Anarchy.build/Deployment-iphoneos/Smash\ Anarchy.build/Objects-normal/arm64/Smash\ Anarchy normal arm64
cd /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS
export IPHONEOS_DEPLOYMENT_TARGET=8.0
export PATH="/Users/henrik/Desktop/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Users/henrik/Desktop/Xcode-beta.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Users/henrik/Desktop/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -arch arm64 -isysroot /Users/henrik/Desktop/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.1.sdk -L/Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS -F/Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS -filelist /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/Smash_Anarchy.build/Deployment-iphoneos/Smash\ Anarchy.build/Objects-normal/arm64/Smash\ Anarchy.LinkFileList -miphoneos-version-min=8.0 -dead_strip -Xlinker -object_path_lto -Xlinker /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/Smash_Anarchy.build/Deployment-iphoneos/Smash\ Anarchy.build/Objects-normal/arm64/Smash\ Anarchy_lto.o -Xlinker -final_output -Xlinker /Applications/Smash\ Anarchy.app/Smash\ Anarchy -fobjc-link-runtime -ObjC -framework SafariServices -weak_framework GLKit -weak_framework CoreBluetooth -weak_framework JavaScriptCore -weak_framework WebKit -licucore -weak_framework AddressBook -lsqlite3 -lc++ -weak_framework GoogleToolboxForMac -weak_framework FirebaseAnalytics -weak_framework FirebaseAuth -weak_framework FirebaseCore -weak_framework FirebaseCoreDiagnostics -weak_framework FirebaseCrash -weak_framework FirebaseDatabase -weak_framework FirebaseDynamicLinks -weak_framework FirebaseInstanceID -weak_framework FirebaseNanoPB -weak_framework GTMSessionFetcher -weak-lxml2 -weak-lz -weak_framework Accelerate -weak_framework Accounts -weak_framework AddressBookUI -weak_framework AdSupport -weak_framework AssetsLibrary -framework AudioToolbox -weak_framework CoreAudio -lGoogleAnalyticsServices -weak_framework CoreData -weak_framework CoreFoundation -weak_framework CoreImage -weak_framework CoreMIDI -framework Appodeal -weak_framework CoreMotion -weak_framework CoreTelephony -weak_framework CoreText -framework CoreVideo -weak_framework EventKit -weak_framework EventKitUI -weak_framework ExternalAccessory -weak_framework iAd -weak_framework ImageIO -weak_framework MediaToolbox -weak_framework MobileCoreServices -weak_framework NewsstandKit -framework OpenAL -weak_framework QuickLook -weak_framework Security -weak_framework Social -weak_framework StoreKit -weak_framework SystemConfiguration -weak_framework Twitter -weak_framework AVFoundation -framework CFNetwork -framework CoreGraphics -weak_framework CoreLocation -weak_framework CoreMedia -framework Foundation -framework FirebaseRemoteConfig -weak_framework GameKit -framework MediaPlayer -weak_framework MessageUI -weak_framework OpenGLES -framework QuartzCore -framework UIKit /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/S3DClient_iOS.a -framework Protobuf /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/Plugins/jpCloudEnvironment_iOS.a /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/Plugins/jpEventQueue_iOS.a -Xlinker -dependency_info -Xlinker /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/Smash_Anarchy.build/Deployment-iphoneos/Smash\ Anarchy.build/Objects-normal/arm64/Smash\ Anarchy_dependency_info.dat -o /Users/henrik/Desktop/iOS_Workspace/SmashAnarchy/Smash_Anarchy_iOS/Smash_Anarchy.build/Deployment-iphoneos/Smash\ Anarchy.build/Objects-normal/arm64/Smash\ Anarchy

error: Invalid bitcode signature
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Any idea how to get rid of this error? My bitcode isn't even on. I've tried enabling, disabling it, cleaning the derived data, cleaning project, restarting Xcode, setting the "Build Active Architecture Only" to YES, and NO.. nothing helped... I'm not using pod...
Any idea how to find the reason of this error?
Thanks!


问:
ios architecture versions - same code
Are different iOS architecture binary files the same overall code, or can they be different.

If I was to check certain things on these binaries, e.g PIE, ARC, or strings such as memcpy etc. Do I need to check both thin binaries for the same things, or are they the same just with different memory addresses?

e.g a fat binary consisting of armv7 and arm64, if the armv7 binary has PIE enabled, so will the arm64?

if the armv7 binary uses strcpy, the arm64 binary will also use strcpy?

Example for further clarification: Both binaries contain the same findings, which means as below in TLDR? Same code, just compiled differently per arch.

```<code>armv7
0x001e7e44   665 _memcpy
0x001e7ea4   770 _strlen
0x001e7eac   772 _strncpy
0x001e85b4   665 _memcpy

arm64
0x00000001001be7f0   645 _memcpy
0x00000001001be904   746 _strlen
0x00000001001be91c   748 _strncpy
0x0000000100220f18   645 _memcpy
</code>```

TLDR; are 2 iOS binaries the same code, just compiled differently depending on the architecture?

答:
Fat binaries contain multiple independent Mach-O files, which don't need to have anything in common at all.

When compiling binaries for just one platform, that fact hardly ever becomes apparent, but when building a cross-platform binary (common for some research tools to run both on macOS and jailbroken iDevices), there's not really any way around doing it manually:

```<code>gcc -o program.macos program.c
xcrun -sdk iphoneos gcc -arch armv7 -arch arm64 -o program.ios program.c
lipo -create -output program program.macos program.ios
</code>```

Now, normally multiple slices of a fat Mach-O contain the same codebase compiled for different architectures - after all, that's the intended use. That is no requirement however, as you can staple entirely different object files together (disclaimer: answer by me). But as I've written in that post, doing that is of very limited use, since you have no control over the slice that is chosen.

Subtle differences are quite common though, and can arise from e.g. C code like this:

```<code>void some_function(void)
{
#if __LP64__
    // do something
#else
    // do something else
#endif
}
</code>```

Examples I know include use of the (officially forbidden) IOKit framework, where the io_* functions are exported on 32-bit but not on 64-bit, which allowed simple imports on the former but demanded homebrew dlsym()-style scanning code on the latter.

In conclusion:

Are the slices of a different Mach-O usually compiled from the same code base? Yes.

Should they be? Yes.

Is that in any way guaranteed? No.

Title: ios architecture versions - same code

Body:
Are different iOS architecture binary files the same overall code, or can they be different.

If I was to check certain things on these binaries, e.g PIE, ARC, or strings such as memcpy etc. Do I need to check both thin binaries for the same things, or are they the same just with different memory addresses?

e.g a fat binary consisting of armv7 and arm64, if the armv7 binary has PIE enabled, so will the arm64?

if the armv7 binary uses strcpy, the arm64 binary will also use strcpy?

Example for further clarification: Both binaries contain the same findings, which means as below in TLDR? Same code, just compiled differently per arch.

armv7
0x001e7e44   665 _memcpy
0x001e7ea4   770 _strlen
0x001e7eac   772 _strncpy
0x001e85b4   665 _memcpy

arm64
0x00000001001be7f0   645 _memcpy
0x00000001001be904   746 _strlen
0x00000001001be91c   748 _strncpy
0x0000000100220f18   645 _memcpy

TLDR; are 2 iOS binaries the same code, just compiled differently depending on the architecture?

Body:
Fat binaries contain multiple independent Mach-O files, which don't need to have anything in common at all.

When compiling binaries for just one platform, that fact hardly ever becomes apparent, but when building a cross-platform binary (common for some research tools to run both on macOS and jailbroken iDevices), there's not really any way around doing it manually:

gcc -o program.macos program.c
xcrun -sdk iphoneos gcc -arch armv7 -arch arm64 -o program.ios program.c
lipo -create -output program program.macos program.ios

Now, normally multiple slices of a fat Mach-O contain the same codebase compiled for different architectures - after all, that's the intended use. That is no requirement however, as you can staple entirely different object files together (disclaimer: answer by me). But as I've written in that post, doing that is of very limited use, since you have no control over the slice that is chosen.

Subtle differences are quite common though, and can arise from e.g. C code like this:

void some_function(void)
{
#if __LP64__
    // do something
#else
    // do something else
#endif
}

Examples I know include use of the (officially forbidden) IOKit framework, where the io_* functions are exported on 32-bit but not on 64-bit, which allowed simple imports on the former but demanded homebrew dlsym()-style scanning code on the latter.

In conclusion:

Are the slices of a different Mach-O usually compiled from the same code base? Yes.

Should they be? Yes.

Is that in any way guaranteed? No.


问:
Multiple Input lines java
I want to write a program that reads this input:

```<code>1
3
9
16
25
17
150312
0.5
13.8
2.4
</code>```

and it should output this:

```<code>1.00,1.00
3.00,1.73
9.00,3.00
16.00,4.00
25.00,5.00
17.00,4.12
150312.00,387.70
0.50,0.71
13.80,3.71
2.40,1.55
</code>```

My Code is this:

```<code>import java.util.Scanner;

public class SqrtTable {

    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        if(StdIn.isEmpty()==true) {
        }
        else {
            output(s);
        }
    }

    public static void output(Scanner s) {
        double a = StdIn.readDouble();
//
        StdOut.printf("%.2f, %.2f", a, Math.sqrt(a));
//      System.out.println(a);
        StdIn.readLine();
    }
}
</code>```

My Code only puts out the first line.
What do I have to change?

答:
By something like this</p>

```<code>String[] splited = str.split("\\s+");
for(String s : splited){
System.out.println(s);
}
</code>```

Title: Multiple Input lines java

Body:
I want to write a program that reads this input:

1
3
9
16
25
17
150312
0.5
13.8
2.4

and it should output this:

1.00,1.00
3.00,1.73
9.00,3.00
16.00,4.00
25.00,5.00
17.00,4.12
150312.00,387.70
0.50,0.71
13.80,3.71
2.40,1.55

My Code is this:

import java.util.Scanner;

public class SqrtTable {

    public static void main(String args[]) {
        Scanner s = new Scanner(System.in);
        if(StdIn.isEmpty()==true) {
        }
        else {
            output(s);
        }
    }

    public static void output(Scanner s) {
        double a = StdIn.readDouble();
//
        StdOut.printf("%.2f, %.2f", a, Math.sqrt(a));
//      System.out.println(a);
        StdIn.readLine();
    }
}

My Code only puts out the first line.
What do I have to change?

Body:
By something like this

String[] splited = str.split("\\s+");
for(String s : splited){
System.out.println(s);
}


问:
Passing Boolean value as a String to a method expecting a String
In Ruby, I'm attempting to pass a boolean result to a method which accepts as a string as a parameter. This is as an experiment.

```<code>fileexists = File.file?("#{$fileLocation}")

puts File.file?("#{$fileLocation}")
puts fileexists
puts fileexists.to_s
</code>```

This will result in:

```<code>true
true
true
</code>```

Now if I attempt to call a method which accepts a string and pass this parameter in a number of ways.

```<code>slack(message: "#{fileexists}")
</code>```

Results in the error message.

```<code>'message' value must be a String! Found TrueClass instead.
</code>```

Which confuses me as I understand that Ruby evaluates anything within "" as a String. So placing a TrueClass object within a placeholder, should effectively cast this value to a string.

So let's try something slightly different:

```<code>slack(message: "#{fileexists.to_s}")
</code>```

This results in the same error.

```<code>'message' value must be a String! Found TrueClass instead.
</code>```

Now this is where things GET REALLY WEIRD!!

```<code>slack(message: "#{fileexists.to_s} ")
slack(message: "#{fileexists} ")
</code>```

If I add a single bit of whitespace to the end of the string after the placeholder, it passes, and a slack message is sent my way, displaying 'true'.

I understand I may be asking for a bit of 'Crystal-ball' insight here as
I don't have the implementation of the 'slack' method, and this may be a result of the way that's implemented.

Does Ruby check types of params as they're passed like this?

Is that a Ruby standard error message you might receive, or a custom error thrown by the slack() method?

答:
I understand I may be asking for a bit of 'Crystal-ball' insight here as I don't have the implementation of the 'slack' method, and this may be a result of the way that's implemented.

Sounds like youre using a lib (gem) which contains the methods slack, you can check the gem code location running gem which gem_name on your console.

Does Ruby check types of params as they're passed like this?

No

Is that a Ruby standard error message you might receive, or a custom error thrown by the slack() method?

Custom Error

As Jorg W Mittag stated this looks like a misimplementation of slack method when trying to deserialize, and then checking the types. You could fix the slack method on the gem by contributing to this gem, monkeypatch it or you can try to hack it the way it is... this last onde depends on how slack was implemented, maybe adding an extra pair of quotes, like "\"#{fileexists}\""

PS: You don't have to embbed the string inside another string if you're going to use it as it is, like fileexists = File.file? $fileLocation , this should work.

Body:
In Ruby, I'm attempting to pass a boolean result to a method which accepts as a string as a parameter. This is as an experiment.

fileexists = File.file?("#{$fileLocation}")

puts File.file?("#{$fileLocation}")
puts fileexists
puts fileexists.to_s

This will result in:

true
true
true

Now if I attempt to call a method which accepts a string and pass this parameter in a number of ways.

slack(message: "#{fileexists}")

Results in the error message.

'message' value must be a String! Found TrueClass instead.

Which confuses me as I understand that Ruby evaluates anything within "" as a String. So placing a TrueClass object within a placeholder, should effectively cast this value to a string.

So let's try something slightly different:

slack(message: "#{fileexists.to_s}")

This results in the same error.

'message' value must be a String! Found TrueClass instead.

Now this is where things GET REALLY WEIRD!!

slack(message: "#{fileexists.to_s} ")
slack(message: "#{fileexists} ")

If I add a single bit of whitespace to the end of the string after the placeholder, it passes, and a slack message is sent my way, displaying 'true'.

I understand I may be asking for a bit of 'Crystal-ball' insight here as
I don't have the implementation of the 'slack' method, and this may be a result of the way that's implemented.

Does Ruby check types of params as they're passed like this?

Is that a Ruby standard error message you might receive, or a custom error thrown by the slack() method?


问:
Play 2.4 dependency injection forgets about builtin classes in unit tests if modules are added
We're migrating our Java-only Play application from Play 2.4 to Play 2.5. First step: Get rid of GlobalSettings, still completely in the 2.4 realm. I wrote some StartModule which will take over functionality as the migration guide and "the internet" describes. I add

```<code>play.modules.enabled += "de.[...].modules.StartModule"
</code>```

to the application's .conf file. Executing this via sbt run or sbt start works as expected. Massive problems, however, arise when I try to unittest this stuff with sbt test or sbt test-only.

We have a rather elaborated unit test setup as the application is complex and has large legacy parts. Eventually, the unit test instance of the Play server is started with

```<code>Helpers.start(testserver=Helpers.testServer(playhttpport,
    app=new GuiceApplicationBuilder()
      .configure(getConfiguration())
      .build()));
</code>```

This works as long as the play.modules.enabled line above is not visible to the unit test code. As soon as I enable it, I get a number of errors like

```<code>Test de.[...]Tests failed: com.google.inject.CreationException:
   Unable to create injector, see the following errors:

1) No implementation for play.inject.ApplicationLifecycle was bound.
   while locating play.inject.ApplicationLifecycle
</code>```

or

```<code>2) Could not find a suitable constructor in play.api.Environment.
   Classes must have either one (and only one) constructor annotated with @Inject
   or a zero-argument constructor that is not private.
</code>```

Same thing happens if I remove the play.modules.enabled line and change the server start to

```<code>Helpers.start(testserver=Helpers.testServer(playhttpport,
  app=new GuiceApplicationBuilder()
    .load(Guiceable.modules(new StartModule()))
    .configure(getConfiguration())
    .build()));
</code>```

In my limited understanding, it seems that GuiceApplicationBuilder (or whatever) "forgets" about all builtin dependency injection configuration if any additional dependency definitions are given. Unfortunately, I have not found any applicable postings here or anywhere else which would lead me to a solution.

Questions:

Is my analysis correct?

How can I make my unit test code functional with the additional module in the DI framework?

Would it be helpful to directly continue in Play 2.5? I'd like to solve this problem before as that migration step will bring its own plethora of things to handle and I'd really to have a functional base for this - including an operational unit test framework...

Any insight and help greatly appreciated!
Kind regards,
Dirk

Update This is StartModule:

```<code>public class StartModule extends AbstractModule {
  @Override protected void configure() {
    bind(InnerServerLauncher.class).asEagerSingleton();
  }
}
</code>```

And this is the InnerServerLauncher:

```<code>@Singleton
public class InnerServerLauncher {
  @Inject
  public InnerServerLauncher(ApplicationLifecycle lifecycle,
                             Environment environment) {
    System.err.println("*** Server launcher called ***");
  }
}
</code>```

I should add that the problem also arises if I put a totally different class into play.modules.enabled like

```<code>play.modules.enabled += "play.filters.cors.CORSModule"
</code>```

答:
Ok, I finally got it. Problem is the configuration() method which I mentioned above but did not elaborate further. As I said, we have quite some legacy in our system. Therefore, we have a mechanism which constructs the configuration independently from Play's config files for the unit tests. GuiceBuilder.configure() (and btw. also the fakeApplication()-based methods) merges this with the Play-internal configuration but only on the topmost layer. For plain settings (strings, numbers etc.) that's ok, but for value lists it means that the complete list is overwritten and replaced.

play.modules.enabled is used by Play internally to gather the default modules which have to be registered with the dependency injection framework. Documentation states very clearly that your statements in application.conf must only add elements to play.modules.enabled, i.e.

```<code>play.modules.enabled += "package.Module"
</code>```

Our "special way" of constructing the configuration environment for unit tests, however, overwrote Play's own play.modules.enabled as soon as any value in our own configuration was set. And that destroyed the complete dependency injection scheme of Play as none of its own base classes were accessible any more. Bummer!

I solved this by actually using a "real" configuration file which is just read normally by GuiceApplicationBuilder and which contains those play.modules.enabled += ... lines. As this config file is still artifically and temporarily generated for the unit test scenario, I pass its name to GuiceApplicationBuilder via System.setProperty:

```<code>System.setProperty("config.file",conffilename);
Helpers.start(testserver=Helpers.testServer(playhttpport,
  app=new GuiceApplicationBuilder().build()));
</code>```

Now, the configuration is created correctly and with the internal default settings for play.modules.enabled. Now, I finally can start to actually move the code from GlobalSettings into that injected and eagerly loaded module. And it was just ten hours of hunting...

Body:
We're migrating our Java-only Play application from Play 2.4 to Play 2.5. First step: Get rid of GlobalSettings, still completely in the 2.4 realm. I wrote some StartModule which will take over functionality as the migration guide and "the internet" describes. I add

play.modules.enabled += "de.[...].modules.StartModule"

to the application's .conf file. Executing this via sbt run or sbt start works as expected. Massive problems, however, arise when I try to unittest this stuff with sbt test or sbt test-only.

We have a rather elaborated unit test setup as the application is complex and has large legacy parts. Eventually, the unit test instance of the Play server is started with

Helpers.start(testserver=Helpers.testServer(playhttpport,
    app=new GuiceApplicationBuilder()
      .configure(getConfiguration())
      .build()));

This works as long as the play.modules.enabled line above is not visible to the unit test code. As soon as I enable it, I get a number of errors like

Test de.[...]Tests failed: com.google.inject.CreationException:
   Unable to create injector, see the following errors:

1) No implementation for play.inject.ApplicationLifecycle was bound.
   while locating play.inject.ApplicationLifecycle

or

2) Could not find a suitable constructor in play.api.Environment.
   Classes must have either one (and only one) constructor annotated with @Inject
   or a zero-argument constructor that is not private.

Same thing happens if I remove the play.modules.enabled line and change the server start to

Helpers.start(testserver=Helpers.testServer(playhttpport,
  app=new GuiceApplicationBuilder()
    .load(Guiceable.modules(new StartModule()))
    .configure(getConfiguration())
    .build()));

In my limited understanding, it seems that GuiceApplicationBuilder (or whatever) "forgets" about all builtin dependency injection configuration if any additional dependency definitions are given. Unfortunately, I have not found any applicable postings here or anywhere else which would lead me to a solution.

Questions:

Is my analysis correct?

How can I make my unit test code functional with the additional module in the DI framework?

Would it be helpful to directly continue in Play 2.5? I'd like to solve this problem before as that migration step will bring its own plethora of things to handle and I'd really to have a functional base for this - including an operational unit test framework...

Any insight and help greatly appreciated!
Kind regards,
Dirk

Update This is StartModule:

public class StartModule extends AbstractModule {
  @Override protected void configure() {
    bind(InnerServerLauncher.class).asEagerSingleton();
  }
}

And this is the InnerServerLauncher:

@Singleton
public class InnerServerLauncher {
  @Inject
  public InnerServerLauncher(ApplicationLifecycle lifecycle,
                             Environment environment) {
    System.err.println("*** Server launcher called ***");
  }
}

I should add that the problem also arises if I put a totally different class into play.modules.enabled like

play.modules.enabled += "play.filters.cors.CORSModule"

Body:
Ok, I finally got it. Problem is the configuration() method which I mentioned above but did not elaborate further. As I said, we have quite some legacy in our system. Therefore, we have a mechanism which constructs the configuration independently from Play's config files for the unit tests. GuiceBuilder.configure() (and btw. also the fakeApplication()-based methods) merges this with the Play-internal configuration but only on the topmost layer. For plain settings (strings, numbers etc.) that's ok, but for value lists it means that the complete list is overwritten and replaced.

play.modules.enabled is used by Play internally to gather the default modules which have to be registered with the dependency injection framework. Documentation states very clearly that your statements in application.conf must only add elements to play.modules.enabled, i.e.

play.modules.enabled += "package.Module"

Our "special way" of constructing the configuration environment for unit tests, however, overwrote Play's own play.modules.enabled as soon as any value in our own configuration was set. And that destroyed the complete dependency injection scheme of Play as none of its own base classes were accessible any more. Bummer!

I solved this by actually using a "real" configuration file which is just read normally by GuiceApplicationBuilder and which contains those play.modules.enabled += ... lines. As this config file is still artifically and temporarily generated for the unit test scenario, I pass its name to GuiceApplicationBuilder via System.setProperty:

System.setProperty("config.file",conffilename);
Helpers.start(testserver=Helpers.testServer(playhttpport,
  app=new GuiceApplicationBuilder().build()));

Now, the configuration is created correctly and with the internal default settings for play.modules.enabled. Now, I finally can start to actually move the code from GlobalSettings into that injected and eagerly loaded module. And it was just ten hours of hunting...


问:
Is there a SQL statement that lets me create exact duplicate of partitioned table structure in Oracle 12c?
I need to clone a partitioned table in Oracle (without data).
Is there a SQL statement that lets me do it in Oracle 12c?

I tried using DBMS metadata and then executing generated DDL.
Looking for something simpler I can use in PL/SQL or SQL code.

答:
Just figured it in 12c.
This creates exact copy with partitions (no data); </p>

```<code>CREATE TABLE GES.TARGET_TABLE
  FOR EXCHANGE WITH TABLE GES.SOURCE_TABLE.
</code>```

Body:
Just figured it in 12c.
This creates exact copy with partitions (no data);

CREATE TABLE GES.TARGET_TABLE
  FOR EXCHANGE WITH TABLE GES.SOURCE_TABLE.


问:
Python - How to sort individual elements in a list of Python tuples
I apologize of if this is a duplicate of this.

Sort a list of tuples depending on two elements
depending-on-two-elements

What I have is a unsorted list of tuples

```<code>unsorted_list  = [(50,45), (35,40)]
sorted_list = [(35,40), (50,45)]
</code>```

I want to end up with the following sorted list. I tried the following:

```<code>sorted(unsorted, key=lambda element: (element[0], element[1]))
</code>```

My result was the following, which is not what I wanted.

```<code>[(35, 40), (45,50)]
</code>```

答:
Tuples are immutable, so you can't simply sort their contents. You have to create new tuples that contain the sorted items of the old tuples. Here's a simple way to do that with a list of two-item tuples.

```<code>unsorted_list = [(50,45), (35,40)]
sorted_list = [(min(t), max(t)) for t in sorted(unsorted_list)]
print(sorted_list)
</code>```

output

```<code>[(35, 40), (45, 50)]
</code>```

Another option is

```<code>sorted_list = [(u, v) if u<=v else (v, u) for u,v in sorted(unsorted_list)]
</code>```

Body:
I apologize of if this is a duplicate of this.

Sort a list of tuples depending on two elements
depending-on-two-elements

What I have is a unsorted list of tuples

unsorted_list  = [(50,45), (35,40)]
sorted_list = [(35,40), (50,45)]

I want to end up with the following sorted list. I tried the following:

sorted(unsorted, key=lambda element: (element[0], element[1]))

My result was the following, which is not what I wanted.

[(35, 40), (45,50)]

Body:
Tuples are immutable, so you can't simply sort their contents. You have to create new tuples that contain the sorted items of the old tuples. Here's a simple way to do that with a list of two-item tuples.

unsorted_list = [(50,45), (35,40)]
sorted_list = [(min(t), max(t)) for t in sorted(unsorted_list)]
print(sorted_list)

output

[(35, 40), (45, 50)]

Another option is

sorted_list = [(u, v) if u<=v else (v, u) for u,v in sorted(unsorted_list)]


问:
Behavior of mysql_insert_id()
I am using functions from a php library that uses mysql_insert_id() every now and then. Now I've modified a few functions that insert data into tables such that the primary key value is explicitly specified e.g. I insert an a row with ID=300 followed by a row with ID=200 when the table originally had 10 rows. I am wondering if mysql_insert_id will behave as expected i.e. return the value I explicitly specified for the AUTO_INCREMENT PRIMARY KEY column.

答:
The answer is yes,

it will return the values you entered. i liked this question so i actually tried multiple times in multiple servers having diffrent configurations.

it will return the value you inserted,

the mysql_insert_id() returns the value of the auto_increment feild, it need not be auto generated.

Also it will return 0, if you try to give dupilcate value for your key because it wont get inserted properly.

if you want to try then use the following query

--EDIT .. with more inserts

```<code><?php
$link = mysql_connect('localhost', 'root', 'techping');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('test');

mysql_query("INSERT INTO test (id, name) values (100,'kossu')");
printf("Last inserted record has id %d<br />", mysql_insert_id());
mysql_query("INSERT INTO test (id, name) values (125,'kossu')");
printf("Last inserted record has id %d<br />", mysql_insert_id());
mysql_query("INSERT INTO test (id, name) values (121,'kossu')");
printf("Last inserted record has id %d<br />", mysql_insert_id());
mysql_query("INSERT INTO test (id, name) values ('','kossu')");
printf("Last inserted record has id %d<br />", mysql_insert_id());
mysql_query("INSERT INTO test (id, name) values (250,'kossu')");
printf("Last inserted record has id %d<br />", mysql_insert_id());
?>
</code>```

The results:

```<code>Last inserted record has id 100
Last inserted record has id 125
Last inserted record has id 121
Last inserted record has id 126
Last inserted record has id 250
</code>```

See when i let the autoincrement generate the id after 121, it generated the next value(126) after the biggest id( ie; 125 in this case ), not 122

Title: Behavior of mysql_insert_id()

Body:
The answer is yes,

it will return the values you entered. i liked this question so i actually tried multiple times in multiple servers having diffrent configurations.

it will return the value you inserted,

the mysql_insert_id() returns the value of the auto_increment feild, it need not be auto generated.

Also it will return 0, if you try to give dupilcate value for your key because it wont get inserted properly.

if you want to try then use the following query

--EDIT .. with more inserts

<?php
$link = mysql_connect('localhost', 'root', 'techping');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('test');

mysql_query("INSERT INTO test (id, name) values (100,'kossu')");
printf("Last inserted record has id %d<br />", mysql_insert_id());
mysql_query("INSERT INTO test (id, name) values (125,'kossu')");
printf("Last inserted record has id %d<br />", mysql_insert_id());
mysql_query("INSERT INTO test (id, name) values (121,'kossu')");
printf("Last inserted record has id %d<br />", mysql_insert_id());
mysql_query("INSERT INTO test (id, name) values ('','kossu')");
printf("Last inserted record has id %d<br />", mysql_insert_id());
mysql_query("INSERT INTO test (id, name) values (250,'kossu')");
printf("Last inserted record has id %d<br />", mysql_insert_id());
?>

The results:

Last inserted record has id 100
Last inserted record has id 125
Last inserted record has id 121
Last inserted record has id 126
Last inserted record has id 250

See when i let the autoincrement generate the id after 121, it generated the next value(126) after the biggest id( ie; 125 in this case ), not 122


问:
why i can't import com.google.android.gms.location.LocationListener; and LocationRequest, also LocationServices?
I am trying to build an android app using android studio that uses the direct user location, and I am got error on import com.google.android.gms.location.LocationListener; it says it can't resolve symbol 'LocationListener', and also for 'LocationRequest' and 'LocationServices' I tried searching for an answer but I can't figure out what the problem is.</p>

答:
Try adding the below :

```<code>   compile 'com.google.android.gms:play-services:9.8.0'
</code>```

in your app level gradle dependencies and

```<code> classpath 'com.google.gms:google-services:3.1.0'
</code>```

in project level gradle dependencies

note the versions may change based on your SDK config or your preference

Body:
Try adding the below :

   compile 'com.google.android.gms:play-services:9.8.0'

in your app level gradle dependencies and

 classpath 'com.google.gms:google-services:3.1.0'

in project level gradle dependencies

note the versions may change based on your SDK config or your preference


问:
MNIST Classification: low accuracy (10%) and no change in loss
I'm learning TensorFlow and tired to apply on mnist database.
My question is (see attached image) :

what could cause such output for accuracy (improving and then degrading!) & Loss (almost constant!)

the accuracy isn't that great just hovering around 10%

Despite:

5 layer network (incl. output layer), with 200/10/60/30/10 neurons respectively

Is the network not learning ? despite 0.1 learning rate (which is quite high I believe)

Full code: https://github.com/vibhorj/tf > mnist-2.py

1) here's how the layers are defined:

```<code>K,L,M,N=200,100,60,30
""" Layer 1 """
with tf.name_scope('L1'):
    w1 = tf.Variable(initial_value = tf.truncated_normal([28*28,K],mean=0,stddev=0.1), name = 'w1')
    b1 = tf.Variable(initial_value = tf.truncated_normal([K],mean=0,stddev=0.1), name = 'b1')
""" Layer 2 """
with tf.name_scope('L2'):
    w2 = tf.Variable(initial_value =tf.truncated_normal([K,L],mean=0,stddev=0.1), name = 'w2')
    b2 = tf.Variable(initial_value = tf.truncated_normal([L],mean=0,stddev=0.1), name = 'b2')
""" Layer 3 """
with tf.name_scope('L3'):
    w3 = tf.Variable(initial_value = tf.truncated_normal([L,M],mean=0,stddev=0.1), name = 'w3')
    b3 = tf.Variable(initial_value = tf.truncated_normal([M],mean=0,stddev=0.1), name = 'b3')
""" Layer 4 """
with tf.name_scope('L4'):
    w4 = tf.Variable(initial_value = tf.truncated_normal([M,N],mean=0,stddev=0.1), name = 'w4')
    b4 = tf.Variable(initial_value = tf.truncated_normal([N],mean=0,stddev=0.1), name = 'b4')
""" Layer output """
with tf.name_scope('L_out'):
    w_out = tf.Variable(initial_value = tf.truncated_normal([N,10],mean=0,stddev=0.1), name = 'w_out')
    b_out = tf.Variable(initial_value = tf.truncated_normal([10],mean=0,stddev=0.1), name = 'b_out')
</code>```

2) loss function

```<code>Y1 = tf.nn.sigmoid(tf.add(tf.matmul(X,w1),b1), name='Y1')
Y2 = tf.nn.sigmoid(tf.add(tf.matmul(Y1,w2),b2), name='Y2')
Y3 = tf.nn.sigmoid(tf.add(tf.matmul(Y2,w3),b3), name='Y3')
Y4 = tf.nn.sigmoid(tf.add(tf.matmul(Y3,w4),b4), name='Y4')

Y_pred_logits = tf.add(tf.matmul(Y4, w_out),b_out,name='logits')
Y_pred_prob = tf.nn.softmax(Y_pred_logits, name='probs')

error = -tf.matmul(Y
              , tf.reshape(tf.log(Y_pred_prob),[10,-1]), name ='err')
loss = tf.reduce_mean(error, name = 'loss')
</code>```

3) optimization function

```<code>opt = tf.train.GradientDescentOptimizer(0.1)
grads_and_vars = opt.compute_gradients(loss)
ctr = tf.Variable(0.0, name='ctr')
z = opt.apply_gradients(grads_and_vars, global_step=ctr)
</code>```

4)  Tensorboard code:

```<code>evt_file = tf.summary.FileWriter('/Users/vibhorj/python/-tf/g_mnist')
evt_file.add_graph(tf.get_default_graph())

s1 = tf.summary.scalar(name='accuracy', tensor=accuracy)
s2 = tf.summary.scalar(name='loss', tensor=loss)
m1 = tf.summary.merge([s1,s2])
</code>```

5) run the session (test data is mnist.test.images & mnist.test.labels

```<code>with tf.Session() as sess:
    sess.run(tf.variables_initializer(tf.global_variables()))
    for i in range(300):
       """ calc. accuracy on test data - TENSORBOARD before iteration beings """
       summary = sess.run(m1, feed_dict=test_data)
       evt_file.add_summary(summary, sess.run(ctr))
       evt_file.flush()

       """ fetch train data """
       a_train, b_train = mnist.train.next_batch(batch_size=100)
       train_data = {X: a_train , Y: b_train}

       """ train """
       sess.run(z, feed_dict = train_data)
</code>```

Appreciate your time to provide any insight into it. I'm completely clueless hwo to proceed further (even tried initializing w & b with random_normal, played with learning rates [0.1,0.01, 0.001])

Cheers!

答:
Please consider

Initializing biases to zeros

Using ReLU units instead of sigmoid - avoid saturation

Using Adam optimizer - faster learning

I feel that your network is quite large. You could do with a smaller network.

```<code>K,L,M,N=200,100,60,30
""" Layer 1 """
with tf.name_scope('L1'):
    w1 = tf.Variable(initial_value = tf.truncated_normal([28*28,K],mean=0,stddev=0.1), name = 'w1')
    b1 = tf.zeros([K])#tf.Variable(initial_value = tf.truncated_normal([K],mean=0,stddev=0.01), name = 'b1')
""" Layer 2 """
with tf.name_scope('L2'):
    w2 = tf.Variable(initial_value =tf.truncated_normal([K,L],mean=0,stddev=0.1), name = 'w2')
    b2 = tf.zeros([L])#tf.Variable(initial_value = tf.truncated_normal([L],mean=0,stddev=0.01), name = 'b2')
""" Layer 3 """
with tf.name_scope('L3'):
    w3 = tf.Variable(initial_value = tf.truncated_normal([L,M],mean=0,stddev=0.1), name = 'w3')
    b3 = tf.zeros([M]) #tf.Variable(initial_value = tf.truncated_normal([M],mean=0,stddev=0.01), name = 'b3')
""" Layer 4 """
with tf.name_scope('L4'):
    w4 = tf.Variable(initial_value = tf.truncated_normal([M,N],mean=0,stddev=0.1), name = 'w4')
    b4 = tf.zeros([N])#tf.Variable(initial_value = tf.truncated_normal([N],mean=0,stddev=0.1), name = 'b4')
""" Layer output """
with tf.name_scope('L_out'):
    w_out = tf.Variable(initial_value = tf.truncated_normal([N,10],mean=0,stddev=0.1), name = 'w_out')
    b_out = tf.zeros([10])#tf.Variable(initial_value = tf.truncated_normal([10],mean=0,stddev=0.1), name = 'b_out')

Y1 = tf.nn.relu(tf.add(tf.matmul(X,w1),b1), name='Y1')
Y2 = tf.nn.relu(tf.add(tf.matmul(Y1,w2),b2), name='Y2')
Y3 = tf.nn.relu(tf.add(tf.matmul(Y2,w3),b3), name='Y3')
Y4 = tf.nn.relu(tf.add(tf.matmul(Y3,w4),b4), name='Y4')

Y_pred_logits = tf.add(tf.matmul(Y4, w_out),b_out,name='logits')

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=Y_pred_logits, name='xentropy'))
opt = tf.train.GradientDescentOptimizer(0.01)
grads_and_vars = opt.compute_gradients(loss)
ctr = tf.Variable(0.0, name='ctr', trainable=False)
train_op = opt.minimize(loss, global_step=ctr)

for v in tf.trainable_variables():
  print v.op.name

with tf.Session() as sess:
    sess.run(tf.variables_initializer(tf.global_variables()))
    for i in range(3000):
       """ calc. accuracy on test data - TENSORBOARD before iteration beings """
       #summary = sess.run(m1, feed_dict=test_data)
       #evt_file.add_summary(summary, sess.run(ctr))
       #evt_file.flush()

       """ fetch train data """
       a_train, b_train = mnist.train.next_batch(batch_size=100)
       train_data = {X: a_train , Y: b_train}

       """ train """
       l = sess.run(loss, feed_dict = train_data)
       print l
       sess.run(train_op, feed_dict = train_data)
</code>```

Body:
I'm learning TensorFlow and tired to apply on mnist database.
My question is (see attached image) :

what could cause such output for accuracy (improving and then degrading!) & Loss (almost constant!)

the accuracy isn't that great just hovering around 10%

Despite:

5 layer network (incl. output layer), with 200/10/60/30/10 neurons respectively

Is the network not learning ? despite 0.1 learning rate (which is quite high I believe)

Full code: https://github.com/vibhorj/tf > mnist-2.py

1) here's how the layers are defined:

K,L,M,N=200,100,60,30
""" Layer 1 """
with tf.name_scope('L1'):
    w1 = tf.Variable(initial_value = tf.truncated_normal([28*28,K],mean=0,stddev=0.1), name = 'w1')
    b1 = tf.Variable(initial_value = tf.truncated_normal([K],mean=0,stddev=0.1), name = 'b1')
""" Layer 2 """
with tf.name_scope('L2'):
    w2 = tf.Variable(initial_value =tf.truncated_normal([K,L],mean=0,stddev=0.1), name = 'w2')
    b2 = tf.Variable(initial_value = tf.truncated_normal([L],mean=0,stddev=0.1), name = 'b2')
""" Layer 3 """
with tf.name_scope('L3'):
    w3 = tf.Variable(initial_value = tf.truncated_normal([L,M],mean=0,stddev=0.1), name = 'w3')
    b3 = tf.Variable(initial_value = tf.truncated_normal([M],mean=0,stddev=0.1), name = 'b3')
""" Layer 4 """
with tf.name_scope('L4'):
    w4 = tf.Variable(initial_value = tf.truncated_normal([M,N],mean=0,stddev=0.1), name = 'w4')
    b4 = tf.Variable(initial_value = tf.truncated_normal([N],mean=0,stddev=0.1), name = 'b4')
""" Layer output """
with tf.name_scope('L_out'):
    w_out = tf.Variable(initial_value = tf.truncated_normal([N,10],mean=0,stddev=0.1), name = 'w_out')
    b_out = tf.Variable(initial_value = tf.truncated_normal([10],mean=0,stddev=0.1), name = 'b_out')

2) loss function

Y1 = tf.nn.sigmoid(tf.add(tf.matmul(X,w1),b1), name='Y1')
Y2 = tf.nn.sigmoid(tf.add(tf.matmul(Y1,w2),b2), name='Y2')
Y3 = tf.nn.sigmoid(tf.add(tf.matmul(Y2,w3),b3), name='Y3')
Y4 = tf.nn.sigmoid(tf.add(tf.matmul(Y3,w4),b4), name='Y4')

Y_pred_logits = tf.add(tf.matmul(Y4, w_out),b_out,name='logits')
Y_pred_prob = tf.nn.softmax(Y_pred_logits, name='probs')

error = -tf.matmul(Y
              , tf.reshape(tf.log(Y_pred_prob),[10,-1]), name ='err')
loss = tf.reduce_mean(error, name = 'loss')

3) optimization function

opt = tf.train.GradientDescentOptimizer(0.1)
grads_and_vars = opt.compute_gradients(loss)
ctr = tf.Variable(0.0, name='ctr')
z = opt.apply_gradients(grads_and_vars, global_step=ctr)

4)  Tensorboard code:

evt_file = tf.summary.FileWriter('/Users/vibhorj/python/-tf/g_mnist')
evt_file.add_graph(tf.get_default_graph())

s1 = tf.summary.scalar(name='accuracy', tensor=accuracy)
s2 = tf.summary.scalar(name='loss', tensor=loss)
m1 = tf.summary.merge([s1,s2])

5) run the session (test data is mnist.test.images & mnist.test.labels

with tf.Session() as sess:
    sess.run(tf.variables_initializer(tf.global_variables()))
    for i in range(300):
       """ calc. accuracy on test data - TENSORBOARD before iteration beings """
       summary = sess.run(m1, feed_dict=test_data)
       evt_file.add_summary(summary, sess.run(ctr))
       evt_file.flush()

       """ fetch train data """
       a_train, b_train = mnist.train.next_batch(batch_size=100)
       train_data = {X: a_train , Y: b_train}

       """ train """
       sess.run(z, feed_dict = train_data)

Appreciate your time to provide any insight into it. I'm completely clueless hwo to proceed further (even tried initializing w & b with random_normal, played with learning rates [0.1,0.01, 0.001])

Cheers!

Body:
Please consider

Initializing biases to zeros

Using ReLU units instead of sigmoid - avoid saturation

Using Adam optimizer - faster learning

I feel that your network is quite large. You could do with a smaller network.

K,L,M,N=200,100,60,30
""" Layer 1 """
with tf.name_scope('L1'):
    w1 = tf.Variable(initial_value = tf.truncated_normal([28*28,K],mean=0,stddev=0.1), name = 'w1')
    b1 = tf.zeros([K])#tf.Variable(initial_value = tf.truncated_normal([K],mean=0,stddev=0.01), name = 'b1')
""" Layer 2 """
with tf.name_scope('L2'):
    w2 = tf.Variable(initial_value =tf.truncated_normal([K,L],mean=0,stddev=0.1), name = 'w2')
    b2 = tf.zeros([L])#tf.Variable(initial_value = tf.truncated_normal([L],mean=0,stddev=0.01), name = 'b2')
""" Layer 3 """
with tf.name_scope('L3'):
    w3 = tf.Variable(initial_value = tf.truncated_normal([L,M],mean=0,stddev=0.1), name = 'w3')
    b3 = tf.zeros([M]) #tf.Variable(initial_value = tf.truncated_normal([M],mean=0,stddev=0.01), name = 'b3')
""" Layer 4 """
with tf.name_scope('L4'):
    w4 = tf.Variable(initial_value = tf.truncated_normal([M,N],mean=0,stddev=0.1), name = 'w4')
    b4 = tf.zeros([N])#tf.Variable(initial_value = tf.truncated_normal([N],mean=0,stddev=0.1), name = 'b4')
""" Layer output """
with tf.name_scope('L_out'):
    w_out = tf.Variable(initial_value = tf.truncated_normal([N,10],mean=0,stddev=0.1), name = 'w_out')
    b_out = tf.zeros([10])#tf.Variable(initial_value = tf.truncated_normal([10],mean=0,stddev=0.1), name = 'b_out')

Y1 = tf.nn.relu(tf.add(tf.matmul(X,w1),b1), name='Y1')
Y2 = tf.nn.relu(tf.add(tf.matmul(Y1,w2),b2), name='Y2')
Y3 = tf.nn.relu(tf.add(tf.matmul(Y2,w3),b3), name='Y3')
Y4 = tf.nn.relu(tf.add(tf.matmul(Y3,w4),b4), name='Y4')

Y_pred_logits = tf.add(tf.matmul(Y4, w_out),b_out,name='logits')

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=Y_pred_logits, name='xentropy'))
opt = tf.train.GradientDescentOptimizer(0.01)
grads_and_vars = opt.compute_gradients(loss)
ctr = tf.Variable(0.0, name='ctr', trainable=False)
train_op = opt.minimize(loss, global_step=ctr)

for v in tf.trainable_variables():
  print v.op.name

with tf.Session() as sess:
    sess.run(tf.variables_initializer(tf.global_variables()))
    for i in range(3000):
       """ calc. accuracy on test data - TENSORBOARD before iteration beings """
       #summary = sess.run(m1, feed_dict=test_data)
       #evt_file.add_summary(summary, sess.run(ctr))
       #evt_file.flush()

       """ fetch train data """
       a_train, b_train = mnist.train.next_batch(batch_size=100)
       train_data = {X: a_train , Y: b_train}

       """ train """
       l = sess.run(loss, feed_dict = train_data)
       print l
       sess.run(train_op, feed_dict = train_data)