问:
How to move to next row in datatable if one row catches an error? C# 2.0
I am getting data from a mySql database and I am inserting it into another system. If a column has data in an incorrect format I log this and go to next row in the datatable. It works as expected but now if I have a search function in my method that gets some additional data and this function fails I want to immediately log this and go to next row. As it is now I just log it but it still gets inserted (without the value that didn't meet the search criteria).

My code:

```<code>    private void updateCustomer()
            {
                 MySqlConnection connection = new MySqlConnection("server=myServer;database=myDatabase;uid=myID;password=myPass");

                MySqlCommand command = new MySqlCommand(@"mySelectCommand", connection);
                DataTable customerTbl = new DataTable();
                MySqlDataReader reader;
                try
                {
                    connection.Open();
                    reader = command.ExecuteReader();

                    if (reader.HasRows)
                    {
                        customerTbl.Load(reader);
                    }
                    reader.Close();

                }
                catch (Exception ex)
                {
            _out.error("Could not connect to mySql database");
                }
                finally
                {
                    connection.Close();
                }

                foreach (DataRow row in customerTbl.Rows)
                {
                    // Declare the customer variables
                    string customerID = Encoding.ASCII.GetString((byte[])row["Customer ID"]);
                    string ChildOf = row["Child of"].ToString();

                    // Create the customer object
                    Customer customer = new Customer();

            customer.entityId = customerID;

                    if (ChildOf != "")
                    {
            RecordRef parentRef = new RecordRef();
                        try
                        {

                            parentRef.internalId = searchCustomer(ChildOf);

                        }
                        catch
                        {
// If it fails here I want to log the customerID and then go to the next row in the datatable (could not find the internalid for ChildOf
                            _out.error(customerID + " was not updated. Error: invalid format Parent string");
                        }
                finally
                {
                parentRef.typeSpecified = false;
                            customer.parent = parentRef;
                }
                    }

                    // Invoke update() operation
                    WriteResponse response = _service.update(customer);

                    // Process the response
                    if (response.status.isSuccess)
                    {

                    }
                    else
                    {
                        _out.error(customerID + " was not updated. Error: " + getStatusDetails(response.status));
                    }
                }
            }
</code>```

答:
I realized that I want to log the other failed fields as well. Maybe it's an inefficient way but I did something like:

```<code>        bool findParent = true;
        if (ChildOf != "")
        {
            try
            {
                RecordRef parentRef = new RecordRef();
                parentRef.internalId = searchCustomer(ChildOf);
                parentRef.typeSpecified = false;
                customer.parent = parentRef;
            }
            catch
            {
                findParent = false;
                _out.error(customerID + " was not inserted. Error: invalid format Parent string");
            }
        }
</code>```

And then an if statement before trying to insert:

```<code>if (findPartner == true && findParent == true)
                {
                    response = _service.add(customer);
                    // Process the response
                    if (response.status.isSuccess)
                    {

                    }
                    else
                    {
                        _out.error(customerID + " was not inserted. Error: " + getStatusDetails(response.status));
                    }

                }
                else
                {
                    //_out.error(customerID + " was not updated. Error: " + getStatusDetails(response.status));
                }
</code>```

Body:
I am getting data from a mySql database and I am inserting it into another system. If a column has data in an incorrect format I log this and go to next row in the datatable. It works as expected but now if I have a search function in my method that gets some additional data and this function fails I want to immediately log this and go to next row. As it is now I just log it but it still gets inserted (without the value that didn't meet the search criteria).

My code:

    private void updateCustomer()
            {
                 MySqlConnection connection = new MySqlConnection("server=myServer;database=myDatabase;uid=myID;password=myPass");

                MySqlCommand command = new MySqlCommand(@"mySelectCommand", connection);
                DataTable customerTbl = new DataTable();
                MySqlDataReader reader;
                try
                {
                    connection.Open();
                    reader = command.ExecuteReader();

                    if (reader.HasRows)
                    {
                        customerTbl.Load(reader);
                    }
                    reader.Close();

                }
                catch (Exception ex)
                {
            _out.error("Could not connect to mySql database");
                }
                finally
                {
                    connection.Close();
                }

                foreach (DataRow row in customerTbl.Rows)
                {
                    // Declare the customer variables
                    string customerID = Encoding.ASCII.GetString((byte[])row["Customer ID"]);
                    string ChildOf = row["Child of"].ToString();

                    // Create the customer object
                    Customer customer = new Customer();

            customer.entityId = customerID;

                    if (ChildOf != "")
                    {
            RecordRef parentRef = new RecordRef();
                        try
                        {

                            parentRef.internalId = searchCustomer(ChildOf);

                        }
                        catch
                        {
// If it fails here I want to log the customerID and then go to the next row in the datatable (could not find the internalid for ChildOf
                            _out.error(customerID + " was not updated. Error: invalid format Parent string");
                        }
                finally
                {
                parentRef.typeSpecified = false;
                            customer.parent = parentRef;
                }
                    }

                    // Invoke update() operation
                    WriteResponse response = _service.update(customer);

                    // Process the response
                    if (response.status.isSuccess)
                    {

                    }
                    else
                    {
                        _out.error(customerID + " was not updated. Error: " + getStatusDetails(response.status));
                    }
                }
            }

Body:
I realized that I want to log the other failed fields as well. Maybe it's an inefficient way but I did something like:

        bool findParent = true;
        if (ChildOf != "")
        {
            try
            {
                RecordRef parentRef = new RecordRef();
                parentRef.internalId = searchCustomer(ChildOf);
                parentRef.typeSpecified = false;
                customer.parent = parentRef;
            }
            catch
            {
                findParent = false;
                _out.error(customerID + " was not inserted. Error: invalid format Parent string");
            }
        }

And then an if statement before trying to insert:

if (findPartner == true && findParent == true)
                {
                    response = _service.add(customer);
                    // Process the response
                    if (response.status.isSuccess)
                    {

                    }
                    else
                    {
                        _out.error(customerID + " was not inserted. Error: " + getStatusDetails(response.status));
                    }

                }
                else
                {
                    //_out.error(customerID + " was not updated. Error: " + getStatusDetails(response.status));
                }


来源: stackexchange

问:
Python loop and invalid answer
This is what I'm working just a little yes/no question.

```<code>print("Hello")
print("I love you")
answer = input("Do you love me?")
if answer in ["yes"]:
  print("Yey! I knew it! Thank You!")
if answer in ["no"]:
  print("O-ok, I understand, no worries.")

while True:
  try:
    print("Please answer me.")
    answer = input("Do you love me?")
  except ValueError:
   continue
  if answer in ["yes", "no"]:
    break
</code>```

When I enter a valid answer it print what I want but also jumps into the loop asking again, if I answer again then it breaks. I don't understand why tho.
When I enter an invalid answer it loops until it gets one right, when it gets one right it breaks but doesn't answer. Can someone please explain why?

Here is where I have been currently testing it: https://trinket.io/python/5a25117b84

答:
The position of while loop is not right. If you want to ask again if answer is invalid, try like this:</p>

```<code>print("Hello")
print("I love you")
answer = input("Do you love me?")

while True:
    try:
        if answer == "yes":
            print("Yey! I knew it! Thank You!")
            break
        elif answer == "no":
            print("O-ok, I understand, no worries.")
            break
        else:
            print("Please answer me.")
            answer = input("Do you love me?")
    except ValueError:
        continue
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python loop and invalid answer

Body:
This is what I'm working just a little yes/no question.

print("Hello")
print("I love you")
answer = input("Do you love me?")
if answer in ["yes"]:
  print("Yey! I knew it! Thank You!")
if answer in ["no"]:
  print("O-ok, I understand, no worries.")

while True:
  try:
    print("Please answer me.")
    answer = input("Do you love me?")
  except ValueError:
   continue
  if answer in ["yes", "no"]:
    break

When I enter a valid answer it print what I want but also jumps into the loop asking again, if I answer again then it breaks. I don't understand why tho.
When I enter an invalid answer it loops until it gets one right, when it gets one right it breaks but doesn't answer. Can someone please explain why?

Here is where I have been currently testing it: https://trinket.io/python/5a25117b84

Body:
The position of while loop is not right. If you want to ask again if answer is invalid, try like this:

print("Hello")
print("I love you")
answer = input("Do you love me?")

while True:
    try:
        if answer == "yes":
            print("Yey! I knew it! Thank You!")
            break
        elif answer == "no":
            print("O-ok, I understand, no worries.")
            break
        else:
            print("Please answer me.")
            answer = input("Do you love me?")
    except ValueError:
        continue


问:
How do you get your path in Octave (on Windows)?
I used addpath(pwd) to get my .m files working in my projects directory. When I close the window and start a new window, the path I just added is gone. But the files still run.

Is it in my path or not? How do I see the directories I have added to my path?

Also, . is the first entry I see from path. Does that mean I don't need to add any directories because it will always search the current directory first?

Thanks.

答:
```<code>addpath(pwd); savepath();
</code>```

Done.

Body:
addpath(pwd); savepath();

Done.


问:
Why to use Polymorphism?
I have the following code in which I have a parent class and its child. I am trying to determine how the code benefits from using polymorphism.

```<code>class FlyingMachines {
    public void fly() {
        System.out.println("No implementation");
    }
}

class Jet extends FlyingMachines {
    public void fly() {
        System.out.println("Start, Taxi, Fly");
    }

    public void bombardment() {
        System.out.println("Throw Missile");
    }
}

public class PolymorphicTest {
    public static void main(String[] args) {
        FlyingMachines flm = new Jet();
        flm.fly();

        Jet j = new Jet();
        j.bombardment();
        j.fly();
    }
}
</code>```

What is the advantage of polymorphism when both flm.fly() and j.fly() give me the same answer?

答:
Let's add one more class in this, It help's you to understand use of polymorphism..

```<code>class FlyingMachines {
    public void fly() {
        System.out.println("No implementation");
    }
}

class Jet extends FlyingMachines {
    public void fly() {
        System.out.println("Start, Jet, Fly");
    }
}

class FighterPlan extends FlyingMachines {
    public void fly() {
        System.out.println("Start, Fighter, Fight");
    }
}

public class PolymorphicTest {
    public static void main(String[] args) {
        FlyingMachines flm = new Jet();
        flm.fly();

        FlyingMachines flm2 = new FighterPlan();
        flm2.fly();
    }
}
</code>```

Output:

```<code>Start, Jet, Fly
Start, Fighter, Fight
</code>```

Title: Why to use Polymorphism?

Body:
I have the following code in which I have a parent class and its child. I am trying to determine how the code benefits from using polymorphism.

class FlyingMachines {
    public void fly() {
        System.out.println("No implementation");
    }
}

class Jet extends FlyingMachines {
    public void fly() {
        System.out.println("Start, Taxi, Fly");
    }

    public void bombardment() {
        System.out.println("Throw Missile");
    }
}

public class PolymorphicTest {
    public static void main(String[] args) {
        FlyingMachines flm = new Jet();
        flm.fly();

        Jet j = new Jet();
        j.bombardment();
        j.fly();
    }
}

What is the advantage of polymorphism when both flm.fly() and j.fly() give me the same answer?

Body:
Let's add one more class in this, It help's you to understand use of polymorphism..

class FlyingMachines {
    public void fly() {
        System.out.println("No implementation");
    }
}

class Jet extends FlyingMachines {
    public void fly() {
        System.out.println("Start, Jet, Fly");
    }
}

class FighterPlan extends FlyingMachines {
    public void fly() {
        System.out.println("Start, Fighter, Fight");
    }
}

public class PolymorphicTest {
    public static void main(String[] args) {
        FlyingMachines flm = new Jet();
        flm.fly();

        FlyingMachines flm2 = new FighterPlan();
        flm2.fly();
    }
}

Output:

Start, Jet, Fly
Start, Fighter, Fight


问:
Form Submit using Angularjs to SpringMVC Controller using $http.post
How to send multiple data  from jsp to Springmvc controller to change password.
I wants to change password using angular js.
How to solve this?

Alert message showing properly but cannot call controller using post method.

My js code

```<code>myangu.controller('account', function($scope, $http) {

    var submitvalue = $scope.detailspassword = function() {

        alert($scope.confirmpassword + "" + $scope.newpassword + ""
                + $scope.existedpassword);

    };
    var submitvalue = function(request) {

    };
    var error = function(reason) {
        alert("failure message: " + JSON.stringify({
            reason : reason
        }));

        $scope.errormessage = "Something Wrong.Cannot Change Your Password";

    };

    $http.post('/java/updatepassword').then(submitvalue, error);

});
</code>```

SpringMvc controller

```<code>@RequestMapping(value = "/updatepassword", method = RequestMethod.POST,produces="application/json")
    public @ResponseBody String updatepassword(@RequestBody Users users) throws JSONException,NullPointerException,JsonGenerationException{

        System.out.println("Updatedpassword"+users.getPassword());

        return uservice.updatepassword(users);
    }
</code>```

Jsp page

```<code><div class="divTablebody">
    <div  ng-controller="account">
        <%-- <form:form action="/java/changepassword"  method="POST" > --%>
        <div>{{errormessage}}</div>
        <div class="divTableRow">

            <div class="divTableCell">Existed password:</div>
            <div class="divTableCell">
                <input type="password" placeholder="Existed Password"
                    id="Existedpw" ng-model="existedpassword">
            </div>
        </div>
        <div class="divTableRow">
            <div class="divTableCell">New password:</div>
            <div class="divTableCell">
                <input type="password" placeholder="New Password" id="newpw"
                    ng-model="newpassword">
            </div>
        </div>
        <div class="divTableRow">
            <div class="divTableCell">Password Confirmation:</div>
            <div class="divTableCell">
                <input type="password" placeholder="Confirm Password "
                    id="confirmpw" ng-model="confirmpassword">
            </div>
        </div>
        <div class="divTableRow">
            <div class="divTableCell">Save</div>
            <div class="divTableCell">
                <input type="submit" id="pwsubmit" ng-click="detailspassword()" name="Submit">
            </div>
        </div>
</code>```

答:
I guess this scenario is: a user logged in and is going to change the password

how about try this,
modify your backend by receiving the old password, new password and userId from @RequestParams (or if you don't have userId then use whatever that are unique for each user like email to query user's information from your DB)

in Spring

```<code>@RequestMapping(value = "/updatepassword", method = RequestMethod.POST,produces="application/json")
public @ResponseBody String updatepassword(@RequestParam String userId, @RequestParam String existedPassword, @RequestParam String newPassword) {

    // query user by userId and match if existedPassword from request param is the same as user.getPassword()
   // if password is correct then update the password to the new password and
   // return blabla

}
</code>```

then take a look at controller in angular

```<code>// first check if $scope.newpassword is the same value as $scope.confirmpassword
// then send the following POST request

$http.post('/java/updatepassword',
  { params: {
       "userId": userId,          // as long as, the user logged in so you can get userId somehow
       "existedPassword": $scope.existedpassword,
       "newPassword": $scope.newpassword
            }
  })
.then(function successCallback(response) {
   // success
}, function errorCallback(response) {
  console.log(response);
});
</code>```

Hope it can help you get alternative way to solve this :)

ContentLicense: CC BY-SA 4.0

Body:
How to send multiple data  from jsp to Springmvc controller to change password.
I wants to change password using angular js.
How to solve this?

Alert message showing properly but cannot call controller using post method.

My js code

myangu.controller('account', function($scope, $http) {

    var submitvalue = $scope.detailspassword = function() {

        alert($scope.confirmpassword + "" + $scope.newpassword + ""
                + $scope.existedpassword);

    };
    var submitvalue = function(request) {

    };
    var error = function(reason) {
        alert("failure message: " + JSON.stringify({
            reason : reason
        }));

        $scope.errormessage = "Something Wrong.Cannot Change Your Password";

    };

    $http.post('/java/updatepassword').then(submitvalue, error);

});

SpringMvc controller

@RequestMapping(value = "/updatepassword", method = RequestMethod.POST,produces="application/json")
    public @ResponseBody String updatepassword(@RequestBody Users users) throws JSONException,NullPointerException,JsonGenerationException{

        System.out.println("Updatedpassword"+users.getPassword());

        return uservice.updatepassword(users);
    }

Jsp page

        <%-- <form:form action="/java/changepassword"  method="POST" > --%>

{{errormessage}}

Existed password:

                <input type="password" placeholder="Existed Password"
                    id="Existedpw" ng-model="existedpassword">

New password:

                <input type="password" placeholder="New Password" id="newpw"
                    ng-model="newpassword">

Password Confirmation:

                <input type="password" placeholder="Confirm Password "
                    id="confirmpw" ng-model="confirmpassword">

Save

                <input type="submit" id="pwsubmit" ng-click="detailspassword()" name="Submit">

Body:
I guess this scenario is: a user logged in and is going to change the password

how about try this,
modify your backend by receiving the old password, new password and userId from @RequestParams (or if you don't have userId then use whatever that are unique for each user like email to query user's information from your DB)

in Spring

@RequestMapping(value = "/updatepassword", method = RequestMethod.POST,produces="application/json")
public @ResponseBody String updatepassword(@RequestParam String userId, @RequestParam String existedPassword, @RequestParam String newPassword) {

    // query user by userId and match if existedPassword from request param is the same as user.getPassword()
   // if password is correct then update the password to the new password and
   // return blabla

}

then take a look at controller in angular

// first check if $scope.newpassword is the same value as $scope.confirmpassword
// then send the following POST request

$http.post('/java/updatepassword',
  { params: {
       "userId": userId,          // as long as, the user logged in so you can get userId somehow
       "existedPassword": $scope.existedpassword,
       "newPassword": $scope.newpassword
            }
  })
.then(function successCallback(response) {
   // success
}, function errorCallback(response) {
  console.log(response);
});

Hope it can help you get alternative way to solve this :)


问:
WebClient 403 Forbidden
I can download this by hand in IE.

http://scholar.google.com/scholar.ris?q=info:j8ymU9rzMsEJ:scholar.google.com/&output=citation&hl=zh-CN&as_sdt=2000&oe=GB&ct=citation&cd=0

But, using follow code

```<code>WebClient client = new WebClient();
client.DownloadFile(address, filename);
</code>```

Show Exception:
403 Forbidden

What's wrong?
How can I do that?

others

http://scholar.google.com/scholar.ris?q=info:sskrpr5jlLwJ:scholar.google.com/&output=citation&hl=zh-CN&as_sdt=2000&oe=GB&ct=citation&cd=1

答:
I ran into the same issue trying to download a file on an Amazon 3S url. I blogged about it here:
http://blog.cdeutsch.com/2010/11/net-webclient-403-forbidden-error.html

The final solution I used was found here:
GETting a URL with an url-encoded slash

Title: WebClient 403 Forbidden

Body:
I can download this by hand in IE.

http://scholar.google.com/scholar.ris?q=info:j8ymU9rzMsEJ:scholar.google.com/&output=citation&hl=zh-CN&as_sdt=2000&oe=GB&ct=citation&cd=0

But, using follow code

WebClient client = new WebClient();
client.DownloadFile(address, filename);

Show Exception:
403 Forbidden

What's wrong?
How can I do that?

others

http://scholar.google.com/scholar.ris?q=info:sskrpr5jlLwJ:scholar.google.com/&output=citation&hl=zh-CN&as_sdt=2000&oe=GB&ct=citation&cd=1

ContentLicense: CC BY-SA 2.5


问:
Encapsulate the properties design pattern
I want to encapsulate the logic how a document is activated(boolean). When a document is activated it should be added to a list of activeDocuments and the flag should be set to true. I want to forbid the direct access to the isActive property.

```<code>class DocumentService {
      private activeDocuments : Map<DocumentModel> = new Map<DocumentModel>();

      // Activates the document and adds it to the list
      activateDocument(document: DocumentModel) {
                document.setActive();
                activeDocuments.set(document.id, document);
      }
}

class DocumentModel {
      private isActive: boolean;

      setActive() {
                this.isActive = true;
      }
}

class DocumentComponent {
      documentSelected() {
           // this.document.setActive()  - SHOULD BE FORBIDDEN because the document is not added to the activedocument list !
           this.documentService.activateDocument(this.document);
      }
}
</code>```

The only solution that i figured out for this problem is to create two interfaces DocumentServiceInterface that has a setActive() method and DocumentInterface that doesn't have it so it prevents the |DocumentComponent to activate the document but the service can still activate the document.

Is there a design pattern/ recipe that can solve this ?

Iterating through the list of documents to check if it's active or not is not an option because the structure is much more complex in the application and the number of documents should scale (for example there could be multiple thousand documents)

答:
A javascript specific way to do it would be like:

```<code>setActive() {
    if (arguments.callee.caller.toString()!=='DocumentService')
         throw new Exception();
}
</code>```

but i find it quite unconventional and hard to read

Body:
I want to encapsulate the logic how a document is activated(boolean). When a document is activated it should be added to a list of activeDocuments and the flag should be set to true. I want to forbid the direct access to the isActive property.

class DocumentService {
      private activeDocuments : Map<DocumentModel> = new Map<DocumentModel>();

      // Activates the document and adds it to the list
      activateDocument(document: DocumentModel) {
                document.setActive();
                activeDocuments.set(document.id, document);
      }
}

class DocumentModel {
      private isActive: boolean;

      setActive() {
                this.isActive = true;
      }
}

class DocumentComponent {
      documentSelected() {
           // this.document.setActive()  - SHOULD BE FORBIDDEN because the document is not added to the activedocument list !
           this.documentService.activateDocument(this.document);
      }
}

The only solution that i figured out for this problem is to create two interfaces DocumentServiceInterface that has a setActive() method and DocumentInterface that doesn't have it so it prevents the |DocumentComponent to activate the document but the service can still activate the document.

Is there a design pattern/ recipe that can solve this ?

Iterating through the list of documents to check if it's active or not is not an option because the structure is much more complex in the application and the number of documents should scale (for example there could be multiple thousand documents)

Body:
A javascript specific way to do it would be like:

setActive() {
    if (arguments.callee.caller.toString()!=='DocumentService')
         throw new Exception();
}

but i find it quite unconventional and hard to read


问:
Xamarin.Forms+Prism Navigation target control
I have a Xamarin app made up of several page types. I'm using Prism.

I'd like the navigation target of the app to be a nested view in the app within the main page, not the main page itself, so that the MainPage is used as an outer frame that's always there, and a nested page hosts the app's navigation service.

In this way I can have some controls (i.e. back/forward/home) always present.
How do I configure the NavigationService's 'MainPage' to be a nested page within the actual MainPage?

I'm pretty new to XF, and haven't used the NavigationPage before, but could it be of any use here?

答:
I have one approach. Not exactly what you want, but could give you food for thought. You could create SomeBaseContentPage with SomeContent property:

```<code>public View SomeContent
{
  set
  {
    someGrid.Children.Add(value);
  }
}
</code>```

Then derive your SomeContentPageA from SomeBaseContentPage and in XAML put your specific content into property <SomeBaseContentPage.SomeContent>.

Body:
I have one approach. Not exactly what you want, but could give you food for thought. You could create SomeBaseContentPage with SomeContent property:

public View SomeContent
{
  set
  {
    someGrid.Children.Add(value);
  }
}

Then derive your SomeContentPageA from SomeBaseContentPage and in XAML put your specific content into property <SomeBaseContentPage.SomeContent>.


问:
What are Java's primitive types?
What are primitive type in Java?

What is the difference between a primitive type and a reference type?

How many primitive types does Java have, and what are they?

答:
There are two divisions in data types which are primitives and reference .
The primitives will represent the following

Numbers

Boolean

Float

Double

Char

Under the numbers we have

Byte: -128 to 127

Short: -32,768 to 32,767

Int: -2^31 to 2^31

Long: -2^63 to 2^63 - 1

These will represent numbers and have different memory allocations to save memory we can use it efficiently. Among int and long we have signed & unsigned. Unsigned starts with min=0.

Title: What are Java's primitive types?


问:
On Android 5.0 lollipop maybe due to depricated getRunningTask() method
Application is working with in Kitkat version. After lollipop version application is not working properly. I am thinking problem with getRunningTasks() . Could you please give me guidance ,How to overcome this problem.

```<code>public class StartupServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    //Log.d("Detector", "Auto Start" + AppLockerPreference.getInstance(context).isAutoStart());
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){

        if (AppLockerPreference.getInstance(context).isAutoStart()){

            if (AppLockerPreference.getInstance(context).isServiceEnabled()){

                context.startService(new Intent(context, DetectorService.class));

            }else{
                AppLockerPreference.getInstance(context).saveServiceEnabled(false);

            }
        }
        return;
    }else if (AppLockerPreference.getInstance(context).isServiceEnabled()){
         Toast.makeText(context, "App------>6", Toast.LENGTH_SHORT).show();
        context.startService(new Intent(context, DetectorService.class));
    }
}
}
</code>```

DetectorService

```<code>public class DetectorService extends Service {
//public static final String ACTION_DETECTOR_SERVICE = "com.gueei.detector.service";

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private static final Class<?>[] mStartForegroundSignature = new Class[] {
    int.class, Notification.class};
private static final Class<?>[] mStopForegroundSignature = new Class[] {
    boolean.class};

private NotificationManager mNM;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];

/**
 * This is a wrapper around the new startForeground method, using the older
 * APIs if it is not available.
 */
void startForegroundCompat(int id, Notification notification) {
    // If we have the new startForeground API, then use it.
    if (mStartForeground != null) {
        mStartForegroundArgs[0] = Integer.valueOf(id);
        mStartForegroundArgs[1] = notification;
        try {
            mStartForeground.invoke(this, mStartForegroundArgs);
        } catch (InvocationTargetException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke startForeground", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke startForeground", e);
        }
        return;
    }

    // Fall back on the old API.
    stopForeground(true);
    mNM.notify(id, notification);
}

/**
 * This is a wrapper around the new stopForeground method, using the older
 * APIs if it is not available.
 */
void stopForegroundCompat(int id) {
    // If we have the new stopForeground API, then use it.
    if (mStopForeground != null) {
        mStopForegroundArgs[0] = Boolean.TRUE;
        try {
            mStopForeground.invoke(this, mStopForegroundArgs);
        } catch (InvocationTargetException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke stopForeground", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke stopForeground", e);
        }
        return;
    }

    // Fall back on the old API.  Note to cancel BEFORE changing the
    // foreground state, since we could be killed at that point.
    mNM.cancel(id);
    stopForeground(false);
}

@Override
public void onCreate() {
    //debug: log.i("Detector","Service.Oncreate");
    initConstant();
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    try {
        mStartForeground = getClass().getMethod("startForeground",
                mStartForegroundSignature);
        mStopForeground = getClass().getMethod("stopForeground",
                mStopForegroundSignature);
    } catch (NoSuchMethodException e) {
        // Running on an older platform.
        mStartForeground = mStopForeground = null;
    }
}

@Override
public void onDestroy() {
    //debug: log.i("Detector","Service.Ondestroy");
    mThread.interrupt();

    // Make sure our notification is gone.
    stopForegroundCompat(R.string.service_running);
}

 // This is the old onStart method that will be called on the pre-2.0
// platform.  On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
    //debug: log.i("Detector","Service.Onstart");
    handleCommand(intent);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //debug: log.i("Detector","Service.OnStartCommand");
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return Service.START_STICKY;
}

private void handleCommand(Intent intent){
    // In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.service_running);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.statusbar_icon, text,
            System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, AppLockerActivity.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, text,
                   text, contentIntent);

    startForegroundCompat(R.string.service_running, notification);

    startMonitorThread((ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE));
}

private void startMonitorThread(final ActivityManager am){
    if (mThread!=null)
        mThread.interrupt();

    mThread = new MonitorlogThread(new ActivityStartingHandler(this));
    mThread.start();
}

private static Thread mThread;
private static boolean constantInited = false;
private static Pattern ActivityNamePattern;
private static String logCatCommand;
private static String ClearlogCatCommand;

private void initConstant() {
    //debug: log.i("Detector","Service.OninitConstant");
    if (constantInited) return;
    String pattern = getResources().getString(R.string.activity_name_pattern);
    //debug: log.d("Detector", "pattern: " + pattern);
    ActivityNamePattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    logCatCommand = getResources().getString(R.string.logcat_command);
    ClearlogCatCommand = getResources().getString(R.string.logcat_clear_command);
}
</code>```

MonitorlogThread

```<code>private class MonitorlogThread extends Thread{

    ActivityStartingListener mListener;
    public MonitorlogThread(ActivityStartingListener listener){
        //debug: log.i("Detector","Monitor//debug: logThread");
        mListener = listener;
    }

    BufferedReader br;
    private Context context;

    @Override
    public void run() {

        //debug: log.i("Detector","RUN!");

        while(!this.isInterrupted() ){

            try {
                Thread.sleep(100);
                ////debug: log.i("Detector","try!");
                //This is the code I use in my service to identify the current foreground application, its really easy:

                ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
                // The first in the list of RunningTasks is always the foreground task.
                 //Toast.makeText(context, "App------>7", Toast.LENGTH_SHORT).show();
                Log.d("Android", "App------>7----"+am);

                //RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
                RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);

                Log.d("Android", "App------>8----"+foregroundTaskInfo);

                //Toast.makeText(context, "App------>7"+foregroundTaskInfo, Toast.LENGTH_SHORT).show();

                //Thats it, then you can easily access details of the foreground app/activity:
                String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
                PackageManager pm = getBaseContext().getPackageManager();
                PackageInfo foregroundAppPackageInfo = null;
                String foregroundTaskAppName = null;
                String foregroundTaskActivityName = foregroundTaskInfo.topActivity.getShortClassName().toString();
                try {
                    foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
                    foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

                    //debug: log.i("Detector",foregroundTaskAppName);
                } catch (NameNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (mListener!=null){
                    //mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskAppName);
                    mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskActivityName);
                }

              } catch (InterruptedException e) {
                  // good practice
                  Thread.currentThread().interrupt();
                  return;
              }
        }

}
}
</code>```

答:
Use RunningAppProcessInfo instead of getRunningTasks for SDK versions greater than KitKat.</p>

```<code>ActivityManager am = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
    List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
    ...
} else {
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    ...
}
</code>```

Body:
Application is working with in Kitkat version. After lollipop version application is not working properly. I am thinking problem with getRunningTasks() . Could you please give me guidance ,How to overcome this problem.

public class StartupServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    //Log.d("Detector", "Auto Start" + AppLockerPreference.getInstance(context).isAutoStart());
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){

        if (AppLockerPreference.getInstance(context).isAutoStart()){

            if (AppLockerPreference.getInstance(context).isServiceEnabled()){

                context.startService(new Intent(context, DetectorService.class));

            }else{
                AppLockerPreference.getInstance(context).saveServiceEnabled(false);

            }
        }
        return;
    }else if (AppLockerPreference.getInstance(context).isServiceEnabled()){
         Toast.makeText(context, "App------>6", Toast.LENGTH_SHORT).show();
        context.startService(new Intent(context, DetectorService.class));
    }
}
}

DetectorService

public class DetectorService extends Service {
//public static final String ACTION_DETECTOR_SERVICE = "com.gueei.detector.service";

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private static final Class<?>[] mStartForegroundSignature = new Class[] {
    int.class, Notification.class};
private static final Class<?>[] mStopForegroundSignature = new Class[] {
    boolean.class};

private NotificationManager mNM;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];

/**
 * This is a wrapper around the new startForeground method, using the older
 * APIs if it is not available.
 */
void startForegroundCompat(int id, Notification notification) {
    // If we have the new startForeground API, then use it.
    if (mStartForeground != null) {
        mStartForegroundArgs[0] = Integer.valueOf(id);
        mStartForegroundArgs[1] = notification;
        try {
            mStartForeground.invoke(this, mStartForegroundArgs);
        } catch (InvocationTargetException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke startForeground", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke startForeground", e);
        }
        return;
    }

    // Fall back on the old API.
    stopForeground(true);
    mNM.notify(id, notification);
}

/**
 * This is a wrapper around the new stopForeground method, using the older
 * APIs if it is not available.
 */
void stopForegroundCompat(int id) {
    // If we have the new stopForeground API, then use it.
    if (mStopForeground != null) {
        mStopForegroundArgs[0] = Boolean.TRUE;
        try {
            mStopForeground.invoke(this, mStopForegroundArgs);
        } catch (InvocationTargetException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke stopForeground", e);
        } catch (IllegalAccessException e) {
            // Should not happen.
            //debug: log.w("Detector", "Unable to invoke stopForeground", e);
        }
        return;
    }

    // Fall back on the old API.  Note to cancel BEFORE changing the
    // foreground state, since we could be killed at that point.
    mNM.cancel(id);
    stopForeground(false);
}

@Override
public void onCreate() {
    //debug: log.i("Detector","Service.Oncreate");
    initConstant();
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    try {
        mStartForeground = getClass().getMethod("startForeground",
                mStartForegroundSignature);
        mStopForeground = getClass().getMethod("stopForeground",
                mStopForegroundSignature);
    } catch (NoSuchMethodException e) {
        // Running on an older platform.
        mStartForeground = mStopForeground = null;
    }
}

@Override
public void onDestroy() {
    //debug: log.i("Detector","Service.Ondestroy");
    mThread.interrupt();

    // Make sure our notification is gone.
    stopForegroundCompat(R.string.service_running);
}

 // This is the old onStart method that will be called on the pre-2.0
// platform.  On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
    //debug: log.i("Detector","Service.Onstart");
    handleCommand(intent);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //debug: log.i("Detector","Service.OnStartCommand");
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return Service.START_STICKY;
}

private void handleCommand(Intent intent){
    // In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.service_running);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.statusbar_icon, text,
            System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, AppLockerActivity.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, text,
                   text, contentIntent);

    startForegroundCompat(R.string.service_running, notification);

    startMonitorThread((ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE));
}

private void startMonitorThread(final ActivityManager am){
    if (mThread!=null)
        mThread.interrupt();

    mThread = new MonitorlogThread(new ActivityStartingHandler(this));
    mThread.start();
}

private static Thread mThread;
private static boolean constantInited = false;
private static Pattern ActivityNamePattern;
private static String logCatCommand;
private static String ClearlogCatCommand;

private void initConstant() {
    //debug: log.i("Detector","Service.OninitConstant");
    if (constantInited) return;
    String pattern = getResources().getString(R.string.activity_name_pattern);
    //debug: log.d("Detector", "pattern: " + pattern);
    ActivityNamePattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    logCatCommand = getResources().getString(R.string.logcat_command);
    ClearlogCatCommand = getResources().getString(R.string.logcat_clear_command);
}

MonitorlogThread

private class MonitorlogThread extends Thread{

    ActivityStartingListener mListener;
    public MonitorlogThread(ActivityStartingListener listener){
        //debug: log.i("Detector","Monitor//debug: logThread");
        mListener = listener;
    }

    BufferedReader br;
    private Context context;

    @Override
    public void run() {

        //debug: log.i("Detector","RUN!");

        while(!this.isInterrupted() ){

            try {
                Thread.sleep(100);
                ////debug: log.i("Detector","try!");
                //This is the code I use in my service to identify the current foreground application, its really easy:

                ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
                // The first in the list of RunningTasks is always the foreground task.
                 //Toast.makeText(context, "App------>7", Toast.LENGTH_SHORT).show();
                Log.d("Android", "App------>7----"+am);

                //RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
                RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);

                Log.d("Android", "App------>8----"+foregroundTaskInfo);

                //Toast.makeText(context, "App------>7"+foregroundTaskInfo, Toast.LENGTH_SHORT).show();

                //Thats it, then you can easily access details of the foreground app/activity:
                String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
                PackageManager pm = getBaseContext().getPackageManager();
                PackageInfo foregroundAppPackageInfo = null;
                String foregroundTaskAppName = null;
                String foregroundTaskActivityName = foregroundTaskInfo.topActivity.getShortClassName().toString();
                try {
                    foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
                    foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

                    //debug: log.i("Detector",foregroundTaskAppName);
                } catch (NameNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                if (mListener!=null){
                    //mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskAppName);
                    mListener.onActivityStarting(foregroundAppPackageInfo.packageName,foregroundTaskActivityName);
                }

              } catch (InterruptedException e) {
                  // good practice
                  Thread.currentThread().interrupt();
                  return;
              }
        }

}
}

Body:
Use RunningAppProcessInfo instead of getRunningTasks for SDK versions greater than KitKat.

ActivityManager am = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
    List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
    ...
} else {
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    ...
}


问:
laravel ORM merge two json arrays
Excuse me, I use laravel ORM have two json arrays , like this:

php

```<code>$personnels = Personnel::all();
$skills = Languagelv::all();
return view('bs_sidebar/recommend',[
            'personnels' => $personnels,
            'skills' => $skills,
]);
</code>```

model

```<code>class Personnel extends Model
{
    protected $table = 'personnels';

    protected $fillable = ['name', 'sex'];
}

class Personnels_skill extends Model
{
    public $timestamps = false;
    protected $table = 'personnels_skill';
    protected $fillable = ['skill_name','personnels_id'];
}
</code>```

json result

```<code>{personnels:[
    {"id" : 1,"name"  : "bruce","sex"   : 1},
    {"id" : 2,"name" : "peter","sex"  : 0}
    ]
};
{skill:[
        {"id" : 1,"skill_name": 'php', "personnels_id" : 1},
        {"id" : 2,"skill_name": 'jsp',"personnels_id" : 1},
        {"id" : 3,"skill_name": 'asp',"personnels_id" : 2}
       ]
};
</code>```

I want to merge two json arrays

(personnels id = skill personnels_id )

skill arrays is into personnels arrays

like this result:

```<code>{merge:[
        {"id":1,"name":"bruce","sex:1,"skill":[{"id": 1,"skill_name": 'php', "personnels_id" : 1},{"id": 2,"skill_name": 'jsp',"personnels_id" : 1}]},

        {"id":2,"name":"peter","sex":0,"skill":[{"id": 3,"skill_name": 'asp',"personnels_id" : 2}
        ]
};
</code>```

How can I do , please help me, thank you.

答:
If you have your relationships correctly configured in your models, you should be able to do the following:

```<code>$personnel = Personnel::with('skills')->get();
return view('bs_sidebar/recommend', compact('personnel'));
</code>```

Edit
Given your models, if you add the following relationships you will be able to use the Eloquent query above.

```<code>class Personnel extends Model
{
    protected $table = 'personnels';

    protected $fillable = [
        'name',
        'sex',
    ];

    public function skills()
    {
        return $this->hasMany(Personnels_skill::class, 'personnel_id', 'id');
    }
}

class Personnels_skill extends Model
{
    protected $table = 'personnels_skill';

    protected $fillable = [
        'personnel_id',
        'skill_name',
    ];

    public $timestamps = false;

    public function personnel()
    {
        return $this->belongsTo(Personnel::class, 'id', 'personnel_id');
    }
}
</code>```

Title: laravel ORM merge two json arrays

Body:
Excuse me, I use laravel ORM have two json arrays , like this:

php

$personnels = Personnel::all();
$skills = Languagelv::all();
return view('bs_sidebar/recommend',[
            'personnels' => $personnels,
            'skills' => $skills,
]);

model

class Personnel extends Model
{
    protected $table = 'personnels';

    protected $fillable = ['name', 'sex'];
}

class Personnels_skill extends Model
{
    public $timestamps = false;
    protected $table = 'personnels_skill';
    protected $fillable = ['skill_name','personnels_id'];
}

json result

{personnels:[
    {"id" : 1,"name"  : "bruce","sex"   : 1},
    {"id" : 2,"name" : "peter","sex"  : 0}
    ]
};
{skill:[
        {"id" : 1,"skill_name": 'php', "personnels_id" : 1},
        {"id" : 2,"skill_name": 'jsp',"personnels_id" : 1},
        {"id" : 3,"skill_name": 'asp',"personnels_id" : 2}
       ]
};

I want to merge two json arrays

(personnels id = skill personnels_id )

skill arrays is into personnels arrays

like this result:

{merge:[
        {"id":1,"name":"bruce","sex:1,"skill":[{"id": 1,"skill_name": 'php', "personnels_id" : 1},{"id": 2,"skill_name": 'jsp',"personnels_id" : 1}]},

        {"id":2,"name":"peter","sex":0,"skill":[{"id": 3,"skill_name": 'asp',"personnels_id" : 2}
        ]
};

How can I do , please help me, thank you.

Body:
If you have your relationships correctly configured in your models, you should be able to do the following:

$personnel = Personnel::with('skills')->get();
return view('bs_sidebar/recommend', compact('personnel'));

Edit
Given your models, if you add the following relationships you will be able to use the Eloquent query above.

class Personnel extends Model
{
    protected $table = 'personnels';

    protected $fillable = [
        'name',
        'sex',
    ];

    public function skills()
    {
        return $this->hasMany(Personnels_skill::class, 'personnel_id', 'id');
    }
}

class Personnels_skill extends Model
{
    protected $table = 'personnels_skill';

    protected $fillable = [
        'personnel_id',
        'skill_name',
    ];

    public $timestamps = false;

    public function personnel()
    {
        return $this->belongsTo(Personnel::class, 'id', 'personnel_id');
    }
}


问:
Mocking open function with mock_open
So I have function in my Django app business logic I want to test:

```<code>def parse_sectors_from_csv():
    sectors_csv = open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv'))
    sectors_csv_reader = csv.DictReader(sectors_csv)
    return [
        {
            'model': 'sector.sector',
            'id': index,
            'fields': {
                'name': row.get('Sector'),
                'slug': slugify(row['Sector']),
                'type_id': row.get('Type_Id')
            }
        }
        for index, row in enumerate(sectors_csv_reader, 1)
    ]
</code>```

I already test it for file existence and for existence of heading row.

Now I want to mock

```<code>open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv'))
</code>```

In my test.py I wrote

```<code>with patch('__builtin__.open', mock_open(read_data=sectors_csv_mock), create=True) as m:
        sectors = service.parse_sectors_from_csv()
        print('Sectors:', sectors)
        self.assertEqual(expected_sectors, sectors)
</code>```

But as I understand, it's passes empty file to function as it prints Sectors: []

I read mock_open dock for a few times and still can't figure it out.

```<code>>>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
...     with open('foo') as h: # what's happening here?
...         result = h.read() # here?
...
>>> m.assert_called_once_with('foo') # and here?
>>> assert result == 'bibble'
</code>```

答:
Whenever I feel the need to mock, I first ask myself whether it's
feasible to refactor the code along these lines:

Stuff that is algorithmically non-trivial and that I might want to unit test
with actual assertions.

Stuff so simple that I either (a) hardly need to test it or (b) could
sufficiently test with a single end-to-end test that merely exercises the code
without making any assertions.

For example:

```<code>####
# Hardly worth testing.
####

def parse_sectors_from_csv():
    file_path = sectors_file_path()
    with open(file_path) as fh:
        return do_parse_sectors_from_csv(fh)

####
# Easily tested without mocks.
####

def do_parse_sectors_from_csv(fh):
    reader = csv.DictReader(fh)
    return do_parse_sectors_from_csv(reader)

def sectors_file_path():
    return os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv')

def parse_sectors_from_csv(rows):
    return [
        {
            'model': 'sector.sector',
            'id': index,
            'fields': {
                'name': row.get('Sector'),
                'slug': slugify(row['Sector']),
                'type_id': row.get('Type_Id')
            }
        }
        for index, row in enumerate(rows, 1)
    ]
</code>```

Title: Mocking open function with mock_open

Body:
So I have function in my Django app business logic I want to test:

def parse_sectors_from_csv():
    sectors_csv = open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv'))
    sectors_csv_reader = csv.DictReader(sectors_csv)
    return [
        {
            'model': 'sector.sector',
            'id': index,
            'fields': {
                'name': row.get('Sector'),
                'slug': slugify(row['Sector']),
                'type_id': row.get('Type_Id')
            }
        }
        for index, row in enumerate(sectors_csv_reader, 1)
    ]

I already test it for file existence and for existence of heading row.

Now I want to mock

open(os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv'))

In my test.py I wrote

with patch('__builtin__.open', mock_open(read_data=sectors_csv_mock), create=True) as m:
        sectors = service.parse_sectors_from_csv()
        print('Sectors:', sectors)
        self.assertEqual(expected_sectors, sectors)

But as I understand, it's passes empty file to function as it prints Sectors: []

I read mock_open dock for a few times and still can't figure it out.

>>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
...     with open('foo') as h: # what's happening here?
...         result = h.read() # here?
...
>>> m.assert_called_once_with('foo') # and here?
>>> assert result == 'bibble'

Body:
Whenever I feel the need to mock, I first ask myself whether it's
feasible to refactor the code along these lines:

Stuff that is algorithmically non-trivial and that I might want to unit test
with actual assertions.

Stuff so simple that I either (a) hardly need to test it or (b) could
sufficiently test with a single end-to-end test that merely exercises the code
without making any assertions.

For example:

####
# Hardly worth testing.
####

def parse_sectors_from_csv():
    file_path = sectors_file_path()
    with open(file_path) as fh:
        return do_parse_sectors_from_csv(fh)

####
# Easily tested without mocks.
####

def do_parse_sectors_from_csv(fh):
    reader = csv.DictReader(fh)
    return do_parse_sectors_from_csv(reader)

def sectors_file_path():
    return os.path.join(settings.BASE_DIR, 'sector', 'fixtures', 'sectors.csv')

def parse_sectors_from_csv(rows):
    return [
        {
            'model': 'sector.sector',
            'id': index,
            'fields': {
                'name': row.get('Sector'),
                'slug': slugify(row['Sector']),
                'type_id': row.get('Type_Id')
            }
        }
        for index, row in enumerate(rows, 1)
    ]


问:
Changing level of logging dynamically
I want to change the level of logging for all (about) of my web application controller classes dynamically. Each class that does logging contains this code:

```<code>private static final Logger logger = LoggerFactory
            .getLogger(HomeController.class);
</code>```

I learned that slf4j doesn't offer the functionality of setting a log level, so that one has to use the underlying log4j:

```<code>public static void setLogLevel(String level) {
    org.apache.log4j.Logger logger4j = org.apache.log4j.Logger.getRootLogger();
    logger4j.setLevel(org.apache.log4j.Level.toLevel(level.toUpperCase()));

    logger.info("Sample Info After setLevel");
    logger.debug("Sample Debug After setLevel");
    logger.error("Sample Error After setLevel");
    logger.trace("Sample Trace After setLevel");
    logger.warn("Sample Warn After setLevel");
}
</code>```

My idea is to have a controller method which changes the logLevel and maybe stores it in the database. My question is: How I can solve this elegantly without copy and pasting everything in 40+ files and modifying every controller method? Also note that the logger code is static, while my database access is not static.

答:
How I can solve this elegantly without copy and pasting everything in 40+ files and modifying every controller method?

You use a single controller method, taking the logger name and desired log level as a query parameters, and call the string version of LogManager.getLogger(String name).

Also saving to the database and re-loading on restart is of course extra work to be done by you.

Alternatively, the controller can update the Log4j configuration file used at startup, and force Log4j to reload it whenever it's changed, e.g. by calling PropertyConfigurator.configure(String configFilename).

Title: Changing level of logging dynamically

Body:
I want to change the level of logging for all (about) of my web application controller classes dynamically. Each class that does logging contains this code:

private static final Logger logger = LoggerFactory
            .getLogger(HomeController.class);

I learned that slf4j doesn't offer the functionality of setting a log level, so that one has to use the underlying log4j:

public static void setLogLevel(String level) {
    org.apache.log4j.Logger logger4j = org.apache.log4j.Logger.getRootLogger();
    logger4j.setLevel(org.apache.log4j.Level.toLevel(level.toUpperCase()));

    logger.info("Sample Info After setLevel");
    logger.debug("Sample Debug After setLevel");
    logger.error("Sample Error After setLevel");
    logger.trace("Sample Trace After setLevel");
    logger.warn("Sample Warn After setLevel");
}

My idea is to have a controller method which changes the logLevel and maybe stores it in the database. My question is: How I can solve this elegantly without copy and pasting everything in 40+ files and modifying every controller method? Also note that the logger code is static, while my database access is not static.


问:
Extending a trait and types
I would like to have a sealed trait which have a declared method that returns the
actual class that extends the trait. Should I use an abstract type, a parameter type or
is there any other nice way to solve this?

```<code>sealed trait Foo {
  type T
  def doit(other: T): T
}
</code>```

or

```<code>sealed trait Foo[T] {
  def doit(other: T): T
}
</code>```

Note that T must be a subtype of Foo in this example. If I do it like this the type
information feels too repeated:

```<code>case class Bar(name: String) extends Foo[Bar] {
  def doit(other: Bar): Bar = ...
}
</code>```

答:
You can cut down on the repetition somewhat by having your doit method return a factory function:

```<code>trait Foo[T] {
   self: T =>
   def doit: T => T
}

case class Bar(name: String) extends Foo[Bar] {
   // note: types omitted
   def doit = { other => Bar(name + other.name) }
}
</code>```

It's not possible to do the same with an abstract type:

```<code>trait Foo {
   self: T => // won't compile because T isn't defined yet
   type T
   def doit: T => T
}
</code>```

Title: Extending a trait and types

Body:
I would like to have a sealed trait which have a declared method that returns the
actual class that extends the trait. Should I use an abstract type, a parameter type or
is there any other nice way to solve this?

sealed trait Foo {
  type T
  def doit(other: T): T
}

or

sealed trait Foo[T] {
  def doit(other: T): T
}

Note that T must be a subtype of Foo in this example. If I do it like this the type
information feels too repeated:

case class Bar(name: String) extends Foo[Bar] {
  def doit(other: Bar): Bar = ...
}

Body:
You can cut down on the repetition somewhat by having your doit method return a factory function:

trait Foo[T] {
   self: T =>
   def doit: T => T
}

case class Bar(name: String) extends Foo[Bar] {
   // note: types omitted
   def doit = { other => Bar(name + other.name) }
}

It's not possible to do the same with an abstract type:

trait Foo {
   self: T => // won't compile because T isn't defined yet
   type T
   def doit: T => T
}


问:
Scroll button hide after 5 seconds using jQuery?
I can scroll on the top or the bottom of my page. But after 5seconds, I want my scroll div disapear. I use the property delay & hide of Jquery.
I must refresh my page to works my code once my div disapear.</p>

```<code>$(function () {

        var scrollTrigger = 100, // px
                backToTop = function () {
                    var scrollTop = $(window).scrollTop();
                    if (scrollTop > scrollTrigger) {

                        $("a[href='#top']").addClass('show').delay(2000).hide(500);
                        $("a[href='#bottom']").addClass('show').delay(2000).hide(500);

                    } else {
                        $("a[href='#top']").removeClass('show');
                        $("a[href='#bottom']").removeClass('show');
                    }
                };
        backToTop();

        $(window).on('scroll', function () {
            backToTop();
        });
        $("a[href='#top']").click(function() {
            $("html, body").animate({ scrollTop: 0 }, "slow");
            return false;
        });

        $("a[href='#bottom']").click(function() {
        $('html,body').animate({ scrollTop: 9999 }, 'slow');
        return false;
        });
    });
</code>```

答:
Here's a function :

```<code>var goToTop = function(){
  window.scrollTo(0,/*y-coordinate (should be 0 if well-designed website)*/);
  setTimeout(function(){$(this).hide(500);},5000);
}
</code>```

Use it as a click event bind on your button just like :

```<code>$(document).ready(
  $(my button JQ selector).click(goToTop);
);
</code>```

Then, when you scroll you should show(500)'it again.

Body:
I can scroll on the top or the bottom of my page. But after 5seconds, I want my scroll div disapear. I use the property delay & hide of Jquery.
I must refresh my page to works my code once my div disapear.

$(function () {

        var scrollTrigger = 100, // px
                backToTop = function () {
                    var scrollTop = $(window).scrollTop();
                    if (scrollTop > scrollTrigger) {

                        $("a[href='#top']").addClass('show').delay(2000).hide(500);
                        $("a[href='#bottom']").addClass('show').delay(2000).hide(500);

                    } else {
                        $("a[href='#top']").removeClass('show');
                        $("a[href='#bottom']").removeClass('show');
                    }
                };
        backToTop();

        $(window).on('scroll', function () {
            backToTop();
        });
        $("a[href='#top']").click(function() {
            $("html, body").animate({ scrollTop: 0 }, "slow");
            return false;
        });

        $("a[href='#bottom']").click(function() {
        $('html,body').animate({ scrollTop: 9999 }, 'slow');
        return false;
        });
    });

Body:
Here's a function :

var goToTop = function(){
  window.scrollTo(0,/*y-coordinate (should be 0 if well-designed website)*/);
  setTimeout(function(){$(this).hide(500);},5000);
}

Use it as a click event bind on your button just like :

$(document).ready(
  $(my button JQ selector).click(goToTop);
);

Then, when you scroll you should show(500)'it again.


问:
ShowDialog call on OpenFileDialog crashing WPF application because of SQLite
I am developing a WPF application (x64, .Net 4 ) using Visual Studio 2015. As a part of Application Home Page, I have a button which will open File Browser.

The Button Click event is as follows...

```<code>openFileDialog.InitialDirectory = Environment.SpecialFolder.Personal.ToString();
openFileDialog.Title = "Select Profile Configuration Files";
openFileDialog.Filter = "Profile Config Files (*.cfg)|*.cfg|All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;

if (openFileDialog.ShowDialog() == true)
{
     try
     {
         _LoadConfigProfile(openFileDialog.FileName.ToString());
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message, "Error Opening Prfile", MessageBoxButton.OK, MessageBoxImage.Error);
     }
}
</code>```

But, everytime I am clicking the button, File Browser is opening, but then within a second, the application is getting crashed.
Using Breakpoints, I have figured out the crash is occuring in the line openFileDialog.ShowDialog().

The error, shown in VS2015 is as follows

Call Stack is as follows

As a part of the application, I am using SQLite to handle some data. I have opened a DataBase Connection at the beginning of Application.

Has anyone faced such problem before ? How can I solve this ?

Comment if you want any more information regarding the application and the error.

答:
The file selector is in the common control DLL that is probably not loaded in a WPF application until you call create an OpenFileDialog object. Check the output log to see that it isn't loading a different (additional) sqlite.dll at this point.

As mentioned in the comments, I had this problem and I had avoided using file selectors before, but with a new requirement I had to add one and on doing so the application crashed again just after the file selector dialog shows.

If you look at the output log, it shows the line number in the sqlite source which is a thrown exception in sqlite3_config if it is called while the library is already in use.
Looking further back in the output log shows that just before this exception occurred, commoncontrols.dll and an additional sqlite.dll were loaded from from C:\Program Files(x86)\Dell Backup And Recovery\ - i.e., a different sqlite.dll than was already in use, and certainly not a location for a library, but presumably earlier in the path. I uninstalled Dell Backup and Recovery and the error no longer occurs.

Body:
I am developing a WPF application (x64, .Net 4 ) using Visual Studio 2015. As a part of Application Home Page, I have a button which will open File Browser.

The Button Click event is as follows...

openFileDialog.InitialDirectory = Environment.SpecialFolder.Personal.ToString();
openFileDialog.Title = "Select Profile Configuration Files";
openFileDialog.Filter = "Profile Config Files (*.cfg)|*.cfg|All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;

if (openFileDialog.ShowDialog() == true)
{
     try
     {
         _LoadConfigProfile(openFileDialog.FileName.ToString());
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message, "Error Opening Prfile", MessageBoxButton.OK, MessageBoxImage.Error);
     }
}

But, everytime I am clicking the button, File Browser is opening, but then within a second, the application is getting crashed.
Using Breakpoints, I have figured out the crash is occuring in the line openFileDialog.ShowDialog().

The error, shown in VS2015 is as follows

Call Stack is as follows

As a part of the application, I am using SQLite to handle some data. I have opened a DataBase Connection at the beginning of Application.

Has anyone faced such problem before ? How can I solve this ?

Comment if you want any more information regarding the application and the error.


问:
Python: Set permissions for pip or conda in /opt directory
I installed python via Anaconda to my /opt directory (I heard that's the proper way when all users should be able to use it).

Everything is working fine so far, up to the point when I try to install packages via pip or conda. Than I get permission issues for both ways.
When I try to do:

```<code>sudo pip install pandas-datareader
</code>```

I get:

```<code>sudo: pip: command not found
</code>```

and the same error results if I try to use conda as well.

Does anyone have an idea how to fix that?

答:
The /opt folder is not in the global path, so when you sudo it is not available.

You may want to sudo -E to preserve any environment variables, which will likely include a customization to the PATH variable to include the directory where pip is installed in /opt

Alternatively, you can give the full path to the command sudo /opt/anaconda-path/bin/pip

Body:
I installed python via Anaconda to my /opt directory (I heard that's the proper way when all users should be able to use it).

Everything is working fine so far, up to the point when I try to install packages via pip or conda. Than I get permission issues for both ways.
When I try to do:

sudo pip install pandas-datareader

I get:

sudo: pip: command not found

and the same error results if I try to use conda as well.

Does anyone have an idea how to fix that?


答:
You can use Slf4j and externalize your application.properties file . You can configure the logging level in this file as per your needs.

```<code>logging.level.com.test=DEBUG
logging.level.org=INFO
</code>```

I am not sure why you need to store this logging level in the Database.

Title: Changing level of logging dynamically

Body:
You can use Slf4j and externalize your application.properties file . You can configure the logging level in this file as per your needs.

logging.level.com.test=DEBUG
logging.level.org=INFO

I am not sure why you need to store this logging level in the Database.


问:
Why I'm getting trash on this pipe?
I'm running a full-duplex server/client code I found on Oracle's website:

When writing ./fd_client hahaha I get something like:

HAHAHA0�$0

The upper case is OK (it's what the server it's supposed to return) but, how the hell do I avoid that trailing trash?

fd_client.c

```<code>#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int wrfd, rdfd, numread;
    char rdbuf[MAX_BUF_SIZE];

    /* Check if an argument was specified. */

    if (argc != 2) {
        printf("Usage : %s \n", argv[0]);
        exit (0);
    }

    /* Open the first named pipe for writing */
    wrfd = open(NP1, O_WRONLY);

    /* Open the second named pipe for reading */
    rdfd = open(NP2, O_RDONLY);

    /* Write to the pipe */
    write(wrfd, argv[1], strlen(argv[1]));

    /* Read from the pipe */
    numread = read(rdfd, rdbuf, MAX_BUF_SIZE);

    rdbuf[numread] = '0';

    printf("Full Duplex Client : Read From the  Pipe : %s\n", rdbuf);

    return 0;
}
</code>```

fd_server.c

```<code>#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int rdfd, wrfd, ret_val, count, numread;
    char buf[MAX_BUF_SIZE];

    /* Create the first named - pipe */
    ret_val = mkfifo(NP1, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    ret_val = mkfifo(NP2, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    /* Open the first named pipe for reading */
    rdfd = open(NP1, O_RDONLY);

    /* Open the second named pipe for writing */
    wrfd = open(NP2, O_WRONLY);

    /* Read from the first pipe */
    numread = read(rdfd, buf, MAX_BUF_SIZE);

    buf[numread] = '0';

    printf("Full Duplex Server : Read From the pipe : %s \n", buf);

    /* Convert to the string to upper case */
    count = 0;
    while (count < numread) {
        buf[count] = toupper(buf[count]);
        count++;
    }

    /*
     * Write the converted string back to the second
     * pipe
     */
    write(wrfd, buf, strlen(buf));
}
</code>```

fullduplex.h

```<code>#define NP1     "/tmp/np1"
#define NP2     "/tmp/np2"
#define MAX_BUF_SIZE    255
</code>```

答:
Did you mean:

```<code>rdbuf[numread] = '\0';
</code>```

buf in fd_server.c has the same problem.

Title: Why I'm getting trash on this pipe?

Body:
I'm running a full-duplex server/client code I found on Oracle's website:

When writing ./fd_client hahaha I get something like:

HAHAHA0�$0

The upper case is OK (it's what the server it's supposed to return) but, how the hell do I avoid that trailing trash?

fd_client.c

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int wrfd, rdfd, numread;
    char rdbuf[MAX_BUF_SIZE];

    /* Check if an argument was specified. */

    if (argc != 2) {
        printf("Usage : %s \n", argv[0]);
        exit (0);
    }

    /* Open the first named pipe for writing */
    wrfd = open(NP1, O_WRONLY);

    /* Open the second named pipe for reading */
    rdfd = open(NP2, O_RDONLY);

    /* Write to the pipe */
    write(wrfd, argv[1], strlen(argv[1]));

    /* Read from the pipe */
    numread = read(rdfd, rdbuf, MAX_BUF_SIZE);

    rdbuf[numread] = '0';

    printf("Full Duplex Client : Read From the  Pipe : %s\n", rdbuf);

    return 0;
}

fd_server.c

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "fullduplex.h" /* For name of the named-pipe */

int main(int argc, char *argv[])
{
    int rdfd, wrfd, ret_val, count, numread;
    char buf[MAX_BUF_SIZE];

    /* Create the first named - pipe */
    ret_val = mkfifo(NP1, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    ret_val = mkfifo(NP2, 0666);

    if ((ret_val == -1) && (errno != EEXIST)) {
        perror("Error creating the named pipe");
        exit (0);
    }

    /* Open the first named pipe for reading */
    rdfd = open(NP1, O_RDONLY);

    /* Open the second named pipe for writing */
    wrfd = open(NP2, O_WRONLY);

    /* Read from the first pipe */
    numread = read(rdfd, buf, MAX_BUF_SIZE);

    buf[numread] = '0';

    printf("Full Duplex Server : Read From the pipe : %s \n", buf);

    /* Convert to the string to upper case */
    count = 0;
    while (count < numread) {
        buf[count] = toupper(buf[count]);
        count++;
    }

    /*
     * Write the converted string back to the second
     * pipe
     */
    write(wrfd, buf, strlen(buf));
}

fullduplex.h

#define NP1     "/tmp/np1"
#define NP2     "/tmp/np2"
#define MAX_BUF_SIZE    255

Body:
Did you mean:

rdbuf[numread] = '\0';

buf in fd_server.c has the same problem.


问:
How can instantiate the type in java
```<code>package crawler;

import org.apache.http.client.*;
import org.apache.http.client.methods.*;

class Crawler{

    public static void main(String args[]){

    HttpClient httpclient = new HttpClient();     // **HERE!!!!!!!!!**

    GetMethod getMethod = new GetMethod("http://www.google.com");

    int statusCode = httpclient.executeMethod(getMethod);

    System.out.println("response=" + getMethod.getResponseBodyAsString());;

    getMethod.releaseConnection();

    }

}
</code>```

The HttpClient from Apache Httpclient.

the code:

```<code>@SuppressWarnings("deprecation")
public interface HttpClient
</code>```

how can fix the problem "HttpClient httpclient = new HttpClient(); "?
THANKS!

答: You can't instantiate an interface. You have to either implement it or create an anonymous class(which is still implement)</p>

Title: How can instantiate the type in java

Body:
package crawler;

import org.apache.http.client.*;
import org.apache.http.client.methods.*;

class Crawler{

    public static void main(String args[]){

    HttpClient httpclient = new HttpClient();     // **HERE!!!!!!!!!**

    GetMethod getMethod = new GetMethod("http://www.google.com");

    int statusCode = httpclient.executeMethod(getMethod);

    System.out.println("response=" + getMethod.getResponseBodyAsString());;

    getMethod.releaseConnection();

    }

}

The HttpClient from Apache Httpclient.

the code:

@SuppressWarnings("deprecation")
public interface HttpClient

how can fix the problem "HttpClient httpclient = new HttpClient(); "?
THANKS!


问:
Is it ok to have style tag and xml in svg embedded in html page?
I have generated some svgs with Adobe Illustrator and have embedded them inline in my html page. As far as I know all style tags must be in head but these svgs have their own style tags. Following is the example of one svg:

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 21.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" id="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 526.6 28.3" style="enable-background:new 0 0 526.6 28.3;" xml:space="preserve">
    <style type="text/css">
        .st0 {
        fill: none;
        }

        .st1 {
        enable-background: new;
        }

        .st2 {
        fill: #009444;
        }
    </style>
    <rect y="2.3" class="st0" width="526.6" height="26" />
</svg>
</code>```

The svg renders well in Firefox and Chrome. One svg appeared smaller than in other browsers in IE11 and Edge it appeared perfect. I haven't checked in Safari as I don't have mac. My question is:

Is it ok to have style tag and xml in svg embedded in html page as per w3c and browser compatibility?

P.S: In a work of mine I saw problems with inline svg in EDGE browser when appended with jquery appendTo. The svgs, set to display inline-block   overlapped each other. (The bottom case in https://anupamkhosla.github.io/marqueedirection/)

Body:
I have generated some svgs with Adobe Illustrator and have embedded them inline in my html page. As far as I know all style tags must be in head but these svgs have their own style tags. Following is the example of one svg:

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

<svg version="1.1" id="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 526.6 28.3" style="enable-background:new 0 0 526.6 28.3;" xml:space="preserve">

    <rect y="2.3" class="st0" width="526.6" height="26" />
</svg>

The svg renders well in Firefox and Chrome. One svg appeared smaller than in other browsers in IE11 and Edge it appeared perfect. I haven't checked in Safari as I don't have mac. My question is:

Is it ok to have style tag and xml in svg embedded in html page as per w3c and browser compatibility?

P.S: In a work of mine I saw problems with inline svg in EDGE browser when appended with jquery appendTo. The svgs, set to display inline-block   overlapped each other. (The bottom case in https://anupamkhosla.github.io/marqueedirection/)

Body:
You can refer MDN for these kinds of standards. As it is given in their SVG style page, you can use and it is valid to have <style>
tag inside SVG.


问:
How to fix NodeJS underutilizing CPU Cores?
According to this page Go vs Node.js, Node.js is not showing to be taking full advantage of CPU cores when running cpu-intensive code.

If I use virtualization and simply add more Node.js instances, will I achieve the same performance as Go? I suppose there still will be overheads and one won't be able to achieve the same performance.

答:
Node.js is indeed a single threaded process. However, you can make use of clustering to spawn multiple workers on multiple cores.

If you are not using PM2 for spawning the app, please consider using it. PM2 makes spawning workers on multiple cores super easy.

pm2 start app.js -i max

This command will spawn workers on each available core.

Also, note that if you are using session/sockets then you might face some problems because of clustering.


问:
How to prevent user to enter specific key using Javascript
I have a text field and I want to allow only alphabet. So I write the below Javascript method to prevent other keys. Unfortunately my text field is allowing uparrow(^).
Can any one tell me how to restrict uparrow(^) ?

```<code>function onlyAlphabet(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;

    var keychar = String.fromCharCode(key);
    var keycheck = /[a-zA-z\s]/;

    if (!(key == 8 || key == 27 || key == 46 || key == 9 || key == 39)) // backspace delete  escape arrows
    {
        if (!keycheck.test(keychar)) {
            theEvent.returnValue = false;//for IE
            if (theEvent.preventDefault)
                theEvent.preventDefault();//Firefox
        }
    }
}
</code>```

html code

```<code><div class="form-group">
   <label class="form-text">Travels Name</label>
   <h:inputText value="#{bean.travelName}" maxlength="50" onkeypress="return onlyAlphabet(event)" />
</div>
</code>```

答:
<!DOCTYPE html>

    <title></title>
 <meta charset="utf-8" />

    <input id="Text1" type="text"  onkeypress="return onlyAlphabet(event)"/>

```

Keycode for ^ is 94 .. Prevent it.. If you want to fix it yourself put
alert(key) in the code, where you will get the code for the pressed key.

Body:
I have a text field and I want to allow only alphabet. So I write the below Javascript method to prevent other keys. Unfortunately my text field is allowing uparrow(^).
Can any one tell me how to restrict uparrow(^) ?

function onlyAlphabet(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;

    var keychar = String.fromCharCode(key);
    var keycheck = /[a-zA-z\s]/;

    if (!(key == 8 || key == 27 || key == 46 || key == 9 || key == 39)) // backspace delete  escape arrows
    {
        if (!keycheck.test(keychar)) {
            theEvent.returnValue = false;//for IE
            if (theEvent.preventDefault)
                theEvent.preventDefault();//Firefox
        }
    }
}

html code

   Travels Name
   <h:inputText value="#{bean.travelName}" maxlength="50" onkeypress="return onlyAlphabet(event)" />

Body:
<!DOCTYPE html>
<html>
<head>
    <title></title>
 <meta charset="utf-8" />
    <script>
        function onlyAlphabet(evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;

            var keychar = String.fromCharCode(key);
            var keycheck = /[a-zA-z\s]/;

            if (!(key == 8 || key == 27 || key == 46 || key == 9 || key == 39 || key == 94)) // backspace delete  escape arrows
            {

                    if (!keycheck.test(keychar)) {
                        theEvent.returnValue = false;//for IE
                        if (theEvent.preventDefault)
                            theEvent.preventDefault();//Firefox
                    }

            }
            else if(key==94)
                theEvent.preventDefault();
        }
    </script>
</head>
<body>

    <input id="Text1" type="text"  onkeypress="return onlyAlphabet(event)"/>
</body>
</html>

Keycode for ^ is 94 .. Prevent it.. If you want to fix it yourself put
alert(key) in the code, where you will get the code for the pressed key.


问:
Using Type instead of specific class
I have this code:

```<code>if (((Classes.ProductGroup)o).ToString().Contains(comboBox.Text))
   return true;
else
   return false;
</code>```

Now I want not to specify the part Classes.ProductGroup. I want to make it universal.

How can I replace the part Classes.ProductGroup with a Type object?

```<code>Type type = typeof(Classes.ProductGroup);
</code>```

Something similar to this:

```<code>if (((type)o).ToString().Contains(comboBox.Text))
</code>```

Is this possible?

Here is the complete method code:

```<code>private void FilterPGsinComboBox(object obj)
{
    if (!Dispatcher.CheckAccess())
    {
        Dispatcher.Invoke(new FilterPGsinComboBoxDelegate(this.FilterPGsinComboBox),obj);
        return;
    }
    Type type = ((Dictionary<ComboBox, Type>)obj).First().Value;
    ComboBox comboBox = ((Dictionary<ComboBox, Type>)obj).First().Key;
    comboBox.IsDropDownOpen = true;
    CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(comboBox.ItemsSource);

    itemsViewOriginal.Filter = ((o) =>
    {
        if (String.IsNullOrEmpty(comboBox.Text))
            return true;
        else
        {
            if (((Classes.ProductGroup)o).ToString().Contains(comboBox.Text))
                return true;
            else
                return false;
        }
    });

    itemsViewOriginal.Refresh();
}
</code>```

答:
You can use generics and build a method like

```<code>public bool ClassNameContainString<T>(string text) where T : class
{
    var containsString = typeof(T).ToString().Contains(text);

    return containsString;
}
</code>```

If you want to make this method case insensitive change the logic to

```<code>var containsString = typeof(T).ToString().ToLower().Contains(text.ToLower());
</code>```

Title: Using Type instead of specific class

Body:
I have this code:

if (((Classes.ProductGroup)o).ToString().Contains(comboBox.Text))
   return true;
else
   return false;

Now I want not to specify the part Classes.ProductGroup. I want to make it universal.

How can I replace the part Classes.ProductGroup with a Type object?

Type type = typeof(Classes.ProductGroup);

Something similar to this:

if (((type)o).ToString().Contains(comboBox.Text))

Is this possible?

Here is the complete method code:

private void FilterPGsinComboBox(object obj)
{
    if (!Dispatcher.CheckAccess())
    {
        Dispatcher.Invoke(new FilterPGsinComboBoxDelegate(this.FilterPGsinComboBox),obj);
        return;
    }
    Type type = ((Dictionary<ComboBox, Type>)obj).First().Value;
    ComboBox comboBox = ((Dictionary<ComboBox, Type>)obj).First().Key;
    comboBox.IsDropDownOpen = true;
    CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(comboBox.ItemsSource);

    itemsViewOriginal.Filter = ((o) =>
    {
        if (String.IsNullOrEmpty(comboBox.Text))
            return true;
        else
        {
            if (((Classes.ProductGroup)o).ToString().Contains(comboBox.Text))
                return true;
            else
                return false;
        }
    });

    itemsViewOriginal.Refresh();
}

Body:
You can use generics and build a method like

public bool ClassNameContainString<T>(string text) where T : class
{
    var containsString = typeof(T).ToString().Contains(text);

    return containsString;
}

If you want to make this method case insensitive change the logic to

var containsString = typeof(T).ToString().ToLower().Contains(text.ToLower());


问:
JUnit Test both passes and fails - conflict using both ExpectedException and TestWatcher @Rule's
I figured this out during making this question, but figured it would be a good resource for future people running into the same weird quirk. Treat it as a challenge to your debugging skills.

Using the latest JUnit at the moment, 4.12, this peculiar test both passes and fails - depending how you look at it. Running it will print out the error message - but despite failed() being called, it will still not quite count as failed.

```<code>import java.io.IOException;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class TestWatcherExpectedExceptionTest {
    @Rule
    public TestWatcher logger = new TestWatcher() {
        @Override
        protected void failed(Throwable e, Description d) {
            System.out.println(d + " FAILED! - are you kidding me ?");
            e.printStackTrace();
        }

        @Override
        protected void succeeded(Description d) {
            System.out.println(d + " succeeded!");
        }
    };

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    /**
     * This test both passes and fails, depending how you look at it.
     */
    @Test
    public void photon() throws IOException {
        thrown.expect(IOException.class);
        throw new IOException("Hi");
    }
}
</code>```

As an additional bonus question, during debugging this issue, the test suddenly started to succeed, and call the succeeded() method, and I could not, for the life of me, figure out why. As far as I could tell, there were no changes to the code that should have possibly had any impact:

```<code>import java.io.IOException;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class TestWatcherExpectedExceptionTest {
    private final class TestLogger extends TestWatcher {
        @Override
        protected void failed(Throwable e, Description d) {
            System.out.println(d + " FAILED! - are you kidding me ?");
            e.printStackTrace();
        }

        @Override
        protected void succeeded(Description d) {
            System.out.println(d + " succeeded!");
        }
    }

    @Rule
    public TestWatcher watcher = new TestLogger();

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    /**
     * This test both passes and fails, depending how you look at it.
     */
    @Test
    public void photon() throws IOException {
        thrown.expect(IOException.class);
        throw new IOException("Hi");
    }
}
</code>```

答:
The peculiar answer to why the second test works, and why the first test fails at all is in the way JUnit handles rules - apparently, rules are handled in alphabetical order, based on the field name, and the TestWatcher rule is not quite compatible with the ExpectedException rule, in that it disregards the exception being expected if the rule is 'interpreted' by JUnit too soon.

So the reason the second test doesn't fail lies in the field names - watcher comes alphabetically after thrown, but the first test's field name, logger, comes before thrown. That one was not fun to debug.

Body:
I figured this out during making this question, but figured it would be a good resource for future people running into the same weird quirk. Treat it as a challenge to your debugging skills.

Using the latest JUnit at the moment, 4.12, this peculiar test both passes and fails - depending how you look at it. Running it will print out the error message - but despite failed() being called, it will still not quite count as failed.

import java.io.IOException;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class TestWatcherExpectedExceptionTest {
    @Rule
    public TestWatcher logger = new TestWatcher() {
        @Override
        protected void failed(Throwable e, Description d) {
            System.out.println(d + " FAILED! - are you kidding me ?");
            e.printStackTrace();
        }

        @Override
        protected void succeeded(Description d) {
            System.out.println(d + " succeeded!");
        }
    };

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    /**
     * This test both passes and fails, depending how you look at it.
     */
    @Test
    public void photon() throws IOException {
        thrown.expect(IOException.class);
        throw new IOException("Hi");
    }
}

As an additional bonus question, during debugging this issue, the test suddenly started to succeed, and call the succeeded() method, and I could not, for the life of me, figure out why. As far as I could tell, there were no changes to the code that should have possibly had any impact:

import java.io.IOException;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class TestWatcherExpectedExceptionTest {
    private final class TestLogger extends TestWatcher {
        @Override
        protected void failed(Throwable e, Description d) {
            System.out.println(d + " FAILED! - are you kidding me ?");
            e.printStackTrace();
        }

        @Override
        protected void succeeded(Description d) {
            System.out.println(d + " succeeded!");
        }
    }

    @Rule
    public TestWatcher watcher = new TestLogger();

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    /**
     * This test both passes and fails, depending how you look at it.
     */
    @Test
    public void photon() throws IOException {
        thrown.expect(IOException.class);
        throw new IOException("Hi");
    }
}


问:
screen naviagation iphone, xcode?
i'm having 3 screens
set title to screen1 using

- (void)viewDidLoad {
    [super viewDidLoad];
 self.navigationItem.title =@"Products";
}

when navigation to next screen (screen2) second screen having the title "Categories"
but there is a button on the top name "Products" to Screen1

i want to change the button name as "Back"

Please tell me how?

triedself.navigationItem.leftBarButtonItem .title = @"Back";

答:
You have to do something like the follows to set the text of the back bar button to something other than what the previous view was named:

```<code>UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
barButton.title = @"Your Custom Title";

self.navigationItem.backBarButtonItem = barButton;
</code>```

You CANNOT do the following:

```<code>self.navigationItem.backBarButtonItem.title = @"Your Title";
</code>```

This sets the previous view on the stack to "Your Title" and not was it was before.

Title: screen naviagation iphone, xcode?

Body:
You have to do something like the follows to set the text of the back bar button to something other than what the previous view was named:

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] init];
barButton.title = @"Your Custom Title";

self.navigationItem.backBarButtonItem = barButton;

You CANNOT do the following:

self.navigationItem.backBarButtonItem.title = @"Your Title";

This sets the previous view on the stack to "Your Title" and not was it was before.