问:
Regular expression to split a string but consider multi-digit escape sequences
I could need some help on the following problem with regular expressions and would appreciate any help, thanks in advance.

I have to split a string by another string, let me call it separator. However, if an escape sequence preceeds separatorString, the string should not be split at this point. The escape sequence is also a string, let me call it escapeSequence.

Maybe it is better to start with some examples

```<code>separatorString = "§§";

escapeSequence = "###";

inputString = "Part1§§Part2" ==> Desired output: "Part1", "Part2"
inputString = "Part1§§Part2§§ThisIs###§§AllPart3" ==> Desired output: "Part1", "Part2", "ThisIs###§§AllPart3"
</code>```

Searching stackoverflow, I found Splitting a string that has escape sequence using regular expression in Java and came up with the regular expression

"(?<!(###))§§".

This is basically saying, match if you find "§§", unless it is preceeded by "###".

This works fine with Regex.Split for the examples above, however, if inputString is "Part1###§§§§Part2" I receive "Part1###§", "§Part2" instead of "Part1###§§", "Part2".

I understand why, as the second "§" gives a match, because the proceeding chars are "##§" and not "###". I tried several hours to modify the regex, but the result got only worse. Does someone have an idea?

答:
How about doing the opposite: Instead of splitting the string at the separators match non-separator parts and separator parts:

```<code>/(?:[^§#]|§[^§#]|#(?:[^#]|#(?:[^#]|#§§)))+|§§/
</code>```

Then you just have to remove every matched separator part to get the non-separator parts.

Body:
I could need some help on the following problem with regular expressions and would appreciate any help, thanks in advance.

I have to split a string by another string, let me call it separator. However, if an escape sequence preceeds separatorString, the string should not be split at this point. The escape sequence is also a string, let me call it escapeSequence.

Maybe it is better to start with some examples

separatorString = "§§";

escapeSequence = "###";

inputString = "Part1§§Part2" ==> Desired output: "Part1", "Part2"
inputString = "Part1§§Part2§§ThisIs###§§AllPart3" ==> Desired output: "Part1", "Part2", "ThisIs###§§AllPart3"

Searching stackoverflow, I found Splitting a string that has escape sequence using regular expression in Java and came up with the regular expression

"(?<!(###))§§".

This is basically saying, match if you find "§§", unless it is preceeded by "###".

This works fine with Regex.Split for the examples above, however, if inputString is "Part1###§§§§Part2" I receive "Part1###§", "§Part2" instead of "Part1###§§", "Part2".

I understand why, as the second "§" gives a match, because the proceeding chars are "##§" and not "###". I tried several hours to modify the regex, but the result got only worse. Does someone have an idea?

Body:
How about doing the opposite: Instead of splitting the string at the separators match non-separator parts and separator parts:

/(?:[^§#]|§[^§#]|#(?:[^#]|#(?:[^#]|#§§)))+|§§/

Then you just have to remove every matched separator part to get the non-separator parts.


来源: stackexchange

问:
iOS Safari/Chrome - Unwanted scrolling when focusing an input inside the modal
Tested in Safari and Chrome - the same result, so I think it's iOS issue.

This happens only if there's an input inside the modal and I tap that input. In the same moment that input got focus and native iOS keyboard become visible.

Page below modal in the same moment is automatically scrolled to 50% of its height. This behaviour is totally unwanted and I have no clue how to prevent this default iOS "feature".

Demo:

答:
I tried multiple things which kind of worked for the bouncing modal inputs on the html page. The simplest solution which worked for me was adding following styles to the body tag when the modal is open on the page.

position: fixed;
width: 100%;
```

ContentLicense: CC BY-SA 3.0


问:
java compareTo method implementation
currently I'm trying to find out how java's interface  "Comparable" works.
As far as I know inteface cannot have any non-static (besides default ones) methods so when we implement an interface we need to define its methods first.

But when I implement "Comparable" interface I obviously can use its compareTo method. Where is that method defined?

```<code>public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {

    int count = 0;

    for (T e : anArray)
        if (e.compareTo(elem) > 0)
            ++count;
    return count;

}
</code>```

How come that I'm able to use interface's method without even defining it?

My apoligies if there was already an answer to that question, wasn't able to find it though.

Thx.

答:
To your code:

You have defined a type T as a sub-class of "Comparable" within your signature and it is used within the parameters as you pass in an array of "T" ( T[] ). The compiler now knows that any T must be at least a Comparable.

Further information:

In general I do not suggest to implement Comparable directly. The reason for that is that comparison is always within a context you do not know.

You should favor the Comparator-interface over the Comparable-interface to implement comparisons with a specific contexts. If you want to define a natural order you can provide a natural comparator as a public constant.

Some examples:

```<code>import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorExample {

    public static void main(String[] args) {

        List<SomeObject> list = new ArrayList<>();

        list.add(new SomeObject(1, "dhjf", "A"));
        list.add(new SomeObject(4, "ghdg", "A"));
        list.add(new SomeObject(6, "uztzt", "B"));
        list.add(new SomeObject(1, "jhgf", "C"));
        list.add(new SomeObject(3, "vbbn", "A"));
        list.add(new SomeObject(99, "cvcxc", "A"));
        list.add(new SomeObject(2, "dfdd", "G"));

        // examples

        Collections.sort(list, SomeObject.NATURAL);
        Collections.sort(list, LexicographicOrderByCategoryAndName.INSTANCE);
        LexicographicOrderByName.INSTANCE.compare(new SomeObject(99, "cvcxc", "A"), new SomeObject(54, "fdjnn", "C"));

    }

    public static class SomeObject {

        public static Comparator<SomeObject> NATURAL = new Comparator<SomeObject>() {

            @Override
            public int compare(SomeObject arg0, SomeObject arg1) {
                return arg1.getId() - arg0.getId();
            }

        };

        private int id;
        private String name;
        private String category;

        public SomeObject(int id, String name, String category) {
            this.id = id;
            this.name = name;
            this.category = category;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public String getCategory() {
            return category;
        }

    }

    public static class LexicographicOrderByName implements Comparator<SomeObject> {

        public static LexicographicOrderByName INSTANCE = new LexicographicOrderByName();

        private LexicographicOrderByName() {
        }

        @Override
        public int compare(SomeObject o1, SomeObject o2) {
            return o1.getName().compareTo(o2.getName());
        }

    }

    public static class LexicographicOrderByCategoryAndName implements Comparator<SomeObject> {

        public static LexicographicOrderByCategoryAndName INSTANCE = new LexicographicOrderByCategoryAndName();

        private LexicographicOrderByCategoryAndName() {
        }

        @Override
        public int compare(SomeObject o1, SomeObject o2) {

            int c = o1.getCategory().compareTo(o2.getCategory());

            if (c == 0) {
                c = o1.getName().compareTo(o2.getName());
            }

            return c;
        }

    }

}
</code>```

The problem with the Comparable-interface is that once you decided a specific comparison of an object you are bound to it forever. You may may change it but expect side effects as you do not know if all contexts have the same erasure and should change too.

Title: java compareTo method implementation

Body:
currently I'm trying to find out how java's interface  "Comparable" works.
As far as I know inteface cannot have any non-static (besides default ones) methods so when we implement an interface we need to define its methods first.

But when I implement "Comparable" interface I obviously can use its compareTo method. Where is that method defined?

public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {

    int count = 0;

    for (T e : anArray)
        if (e.compareTo(elem) > 0)
            ++count;
    return count;

}

How come that I'm able to use interface's method without even defining it?

My apoligies if there was already an answer to that question, wasn't able to find it though.

Thx.

Body:
To your code:

You have defined a type T as a sub-class of "Comparable" within your signature and it is used within the parameters as you pass in an array of "T" ( T[] ). The compiler now knows that any T must be at least a Comparable.

Further information:

In general I do not suggest to implement Comparable directly. The reason for that is that comparison is always within a context you do not know.

You should favor the Comparator-interface over the Comparable-interface to implement comparisons with a specific contexts. If you want to define a natural order you can provide a natural comparator as a public constant.

Some examples:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorExample {

    public static void main(String[] args) {

        List<SomeObject> list = new ArrayList<>();

        list.add(new SomeObject(1, "dhjf", "A"));
        list.add(new SomeObject(4, "ghdg", "A"));
        list.add(new SomeObject(6, "uztzt", "B"));
        list.add(new SomeObject(1, "jhgf", "C"));
        list.add(new SomeObject(3, "vbbn", "A"));
        list.add(new SomeObject(99, "cvcxc", "A"));
        list.add(new SomeObject(2, "dfdd", "G"));

        // examples

        Collections.sort(list, SomeObject.NATURAL);
        Collections.sort(list, LexicographicOrderByCategoryAndName.INSTANCE);
        LexicographicOrderByName.INSTANCE.compare(new SomeObject(99, "cvcxc", "A"), new SomeObject(54, "fdjnn", "C"));

    }

    public static class SomeObject {

        public static Comparator<SomeObject> NATURAL = new Comparator<SomeObject>() {

            @Override
            public int compare(SomeObject arg0, SomeObject arg1) {
                return arg1.getId() - arg0.getId();
            }

        };

        private int id;
        private String name;
        private String category;

        public SomeObject(int id, String name, String category) {
            this.id = id;
            this.name = name;
            this.category = category;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public String getCategory() {
            return category;
        }

    }

    public static class LexicographicOrderByName implements Comparator<SomeObject> {

        public static LexicographicOrderByName INSTANCE = new LexicographicOrderByName();

        private LexicographicOrderByName() {
        }

        @Override
        public int compare(SomeObject o1, SomeObject o2) {
            return o1.getName().compareTo(o2.getName());
        }

    }

    public static class LexicographicOrderByCategoryAndName implements Comparator<SomeObject> {

        public static LexicographicOrderByCategoryAndName INSTANCE = new LexicographicOrderByCategoryAndName();

        private LexicographicOrderByCategoryAndName() {
        }

        @Override
        public int compare(SomeObject o1, SomeObject o2) {

            int c = o1.getCategory().compareTo(o2.getCategory());

            if (c == 0) {
                c = o1.getName().compareTo(o2.getName());
            }

            return c;
        }

    }

}

The problem with the Comparable-interface is that once you decided a specific comparison of an object you are bound to it forever. You may may change it but expect side effects as you do not know if all contexts have the same erasure and should change too.


问:
Sql server row lock
I have developed an app with c# where a form displays a few details of a employee in a listview control. When a user clicks on a row, then another form will open and show that employee's record with more detail.

I want it to work so that a user will see the form where employee records are shown in more detail, that that record will be locked in such a way that another user will not be able to see that record until the original user closes the detail form. Please guide me how I can design this type of app with SQL Server lock.

答:
A preferred way would be...

You could add a timestamp column to the table and compare it to the incoming update.

If the user tries to update the data and the timestamp is different, alert the user that the data has changed and refresh the screen.

A non-preferred way would be...

Add a userEditing column to the table, and set it to the user who is working with the row (like a checkout). Hide this row from any user that doesnt have it "checked out", and release it when they are done.

This can become problematic for you in many ways (Joe user locks a row, is out today, and Jane needs it now), but can be the appropriate solution in some cases.

Title: Sql server row lock

ContentLicense: CC BY-SA 2.5


问:
changing static variables from another method in java
I want to create a method, moveQ(), that I will be able to call in method find() in order to change find()'s variables, but in method moveQ() I am getting the error cannot find symbol variable x in this example x, y, and z are the variables I need to change.

edited:

I also have a few restrictions as this is taken from an exercise from Java course:
1. method must be static.
2. global variables are not allowed.
3. time complexity should be less than O(n), I cannot add to memory complexity (meaning can not use another array or objects).
4. the method find() can not accept parameters.

In the actual program, I need to write a static boolean method that will return true if number x is found in an array that is divided into quadrants. To do that, it searches for each quadrant's highest number. If x is larger than the quadrant highest number, then I need to move to the next quadrant.

x, y, and z are the maximum number, middle number and the minimum number of the quadrant of the array and by changing them, I can move quadrants.

I've already written the find() method, but I want to use helper methods to make the code better.

Is what I am trying to do even possible, and if so how do I accomplish it?

```<code>public class Test
{
    public static boolean find()
    {
        int x = 10;
        int y = 20;
        int z = 30;
        change(x,y,z); // call helper method to change this method's variables.
        System.out.println(x); // should be 20
        System.out.println(y); // should be 22
        System.out.println(z); // should be 15
    }

    //helper method to be called from find() method
    private static void change(int changeX ,int changeY,int changeZ)
    {
        //change find() variables.
        x = changeX * 2;
        y = changeY + 2;
        z = changeZ /2;
    }
}
</code>```

答:
You can achieve that in more organized way :

Create Calculation class then put all your variables and methods on it

File Calculation.java:

```<code>public class Calculation {

    private int x = 10;
    private int y = 20;
    private int z = 30;

    public void setX(int value){
        x = value;
    }
    public void setY(int value){
        y = value;
    }
    public void setZ(int value){
        z = value;
    }

    public int getX(){
        return x;
    }
    public int getY(){
        return y;
    }
    public int getZ(){
        return z;
    }

    private void change(int changeX, int changeY, int changeZ){
        setX(changeX * 2);
        setY(changeY + 2);
        setZ(changeZ / 2);
    }

    public void find(){
        change(x,y,z);
        System.out.println(getX());
        System.out.println(getY());
        System.out.println(getZ());
    }
}
</code>```

After that just create new object of class Calculation in your main program and call find() method on this object variable

File Main.java:

```<code>public class Main {

    public static void main(String[] args) {
        Calculation c = new Calculation();
        c.find();
    }
}
</code>```

Output:

```<code>20
22
15
</code>```

Body:
I want to create a method, moveQ(), that I will be able to call in method find() in order to change find()'s variables, but in method moveQ() I am getting the error cannot find symbol variable x in this example x, y, and z are the variables I need to change.

edited:

I also have a few restrictions as this is taken from an exercise from Java course:
1. method must be static.
2. global variables are not allowed.
3. time complexity should be less than O(n), I cannot add to memory complexity (meaning can not use another array or objects).
4. the method find() can not accept parameters.

In the actual program, I need to write a static boolean method that will return true if number x is found in an array that is divided into quadrants. To do that, it searches for each quadrant's highest number. If x is larger than the quadrant highest number, then I need to move to the next quadrant.

x, y, and z are the maximum number, middle number and the minimum number of the quadrant of the array and by changing them, I can move quadrants.

I've already written the find() method, but I want to use helper methods to make the code better.

Is what I am trying to do even possible, and if so how do I accomplish it?

public class Test
{
    public static boolean find()
    {
        int x = 10;
        int y = 20;
        int z = 30;
        change(x,y,z); // call helper method to change this method's variables.
        System.out.println(x); // should be 20
        System.out.println(y); // should be 22
        System.out.println(z); // should be 15
    }

    //helper method to be called from find() method
    private static void change(int changeX ,int changeY,int changeZ)
    {
        //change find() variables.
        x = changeX * 2;
        y = changeY + 2;
        z = changeZ /2;
    }
}

Body:
You can achieve that in more organized way :

Create Calculation class then put all your variables and methods on it

File Calculation.java:

public class Calculation {

    private int x = 10;
    private int y = 20;
    private int z = 30;

    public void setX(int value){
        x = value;
    }
    public void setY(int value){
        y = value;
    }
    public void setZ(int value){
        z = value;
    }

    public int getX(){
        return x;
    }
    public int getY(){
        return y;
    }
    public int getZ(){
        return z;
    }

    private void change(int changeX, int changeY, int changeZ){
        setX(changeX * 2);
        setY(changeY + 2);
        setZ(changeZ / 2);
    }

    public void find(){
        change(x,y,z);
        System.out.println(getX());
        System.out.println(getY());
        System.out.println(getZ());
    }
}

After that just create new object of class Calculation in your main program and call find() method on this object variable

File Main.java:

public class Main {

    public static void main(String[] args) {
        Calculation c = new Calculation();
        c.find();
    }
}

Output:

20
22
15


问:
Testing with SugarORM and Robolectric
I trying to setup an testing environment for my android project. The basic Robolectric setup is done. I used this nice tutorial. If I comment out SugarORM in my Manifest.xml, all test works fine. But If I want to use it with SugarORM I always get this error:

java.lang.NullPointerException at
  dalvik.system.DexFile$DFEnum.hasMoreElements(DexFile.java:239) at
  com.orm.SugarDb.getDomainClasses(SugarDb.java:37) at
  com.orm.SugarDb.createDatabase(SugarDb.java:104) at
  com.orm.SugarDb.onCreate(SugarDb.java:100) at
  android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
  at
  android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
  at com.orm.Database.getDB(Database.java:18) at
  com.orm.SugarApp.onTerminate(SugarApp.java:16) at
  org.robolectric.internal.ParallelUniverse.tearDownApplication(ParallelUniverse.java:133)
  at
  org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:246)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at
  org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  at
  org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at
  org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:158)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
  org.junit.runner.JUnitCore.run(JUnitCore.java:137) at
  com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

Does everyone have the same problem?

Edit

Maybe it is, because Robolectric shutdown after the test and sugarorm is still not finished. My TestClass

```<code>@RunWith(RobolectricTestRunner.class)
@Config(manifest="./src/main/AndroidManifest.xml",emulateSdk=18)
public class MyActivityTest{

    private ActivityController<OnLogActivity> controller = Robolectric.buildActivity(OnLogActivity.class).create().setup();

    @Test
    public void clickingLogin_shouldStartLoginActivity() {
        OnLogActivity activity = controller.get();
        assertTrue(activity.findViewById(R.id.login) instanceof Button);

    }

}
</code>```

Edit 2.0:

That Robolectric can find the android:name=com.orm.SugarApp you have to create a testfolder with the same package of com.orm and add a test class called TestSugarApp. After that you can test all the stuff.

```<code>package com.orm;

...

@RunWith(RobolectricTestRunner.class)
@Config(manifest="./src/main/AndroidManifest.xml",emulateSdk=18)
public class TestSugarApp extends Application
        implements TestLifecycleApplication {

    private ActivityController<OnLogActivity> controller;

    @Test
    public void startEverTestSugarAppAsFirst() {

    }

    @Override
    public void beforeTest(Method method) {
        Log.v("test", "beforeTest");
    }

    @Override
    public void prepareTest(Object test) {
        Log.v("test", "prepareTest");
    }

    @Override
    public void afterTest(Method method) {
        Log.v("test", "afterTest");
    }
}
</code>```

答:
@Eugen Martynov's answer works perfectly (thanks alot!).
However, when you've extended android.app.Application yourself (which on its turn extends SugarApp), then you'll also exclude your own code.

I've solved this with using this code:

The Application class in the test code (as opposed to Eugen's answer):

```<code>public class TestApp extends App {
    /** Prevents onCreate() and onTerminate() to call their super (in which {@link com.orm.SugarApp} is initialized) */
    @Override
    protected boolean callSuper() {
        return false;
    }
}
</code>```

My own Application class (extending SugarApp):

```<code>public class App extends com.orm.SugarApp {
    private static Context context;

    public static Context getContext() {
        return context;
    }

    @Override
    public void onCreate() {
        if (callSuper()) {
            super.onCreate();
        }

        // My own code is always executed, also during unittests
        context = getApplicationContext();
    }

    @Override
    public void onTerminate() {
        if (callSuper()) {
            super.onTerminate();
        }
    }

    protected boolean callSuper() {
        return true; // Super is executed by default
    }
}
</code>```

I agree it doesn't look very beautiful (any advice to make this better?), but it works perfectly for me!

ps. I declared my application class in my manifest like this:

```<code><application
    android:name=".App"
</code>```

Title: Testing with SugarORM and Robolectric

Body:
I trying to setup an testing environment for my android project. The basic Robolectric setup is done. I used this nice tutorial. If I comment out SugarORM in my Manifest.xml, all test works fine. But If I want to use it with SugarORM I always get this error:

java.lang.NullPointerException at
  dalvik.system.DexFile$DFEnum.hasMoreElements(DexFile.java:239) at
  com.orm.SugarDb.getDomainClasses(SugarDb.java:37) at
  com.orm.SugarDb.createDatabase(SugarDb.java:104) at
  com.orm.SugarDb.onCreate(SugarDb.java:100) at
  android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
  at
  android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
  at com.orm.Database.getDB(Database.java:18) at
  com.orm.SugarApp.onTerminate(SugarApp.java:16) at
  org.robolectric.internal.ParallelUniverse.tearDownApplication(ParallelUniverse.java:133)
  at
  org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:246)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at
  org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  at
  org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at
  org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:158)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
  org.junit.runner.JUnitCore.run(JUnitCore.java:137) at
  com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

Does everyone have the same problem?

Edit

Maybe it is, because Robolectric shutdown after the test and sugarorm is still not finished. My TestClass

@RunWith(RobolectricTestRunner.class)
@Config(manifest="./src/main/AndroidManifest.xml",emulateSdk=18)
public class MyActivityTest{

    private ActivityController<OnLogActivity> controller = Robolectric.buildActivity(OnLogActivity.class).create().setup();

    @Test
    public void clickingLogin_shouldStartLoginActivity() {
        OnLogActivity activity = controller.get();
        assertTrue(activity.findViewById(R.id.login) instanceof Button);

    }

}

Edit 2.0:

That Robolectric can find the android:name=com.orm.SugarApp you have to create a testfolder with the same package of com.orm and add a test class called TestSugarApp. After that you can test all the stuff.

package com.orm;

...

@RunWith(RobolectricTestRunner.class)
@Config(manifest="./src/main/AndroidManifest.xml",emulateSdk=18)
public class TestSugarApp extends Application
        implements TestLifecycleApplication {

    private ActivityController<OnLogActivity> controller;

    @Test
    public void startEverTestSugarAppAsFirst() {

    }

    @Override
    public void beforeTest(Method method) {
        Log.v("test", "beforeTest");
    }

    @Override
    public void prepareTest(Object test) {
        Log.v("test", "prepareTest");
    }

    @Override
    public void afterTest(Method method) {
        Log.v("test", "afterTest");
    }
}

Body:
@Eugen Martynov's answer works perfectly (thanks alot!).
However, when you've extended android.app.Application yourself (which on its turn extends SugarApp), then you'll also exclude your own code.

I've solved this with using this code:

The Application class in the test code (as opposed to Eugen's answer):

public class TestApp extends App {
    /** Prevents onCreate() and onTerminate() to call their super (in which {@link com.orm.SugarApp} is initialized) */
    @Override
    protected boolean callSuper() {
        return false;
    }
}

My own Application class (extending SugarApp):

public class App extends com.orm.SugarApp {
    private static Context context;

    public static Context getContext() {
        return context;
    }

    @Override
    public void onCreate() {
        if (callSuper()) {
            super.onCreate();
        }

        // My own code is always executed, also during unittests
        context = getApplicationContext();
    }

    @Override
    public void onTerminate() {
        if (callSuper()) {
            super.onTerminate();
        }
    }

    protected boolean callSuper() {
        return true; // Super is executed by default
    }
}

I agree it doesn't look very beautiful (any advice to make this better?), but it works perfectly for me!

ps. I declared my application class in my manifest like this:

<application
    android:name=".App"


问:
SQL Server backup strategy questions for DB in Full recovery mode
I've recently taken on the database administration of a few SQL servers varying from SQL Server 2005 to 2014, where many of the DB's are in Full recovery mode, however no good ongoing backup maintenance plans were ever setup.

It seems to me that the previous DBA would only deal with transaction log files when they got out of control and fill up the hard drive. So i'd like to change this and fix the issue once and for all. I've been doing some reading and think I have a decent understanding of what need to be done, so i'd like to validate my understanding as well as ask a few question to clarify a few points that I still don't fully get.

So based on my understanding to date i would need to create a maintenance plan which starts with a Full Backup. I still need to talk to management to figure out things like RTO, acceptable data loss, etc so let's assume for this example that we'll do Full Backup's on Sunday.

Next I would add to this maintenance plan Differential backups every night... so Monday to Saturday. I realize that this could also be Full backup's or run the differentials more frequently, but again this is just as an example to make sure i'm understanding things correctly.

Now as for the transaction log backups. I get that i would need to back these up and truncate the log file to prevent it from continually growing and getting out of control. I don't know if there are any specific recommendation for how often to back this up, but i've seen 15 minutes suggested. I guess this would more so fall under the acceptable data loss window. Is that correct?

So the other thing that i've discovered is that when you backup the transaction log file with truncation, that if the log file has already grown out of control that it doesn't shrink the file. I've also read that it isn't good to shrink these files, at least on regular basis because once you shrink it, it would need to grow again and this will cause fragmentation and performance issues.

Now since I am currently in a situation that the files have already grown out of control, i'd assume that i should in fact shrink the log files this one time once i've but my maintenance in place. Is that assumption correct?

Also once i Shrink the transaction log file this one time, are there any maintenance task that i should be running to avoid performance issue due to shrinking the log files?

One other question that i was wondering about would be with respect to point in time recovery. So let's say I take a full backup at 5:00 AM and i also take a transaction log backup every 15 minutes. I get alerted that at 6:18 AM something has gone wrong (let's say a table was deleted). So i know i can restore by Full backup that happened at 5:00 AM and leave it in NO RECOVERY mode and restore all of the Transaction log backup from 5:15 AM to 6:15 AM, but here is what i'm interested in...since i have my DB in full recovery mode, is it possible to somehow use my existing transaction log file (not the backups) to roll forward all transaction between 6:15 and 6:17 just before the table was deleted? If so how would you do this? I guess this obviously wouldn't work in the case of you loosing the hard drive with your transaction log files, or your server exploding...but in a case like i've outlined is it do able?

Thanks

答:
I would recommend doing a full backup after everyone stopped working, e. g. at 10 p.m. (if that is the case), not in the morning shortly before people start working. Just in order to give it enough time to run.

Personally, I prefer doing daily full backups instead of incremental backups if the database is not too big to save backups for, say, 14 days. I feel better to rely on less files. If database and full backups are too big, incremental backups might be the better choice.

As you said: How many transaction log backups you create during the day depends on the acceptable data loss window. In an environment > 5 people working on the system (just as a gut feeling) I would configure them to run all 15 minutes, on very big systems maybe even more.

After the first transaction log backup, you might want to shrink the LOG file ONCE.

I think it's not necessary to run any optimizations after a log shrink.

As far as I know it's not possible to restore transactions between 06:15 and 06:17.

When activating the transaction log backups, keep in mind that the first transaction log backup will be quite big (around the size of the current, large log). Ensure to have enough space on disk until you shrink the log file and delete the first transaction log (usually done automatically within the maintenance plan, e. g. after 14 days.).


问:
asp:RequiredFieldValidator with the contents being a table row
I've got the following code, which to my eye looks fine, can anyone suggest why it doesn't work?

```<code><tr>
  <td>
    <asp:TextBox ID="PurchaserEmailTextBox" runat="server" CssClass="type-text" />
  </td>
  <td>
  </td>
</tr>

<asp:RequiredFieldValidator ControlToValidate="PurchaserEmailTextBox" ID="RequiredFieldValidator5" Display="Dynamic" runat="server">
  <tr>
    <td colspan="2">
      <span class="error">You need a purchaser email</span>
    </td>
  </tr>
</asp:RequiredFieldValidator>
</code>```

The problem is that the validator renders fine, but refuses to disappear when the email is correctly filled in as it should.

Thanks!

答:
This is the markup rendered by the validator:

```<code><table>
    <tr>
        <td>
            <input name="PurchaserEmailTextBox" type="text" value="asdf" id="PurchaserEmailTextBox" />
        </td>
        <td>
        </td>
    </tr>
    <span id="RequiredFieldValidator5" style="color:Red;display:none;">
            <tr>
               <td colspan="2">
                 <span>You need a purchaser email</span>
               </td>
             </tr>
    </span>
</table>
</code>```

The problem is there's a span element within the table element, which isn't allowed.  http://www.w3.org/TR/html401/struct/tables.html#edef-TABLE

Body:
I've got the following code, which to my eye looks fine, can anyone suggest why it doesn't work?

    <asp:TextBox ID="PurchaserEmailTextBox" runat="server" CssClass="type-text" />

<asp:RequiredFieldValidator ControlToValidate="PurchaserEmailTextBox" ID="RequiredFieldValidator5" Display="Dynamic" runat="server">

      You need a purchaser email

</asp:RequiredFieldValidator>

The problem is that the validator renders fine, but refuses to disappear when the email is correctly filled in as it should.

Thanks!

Body:
This is the markup rendered by the validator:

<table>
    <tr>
        <td>
            <input name="PurchaserEmailTextBox" type="text" value="asdf" id="PurchaserEmailTextBox" />
        </td>
        <td>
        </td>
    </tr>
    <span id="RequiredFieldValidator5" style="color:Red;display:none;">
            <tr>
               <td colspan="2">
                 <span>You need a purchaser email</span>
               </td>
             </tr>
    </span>
</table>

The problem is there's a span element within the table element, which isn't allowed.  http://www.w3.org/TR/html401/struct/tables.html#edef-TABLE


问:
Issue in create trigger phpmyadmin
I have a problem creating a trigger in phpmyadmin. Here is my syntax:

```<code>DECLARE n_ubicacion VARCHAR(45) DEFAULT '';

IF (OLD.id_ubicacion <> NEW.id_ubicacion) THEN
SELECT ubicacion INTO n_ubicacion FROM ubicacions WHERE id = NEW.id_ubicacion LIMIT 1;
END IF;

INSERT INTO historico_equipos(usuario, id_equipo, estado, ubicacion, empleado, f_asignacion, created_at) VALUES (CURRENT_USER(), NEW.id, NEW.id_estado, n_ubicacion, NEW.id_empleado, NEW.f_asignacion, CURRENT_DATE())
</code>```

I don''t know where is the problem. In phpmyadmin show the next error:

Something is wrong in your syntax near 'DECLARE n_ubicacion VARCHAR(45) DEFAULT ''; IF (OLD.id_ubicacion <> NEW.id_ubicacion) THEN'

Thanks.

答:
Check if any other statements are present inside the Trigger above the DECLARE statement. If so, then it may throw the error.

Check your delimiter. By default, MySQL's delimiter is ';'. So, on seeing the first ';', your query will break. Hence use some other delimiter before creating the trigger.

Example:

```<code>DELIMITER //

CREATE TRIGGER ...
BEGIN
DECLARE n_ubicacion VARCHAR(45) DEFAULT '';
IF (OLD.id_ubicacion <> NEW.id_ubicacion) THEN
    SELECT ubicacion INTO n_ubicacion FROM ubicacions WHERE id =
                                       NEW.id_ubicacion LIMIT 1;
END IF;
INSERT INTO historico_equipos(usuario, id_equipo, estado, ubicacion, empleado, f_asignacion, created_at) VALUES (CURRENT_USER(), NEW.id, NEW.id_estado, n_ubicacion, NEW.id_empleado, NEW.f_asignacion, CURRENT_DATE())
END//
</code>```

Then again change the DELIMITER to default.

DELIMITER ;

Title: Issue in create trigger phpmyadmin

Body:
I have a problem creating a trigger in phpmyadmin. Here is my syntax:

DECLARE n_ubicacion VARCHAR(45) DEFAULT '';

IF (OLD.id_ubicacion <> NEW.id_ubicacion) THEN
SELECT ubicacion INTO n_ubicacion FROM ubicacions WHERE id = NEW.id_ubicacion LIMIT 1;
END IF;

INSERT INTO historico_equipos(usuario, id_equipo, estado, ubicacion, empleado, f_asignacion, created_at) VALUES (CURRENT_USER(), NEW.id, NEW.id_estado, n_ubicacion, NEW.id_empleado, NEW.f_asignacion, CURRENT_DATE())

I don''t know where is the problem. In phpmyadmin show the next error:

Something is wrong in your syntax near 'DECLARE n_ubicacion VARCHAR(45) DEFAULT ''; IF (OLD.id_ubicacion <> NEW.id_ubicacion) THEN'

Thanks.

Body:
Check if any other statements are present inside the Trigger above the DECLARE statement. If so, then it may throw the error.

Check your delimiter. By default, MySQL's delimiter is ';'. So, on seeing the first ';', your query will break. Hence use some other delimiter before creating the trigger.

Example:

DELIMITER //

CREATE TRIGGER ...
BEGIN
DECLARE n_ubicacion VARCHAR(45) DEFAULT '';
IF (OLD.id_ubicacion <> NEW.id_ubicacion) THEN
    SELECT ubicacion INTO n_ubicacion FROM ubicacions WHERE id =
                                       NEW.id_ubicacion LIMIT 1;
END IF;
INSERT INTO historico_equipos(usuario, id_equipo, estado, ubicacion, empleado, f_asignacion, created_at) VALUES (CURRENT_USER(), NEW.id, NEW.id_estado, n_ubicacion, NEW.id_empleado, NEW.f_asignacion, CURRENT_DATE())
END//

Then again change the DELIMITER to default.

DELIMITER ;


问:
Find and replace in Visual Studio code in a selection
I have the following line in a file I'm editing in VSCode:

...............111.........111.............111..

I want to replace all .s with 0s. However, when I highlight the line and do a find/replace for .s, all the .s in the document are replaced, not just the ones in the line I've select, even when I toggle the "Find in selection" button. Is this a bug? In other editors, if I select a chunk of text and then do a find/replace, it will only find/replace matches within the selected block.

Below is a snippet that you should be able to reproduce the issue with. The ...............111.........111.............111.. line is inside the test_unicode function.

```<code>def test_simple2(self):
        """Simple CSV transduction test with empty fields, more complex idx, different pack_size.

        100011000001000 ->
        ..........111....................111..........11111..........111..
        """
        field_width_stream = pablo.BitStream(int('1000110001000001000', 2))
        idx_marker_stream = pablo.BitStream(int('11101', 2))
        pack_size = 4
        target_format = TransductionTarget.JSON
        csv_column_names = ["col1", "col2", "col3", "col4", "col5"]

        pdep_marker_stream = pablo.BitStream(generate_pdep_stream(field_width_stream,
                                                                  idx_marker_stream,
                                                                  pack_size, target_format,
                                                                  csv_column_names))
        self.assertEqual(pdep_marker_stream.value, 63050402300395548)

    def test_unicode(self):
        """Non-ascii column names.

        Using UTF8. Hard coded SON boilerplate byte size should remain the same, column name
        boilerplate bytes should expand.

        100010010000000 ->
        2 + 4 + 9     2 + 4 + 6     2 + 4 + 7
        ...............111.........111.............111..
        """
        field_width_stream = pablo.BitStream(int('100010001000', 2))
        idx_marker_stream = pablo.BitStream(1)
        pack_size = 64
        target_format = TransductionTarget.JSON
        csv_column_names = ["한국어", "中文", "English"]

        pdep_marker_stream = pablo.BitStream(generate_pdep_stream(field_width_stream,
                                                                  idx_marker_stream,
                                                                  pack_size, target_format,
                                                                  csv_column_names))
        self.assertEqual(pdep_marker_stream.value, 1879277596)
</code>```

I'm using VSCode 1.12.2 in Ubuntu 16.04.

答:
From the VSCode devs:

We used to enable find in selection automatically when opening the
find widget with a selection, but it was too easy to trigger
accidentally and produced a lot of complaints. You probably want to
set "editor.find.autoFindInSelection": true which will make it work
the way you expect.

The VSCode GitHub issue has more details if anyone is interested.

EDIT: The autoFindInSelection option is available starting from VSCode 1.13. That version is currently in development (as of 6/7/2017), so this fix won't work until the new version is released.

ContentLicense: CC BY-SA 4.0

Body:
I have the following line in a file I'm editing in VSCode:

...............111.........111.............111..

I want to replace all .s with 0s. However, when I highlight the line and do a find/replace for .s, all the .s in the document are replaced, not just the ones in the line I've select, even when I toggle the "Find in selection" button. Is this a bug? In other editors, if I select a chunk of text and then do a find/replace, it will only find/replace matches within the selected block.

Below is a snippet that you should be able to reproduce the issue with. The ...............111.........111.............111.. line is inside the test_unicode function.

def test_simple2(self):
        """Simple CSV transduction test with empty fields, more complex idx, different pack_size.

        100011000001000 ->
        ..........111....................111..........11111..........111..
        """
        field_width_stream = pablo.BitStream(int('1000110001000001000', 2))
        idx_marker_stream = pablo.BitStream(int('11101', 2))
        pack_size = 4
        target_format = TransductionTarget.JSON
        csv_column_names = ["col1", "col2", "col3", "col4", "col5"]

        pdep_marker_stream = pablo.BitStream(generate_pdep_stream(field_width_stream,
                                                                  idx_marker_stream,
                                                                  pack_size, target_format,
                                                                  csv_column_names))
        self.assertEqual(pdep_marker_stream.value, 63050402300395548)

    def test_unicode(self):
        """Non-ascii column names.

        Using UTF8. Hard coded SON boilerplate byte size should remain the same, column name
        boilerplate bytes should expand.

        100010010000000 ->
        2 + 4 + 9     2 + 4 + 6     2 + 4 + 7
        ...............111.........111.............111..
        """
        field_width_stream = pablo.BitStream(int('100010001000', 2))
        idx_marker_stream = pablo.BitStream(1)
        pack_size = 64
        target_format = TransductionTarget.JSON
        csv_column_names = ["한국어", "中文", "English"]

        pdep_marker_stream = pablo.BitStream(generate_pdep_stream(field_width_stream,
                                                                  idx_marker_stream,
                                                                  pack_size, target_format,
                                                                  csv_column_names))
        self.assertEqual(pdep_marker_stream.value, 1879277596)

I'm using VSCode 1.12.2 in Ubuntu 16.04.


问:
c# .net 4.0 Covariant vs Contravariant
I'm trying to get something working and struggling with the below when using Contravariance. My understanding is Covariance is where you can return a derived type from a base type. Contravariance is where you can pass in a derived type from a base type as an argument into a class.

So I have the below interface (contravariant):

```<code>public interface IBase<in T> where T: BaseModel
{
        void Process(T model);
}
</code>```

I then have an abstract class

```<code>public abstract class Base<T>: IBase<T> where T: BaseModel
{
    public virtual void Process(T model)
    {
       // throw new System.NotImplementedException();
    }
}
</code>```

and another concrete class

```<code>public class Parent: Base<ParentModel>
{
    public override void Process(ParentModel model)
    {
        // throw new System.NotImplementedException();
    }
}
</code>```

Considering the generic type is only ever used as an input and not a return type, I don't see why I cannot do the below:

```<code>IBase<BaseModel> baseContravariant = new  Parent();
// This doesn't compile. I will eventually have a list of IBase<BaseMode> to which I'd like to pass in different parent instances.
</code>```

I have another example using covariance which is below and works fine.

```<code>public interface IBase<out T> where T : BaseModel, new()
{
    T ProcessAndGet();
}
</code>```

Abstract

```<code>public abstract class Base<T>: IBase<T> where T: BaseModel, new()
{
    public virtual T ProcessAndGet()
    {
        var result = new T() as BaseModel;

        // More shizzle here
        return (T)result;
    }
}
</code>```

Concrete

```<code>public class Parent : Base<ParentModel>
{
    public override ParentModel ProcessAndGet()
    {
        var x = base.ProcessAndGet();
        return x;
    }
}
</code>```

Now I can do

```<code>IBase<BaseModel> baseInstance = new Base<BaseModel>();
IBase<BaseModel> derived = new Parent();
baseInstance = derived;
</code>```

There's more code to the above examples but I've removed it for ease of reading (hopefully!) :-)

答:
Contravariance in this case means that you need to pass in types that are of the specified type or one that is "more specialised" (=> derive from the base type).

Since your Parent implementation in your first example can only process ParentModel, it is invalid to pass in a BaseModel instance. Trying to do new Parent().Process(new BaseModel()) also would not compile. So it is invalid to cast it to IBase<BaseModel>. (assuming ParentModel is a subclass of BaseModel).

In this case the contravariance model is easier to reason about by thinking that an IBase<in T> "consumes a T". So an IBase<ParentModel> "consumes ParentModels". This means it can only be passed values that are instances of ParentModel or can be treated as one (effectively only subclasses).

In your second example you are using <out T>, which is "covariant". This can be described as "it produces instances of T". So a class that "produces" a ParentModel is automatically a "producer" of BaseModel as well: since ParentModel can be cased to BaseModel, IBase<ParentModel> can be casted to IBase<BaseModel> as well.

Title: c# .net 4.0 Covariant vs Contravariant

Body:
I'm trying to get something working and struggling with the below when using Contravariance. My understanding is Covariance is where you can return a derived type from a base type. Contravariance is where you can pass in a derived type from a base type as an argument into a class.

So I have the below interface (contravariant):

public interface IBase<in T> where T: BaseModel
{
        void Process(T model);
}

I then have an abstract class

public abstract class Base<T>: IBase<T> where T: BaseModel
{
    public virtual void Process(T model)
    {
       // throw new System.NotImplementedException();
    }
}

and another concrete class

public class Parent: Base<ParentModel>
{
    public override void Process(ParentModel model)
    {
        // throw new System.NotImplementedException();
    }
}

Considering the generic type is only ever used as an input and not a return type, I don't see why I cannot do the below:

IBase<BaseModel> baseContravariant = new  Parent();
// This doesn't compile. I will eventually have a list of IBase<BaseMode> to which I'd like to pass in different parent instances.

I have another example using covariance which is below and works fine.

public interface IBase<out T> where T : BaseModel, new()
{
    T ProcessAndGet();
}

Abstract

public abstract class Base<T>: IBase<T> where T: BaseModel, new()
{
    public virtual T ProcessAndGet()
    {
        var result = new T() as BaseModel;

        // More shizzle here
        return (T)result;
    }
}

Concrete

public class Parent : Base<ParentModel>
{
    public override ParentModel ProcessAndGet()
    {
        var x = base.ProcessAndGet();
        return x;
    }
}

Now I can do

IBase<BaseModel> baseInstance = new Base<BaseModel>();
IBase<BaseModel> derived = new Parent();
baseInstance = derived;

There's more code to the above examples but I've removed it for ease of reading (hopefully!) :-)


问:
Disabled other select if value equal to 1
I have dynamic select option. Only 0 and 1 user can select.

If user select value = 1, I want disable other select & keep current.

If user select value = 0 from current option so other select enable again.

HTML

```<code>A :
<select name="quantity[1]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
B :
<select name="quantity[2]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
C:
<select name="quantity[3]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
</code>```

jQuery

```<code>$(document).on('change keyup keypress', '.trigger', function() {
  $(".quantity").prop("disabled", true);

  $('.quantity option:selected').each(function() {
    quantity += parseInt($(this).val()) || 0;
    if (quantity == 1) {
      $(this).prop("disabled", false);
    } else {
      $(this).prop("disabled", true);
    }
  });
});
</code>```

https://jsfiddle.net/qq1q6orw/2/

答:
here is updated fiddle:

https://jsfiddle.net/8sbk4dgo/1/

```<code>$(document).on('change keyup keypress', '.trigger', function() {
    if($(this).val() == 1){
      $(".quantity").not(this).prop("disabled", true);
    }else{
    $(".quantity").prop("disabled", false);
    }

    $('.quantity option:selected').each(function() {
        var quantity = parseInt($(this).val());
        if (quantity == 1) {
            $(this).prop("disabled", false);
        } else {
            $(this).prop("disabled", true);
        }
    });
});
</code>```

Body:
I have dynamic select option. Only 0 and 1 user can select.

If user select value = 1, I want disable other select & keep current.

If user select value = 0 from current option so other select enable again.

HTML

A :
<select name="quantity[1]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
B :
<select name="quantity[2]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
C:
<select name="quantity[3]" class="form-control quantity trigger">
  <option value="0">0</option>
  <option value="1">1</option>
</select>

jQuery

$(document).on('change keyup keypress', '.trigger', function() {
  $(".quantity").prop("disabled", true);

  $('.quantity option:selected').each(function() {
    quantity += parseInt($(this).val()) || 0;
    if (quantity == 1) {
      $(this).prop("disabled", false);
    } else {
      $(this).prop("disabled", true);
    }
  });
});

https://jsfiddle.net/qq1q6orw/2/

Body:
here is updated fiddle:

https://jsfiddle.net/8sbk4dgo/1/

$(document).on('change keyup keypress', '.trigger', function() {
    if($(this).val() == 1){
      $(".quantity").not(this).prop("disabled", true);
    }else{
    $(".quantity").prop("disabled", false);
    }

    $('.quantity option:selected').each(function() {
        var quantity = parseInt($(this).val());
        if (quantity == 1) {
            $(this).prop("disabled", false);
        } else {
            $(this).prop("disabled", true);
        }
    });
});


问:
WooCommerce 3.0 enqueue bundled scripts and styles, zoom, photoswipe
I was using prettyphoto in my WooCommerce Addon, and it was loading from WooCommerce files, but in v 3.0 WooCommerce has removed the prettyphoto and started using other scripts like

flexslider

zoom

photoswipe

I want to enqueue their these bundled scripts, but can't find a function to do that. Any help will be appreciated.

Thanks

答:
I'm not sure I fully understand your problem, but if I do maybe this can help:

in your function.php add these lines:

```<code>add_action( 'after_setup_theme', 'photoswipe_gallery_setup' );

function photoswipe_gallery_setup() {
  add_theme_support( 'wc-product-gallery-zoom' );
  add_theme_support( 'wc-product-gallery-lightbox' );
  add_theme_support( 'wc-product-gallery-slider' );
}
</code>```

This will enable support for PhotoSwipe
You can enable/disable features deleting/commenting the correstonding line.

credits

Body:
I'm not sure I fully understand your problem, but if I do maybe this can help:

in your function.php add these lines:

add_action( 'after_setup_theme', 'photoswipe_gallery_setup' );

function photoswipe_gallery_setup() {
  add_theme_support( 'wc-product-gallery-zoom' );
  add_theme_support( 'wc-product-gallery-lightbox' );
  add_theme_support( 'wc-product-gallery-slider' );
}

This will enable support for PhotoSwipe
You can enable/disable features deleting/commenting the correstonding line.

credits


问:
C - fscanf error with char *
I'm trying to read a txt file with this format:

```<code>8590 2 07 Goku
8591 2 07 Vegeta
6973 2 07 Picolo
5432 3 02 Jerez
6773 3 02 Sour
4689 4 03 Mosco
6981 5 06 Cabba
7891 5 06 Frost
</code>```

The columns are: hp, universe color, universe number and name. What I do is this read the line and save the parameters in an array of structures called warrior with this format:

```<code>typedef struct Warrior{
    int hp;
    int color;
    int universe;
    char * name;
    int posX;
    int posY;
    int ki;
} warrior;

warrior createWarrior(int inHp, int inColor, int inUniverse, char * inName){
    warrior guerrero;
    guerrero.hp = inHp;
    guerrero.color = inColor;
    guerrero.universe = inUniverse;
    guerrero.name = inName;
    guerrero.posX= 0;
    guerrero.posY= 0;
    guerrero.ki=0;
    return guerrero;
}
</code>```

The readFile code is:

```<code>warrior * readFile(char * nameFile, warrior * listGuerrero){
    FILE * filePointer;
    int sizeFile = 0, ch = 0;
    int inHp, inColor, inUniverse;
    char inName[50];

    filePointer = fopen(nameFile, "r");

    while(fscanf(filePointer, "%d %d %d %s\n", &inHp, &inColor, &inUniverse, inName) != EOF){
        sizeFile ++;
    }

    rewind(filePointer);

    listGuerrero = (warrior *)malloc(sizeFile*sizeof(warrior));
    for(int k = 0; k < sizeFile; k++){
        fscanf(filePointer, "%d %d %d %s\n", &inHp, &inColor, &inUniverse, &inName[0]);
        listGuerrero[k] = createWarrior(inHp,inColor,inUniverse,inName);
        printf("k: %d - HP: %d - Color: %d - Universo: %d - Nombre: %s \n", k, listGuerrero[k].hp, listGuerrero[k].color, listGuerrero[k].universe, listGuerrero[k].name);
    }

    fclose(filePointer);
    return listGuerrero;
}
</code>```

But for some reason I can't understand, the final list of warriors all have the same name like:

```<code>j: 0 - HP: 8590 - Color: 2 - Universo: 7 - Nombre: Frost
j: 1 - HP: 8591 - Color: 2 - Universo: 7 - Nombre: Frost
j: 2 - HP: 6973 - Color: 2 - Universo: 7 - Nombre: Frost
j: 3 - HP: 5432 - Color: 3 - Universo: 2 - Nombre: Frost
j: 4 - HP: 6773 - Color: 3 - Universo: 2 - Nombre: Frost
j: 5 - HP: 4689 - Color: 4 - Universo: 3 - Nombre: Frost
j: 6 - HP: 6981 - Color: 5 - Universo: 6 - Nombre: Frost
j: 7 - HP: 7891 - Color: 5 - Universo: 6 - Nombre: Frost
</code>```

Is something wrong with the inName pointer?

When I debug, the first iteration prints:

```<code>j: 0 - HP: 8590 - Color: 2 - Universo: 7 - Nombre: Goku
</code>```

And the second iteration prints:

```<code>j: 0 - HP: 8590 - Color: 2 - Universo: 7 - Nombre: Vegeta
j: 1 - HP: 8591 - Color: 2 - Universo: 7 - Nombre: Vegeta
</code>```

and so on.

答:
the problem is that you read the first name and after that for every warrior in the file you just set a pointer to that first name. For every element from your file you must allocate new memory for it's name (using malloc) and copy the new name into it( using strcpy). Because you declared the name char*

```<code>warrior createWarrior(int inHp, int inColor, int inUniverse, char * inName){

    warrior guerrero;
    guerrero.hp = inHp;
    guerrero.color = inColor;
    guerrero.universe = inUniverse;

    guerrero.name = malloc(sizeof(char) * 30); // 30 is the length of the name

    strcpy(guerrero.name,inName); // copy new name
    guerrero.posX= 0;
    guerrero.posY= 0;
    guerrero.ki=0;

    return guerrero;

}
</code>```

There is another cool way to do it using strdup() which basically alocates new memory and copy the parameter string there ( but i've not tested this):

```<code>warrior createWarrior(int inHp, int inColor, int inUniverse, char * inName){

    warrior guerrero;
    guerrero.hp = inHp;
    guerrero.color = inColor;
    guerrero.universe = inUniverse;

    guerrero.name = strdup(inName);
    guerrero.posX= 0;
    guerrero.posY= 0;
    guerrero.ki=0;

    return guerrero;

}
</code>```

Don't forget:

```<code>#include <string.h>
#include <stdlib.h>
</code>```

Title: C - fscanf error with char *

Body:
I'm trying to read a txt file with this format:

8590 2 07 Goku
8591 2 07 Vegeta
6973 2 07 Picolo
5432 3 02 Jerez
6773 3 02 Sour
4689 4 03 Mosco
6981 5 06 Cabba
7891 5 06 Frost

The columns are: hp, universe color, universe number and name. What I do is this read the line and save the parameters in an array of structures called warrior with this format:

typedef struct Warrior{
    int hp;
    int color;
    int universe;
    char * name;
    int posX;
    int posY;
    int ki;
} warrior;

warrior createWarrior(int inHp, int inColor, int inUniverse, char * inName){
    warrior guerrero;
    guerrero.hp = inHp;
    guerrero.color = inColor;
    guerrero.universe = inUniverse;
    guerrero.name = inName;
    guerrero.posX= 0;
    guerrero.posY= 0;
    guerrero.ki=0;
    return guerrero;
}

The readFile code is:

warrior * readFile(char * nameFile, warrior * listGuerrero){
    FILE * filePointer;
    int sizeFile = 0, ch = 0;
    int inHp, inColor, inUniverse;
    char inName[50];

    filePointer = fopen(nameFile, "r");

    while(fscanf(filePointer, "%d %d %d %s\n", &inHp, &inColor, &inUniverse, inName) != EOF){
        sizeFile ++;
    }

    rewind(filePointer);

    listGuerrero = (warrior *)malloc(sizeFile*sizeof(warrior));
    for(int k = 0; k < sizeFile; k++){
        fscanf(filePointer, "%d %d %d %s\n", &inHp, &inColor, &inUniverse, &inName[0]);
        listGuerrero[k] = createWarrior(inHp,inColor,inUniverse,inName);
        printf("k: %d - HP: %d - Color: %d - Universo: %d - Nombre: %s \n", k, listGuerrero[k].hp, listGuerrero[k].color, listGuerrero[k].universe, listGuerrero[k].name);
    }

    fclose(filePointer);
    return listGuerrero;
}

But for some reason I can't understand, the final list of warriors all have the same name like:

j: 0 - HP: 8590 - Color: 2 - Universo: 7 - Nombre: Frost
j: 1 - HP: 8591 - Color: 2 - Universo: 7 - Nombre: Frost
j: 2 - HP: 6973 - Color: 2 - Universo: 7 - Nombre: Frost
j: 3 - HP: 5432 - Color: 3 - Universo: 2 - Nombre: Frost
j: 4 - HP: 6773 - Color: 3 - Universo: 2 - Nombre: Frost
j: 5 - HP: 4689 - Color: 4 - Universo: 3 - Nombre: Frost
j: 6 - HP: 6981 - Color: 5 - Universo: 6 - Nombre: Frost
j: 7 - HP: 7891 - Color: 5 - Universo: 6 - Nombre: Frost

Is something wrong with the inName pointer?

When I debug, the first iteration prints:

j: 0 - HP: 8590 - Color: 2 - Universo: 7 - Nombre: Goku

And the second iteration prints:

j: 0 - HP: 8590 - Color: 2 - Universo: 7 - Nombre: Vegeta
j: 1 - HP: 8591 - Color: 2 - Universo: 7 - Nombre: Vegeta

and so on.

Body:
the problem is that you read the first name and after that for every warrior in the file you just set a pointer to that first name. For every element from your file you must allocate new memory for it's name (using malloc) and copy the new name into it( using strcpy). Because you declared the name char*

warrior createWarrior(int inHp, int inColor, int inUniverse, char * inName){

    warrior guerrero;
    guerrero.hp = inHp;
    guerrero.color = inColor;
    guerrero.universe = inUniverse;

    guerrero.name = malloc(sizeof(char) * 30); // 30 is the length of the name

    strcpy(guerrero.name,inName); // copy new name
    guerrero.posX= 0;
    guerrero.posY= 0;
    guerrero.ki=0;

    return guerrero;

}

There is another cool way to do it using strdup() which basically alocates new memory and copy the parameter string there ( but i've not tested this):

warrior createWarrior(int inHp, int inColor, int inUniverse, char * inName){

    warrior guerrero;
    guerrero.hp = inHp;
    guerrero.color = inColor;
    guerrero.universe = inUniverse;

    guerrero.name = strdup(inName);
    guerrero.posX= 0;
    guerrero.posY= 0;
    guerrero.ki=0;

    return guerrero;

}

Don't forget:

#include <string.h>
#include <stdlib.h>


问:
How can I implement an anti-spamming technique on my IRC bot?
I run my bot in a public channel with hundreds of users. Yesterday a person came in and just abused it.

I would like to let anyone use the bot, but if they spam commands consecutively  and if they aren't a bot "owner" like me when I debug then I would like to add them to an ignored list which expires in an hour or so.

One way I'm thinking would be to save all commands by all users, in a dictionary such as:

```<code>({
  'meder@freenode': [{command:'.weather 20851', timestamp: 209323023 }],
  'jack@efnet': [{command:'.seen john' }]
})
</code>```

I would setup a cron job to flush this out every 24 hours, but I would basically determine if a person has made X number of commands in a duration of say, 15 seconds and add them to an ignore list.

Actually, as I'm writing this answer I thought of a better idea.. maybe instead of storing each users commands, just store the the bot's commands in a list and keep on pushing until it reaches a limit of say, 15.

```<code>lastCommands = [], limit = 5;

function handleCommand( timeObj, action ) {
    if ( lastCommands.length < limit ) {
        action();
    } else {
        // enumerate through lastCommands and compare the timestamps of all 5 commands
        // if the user is the same for all 5 commands, and...
        // if the timestamps are all within the vicinity of 20 seconds
        // add the user to the ignoreList
    }
}

watch_for('command', function() {
   handleCommand({timestamp: 2093293032, user: user}, function(){ message.say('hello there!') })
});
</code>```

I would appreciate any advice on the matter.

答:
These answers seem to be going the wrong way about this.

IRC Servers will disconnect your client regardless of whether you're "debugging" or not if the client or bot is flooding a channel or the server in general.

Make a blanket flood control, using the method @nmichaels has detailed, but on the bot's network connection to the server itself.

Body:
I run my bot in a public channel with hundreds of users. Yesterday a person came in and just abused it.

I would like to let anyone use the bot, but if they spam commands consecutively  and if they aren't a bot "owner" like me when I debug then I would like to add them to an ignored list which expires in an hour or so.

One way I'm thinking would be to save all commands by all users, in a dictionary such as:

({
  'meder@freenode': [{command:'.weather 20851', timestamp: 209323023 }],
  'jack@efnet': [{command:'.seen john' }]
})

I would setup a cron job to flush this out every 24 hours, but I would basically determine if a person has made X number of commands in a duration of say, 15 seconds and add them to an ignore list.

Actually, as I'm writing this answer I thought of a better idea.. maybe instead of storing each users commands, just store the the bot's commands in a list and keep on pushing until it reaches a limit of say, 15.

lastCommands = [], limit = 5;

function handleCommand( timeObj, action ) {
    if ( lastCommands.length < limit ) {
        action();
    } else {
        // enumerate through lastCommands and compare the timestamps of all 5 commands
        // if the user is the same for all 5 commands, and...
        // if the timestamps are all within the vicinity of 20 seconds
        // add the user to the ignoreList
    }
}

watch_for('command', function() {
   handleCommand({timestamp: 2093293032, user: user}, function(){ message.say('hello there!') })
});

I would appreciate any advice on the matter.


问:
Reflection Setting values of a class
I am trying to build an extension to populate an object with values from a SQLDataReader.

The code I have so far is

```<code>public static T RetunObject<T>(this Type source, SqlDataReader dr)
    {
        Type type = source.GetType();
        PropertyInfo[] properties = type.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            property.SetValue(property, dr[property.Name]);
            type.GetProperty(property.Name).SetValue(type, dr[property.Name]);
        }

        return type.Cast<T>();
    }
</code>```

One thing for sure is the last line is not right and not exactly sure if there is a way for this to work at this point.

The goal results would be to use the code like

```<code>MyClass myclass = new MyClass();
var results = myclass.ReturnObject(myDataReader);
</code>```

Reflection has never been my strong suit. so I am pretty sure I am pretty far off.

UPDATED CODE WHICH APPEARS TO WORK

```<code>    public static object RetunObject(this object source, SqlDataReader dr)
    {
        while (dr.Read())
        {
            foreach (PropertyInfo property in source.GetType().GetRuntimeProperties())
            {
                if(dr.GetSchemaTable().Select("ColumnName='"+ property.Name+"'").Count() == 1)
                {
                    var readervalue = dr.GetValue(dr.GetOrdinal(property.Name));
                    property.SetValue(source, readervalue);
                }
            }
        }
        return source;
    }
</code>```

it is used like

```<code>     return (Role)role.RetunObject(sqlcomm.ExecuteReader());
</code>```

Takes a SQLDataReader and returns an generic object which is able to be cast to the object type you need it to be. Obviously if you try to cast to an invalid type of object then it won't work but so far this seems to work. My next trial will be to test nested class to see if it will work there as well.

答:
In your example there is plenty errors and it is completely unclear what you try to accomplish. Probably you tried to just apply properties from reader to your object:

```<code>public static T RetunObject<T>(this T source, SqlDataReader dr)
{
    var type = typeof(T);
    var properties = type.GetProperties();
    foreach (var property in properties)
    {
        property.SetValue(source, dr[property.Name]);
    }
    return source;
}
</code>```

But, I recommend you to use Entity Framework for this, because you probably creating another bicycle by doing this. This task was completed a lot better/faster/safer than the solution you try to accomplish.

Try to spend a little of your time on things people commonly use before trying to implement something, that no one beside you will understand/support.

It will be a lot more useful and faster than spending time on potentially buggy code. Here is good start in EF Code First: https://msdn.microsoft.com/en-us/library/jj193542(v=vs.113).aspx

Title: Reflection Setting values of a class

Body:
I am trying to build an extension to populate an object with values from a SQLDataReader.

The code I have so far is

public static T RetunObject<T>(this Type source, SqlDataReader dr)
    {
        Type type = source.GetType();
        PropertyInfo[] properties = type.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            property.SetValue(property, dr[property.Name]);
            type.GetProperty(property.Name).SetValue(type, dr[property.Name]);
        }

        return type.Cast<T>();
    }

One thing for sure is the last line is not right and not exactly sure if there is a way for this to work at this point.

The goal results would be to use the code like

MyClass myclass = new MyClass();
var results = myclass.ReturnObject(myDataReader);

Reflection has never been my strong suit. so I am pretty sure I am pretty far off.

UPDATED CODE WHICH APPEARS TO WORK

    public static object RetunObject(this object source, SqlDataReader dr)
    {
        while (dr.Read())
        {
            foreach (PropertyInfo property in source.GetType().GetRuntimeProperties())
            {
                if(dr.GetSchemaTable().Select("ColumnName='"+ property.Name+"'").Count() == 1)
                {
                    var readervalue = dr.GetValue(dr.GetOrdinal(property.Name));
                    property.SetValue(source, readervalue);
                }
            }
        }
        return source;
    }

it is used like

     return (Role)role.RetunObject(sqlcomm.ExecuteReader());

Takes a SQLDataReader and returns an generic object which is able to be cast to the object type you need it to be. Obviously if you try to cast to an invalid type of object then it won't work but so far this seems to work. My next trial will be to test nested class to see if it will work there as well.

Body:
In your example there is plenty errors and it is completely unclear what you try to accomplish. Probably you tried to just apply properties from reader to your object:

public static T RetunObject<T>(this T source, SqlDataReader dr)
{
    var type = typeof(T);
    var properties = type.GetProperties();
    foreach (var property in properties)
    {
        property.SetValue(source, dr[property.Name]);
    }
    return source;
}

But, I recommend you to use Entity Framework for this, because you probably creating another bicycle by doing this. This task was completed a lot better/faster/safer than the solution you try to accomplish.

Try to spend a little of your time on things people commonly use before trying to implement something, that no one beside you will understand/support.

It will be a lot more useful and faster than spending time on potentially buggy code. Here is good start in EF Code First: https://msdn.microsoft.com/en-us/library/jj193542(v=vs.113).aspx


问:
Usage of filter_path with helpers.scan in elastisearch client
When doing a search operation in elasticsearch i want the metadata to be filtered out and return only "_source" in the response. I'm able to achieve the same through "search" in the following way:

out1 = es.search(index='index.com', filter_path=['hits.hits._id',
  'hits.hits._source'])

But when i do the same with scan method it just returns an empty list:

out2 = helpers.scan(es, query, index='index.com',
  doc_type='2016-07-27',filter_path= ['hits.hits._source'])

The problem may be with the way i'm processing the response of 'scan' method or with the way i'm passing the value to filter_path. To check the output i parse out2 to a list.

答: You could pass filter_path=['_scroll_id', '_shards', 'hits.hits._source'] to the scan helper to get it to work. Obviously that leaves some metadata in the response but it removes as much as possible while allowing the scroll to work. _shards is required because it is used internally by the scan helper.


问:
Remove the JavaScript object from array with checkbox in jquery table
I'm working on project here I'm facing an issue: I have created jQuery table and on checkbox checked get all the values of specific row and push it into array now I want to remove each row record from array when I uncheck that row. I have written some script for remove but it doesn't work properly. And also tell me that is there any easy way to get data of specific row with checkbox in jQuery table.

Script

$.ajax({
    type: 'POST',
    url: "/Student/GetFee",
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    data: JSON.stringify({ Class_Id: Class_Id }),
    success: function (list) {
        $("#view").html('');
        $.each(list, function (key, value) {
            var html = $(
                '
' +
                    '' + value.Id + '	' +
                    '' + value.FeeHeadName + '	' +
                    '' + value.SchoolName + '	' +
                    '' + value.ClassName + '	' +
                    '' + value.Amount + '	' +
                    '' + "<input type='text'  name='Paid' class='paid' onkeypress='paid(this)'/>" + '	' +
                    '' + "<input type='text' class='Discount' name='Discount' onkeypress='discount(this)'/>" + '	' +
                    '' + "<input type='text' class='NetAmount' name='NetAmount' />" + '	' +
                    '' + "<input type='checkbox' class='ckb'/>" + '	' +
                '
');
            $("#view").append(html);
            html = '';
        });

        //pushing objects in array
        $('#view input[type=checkbox]').click(function () {
            var row = $(this).closest('tr');
            var id = row.find('td:eq(0)').text();
            var fname = row.find('td:eq(1)').text();
            var sname = row.find('td:eq(2)').text();
            var cname = row.find('td:eq(3)').text();
            var amount = row.find('td:eq(4)').text();
            var paid = row.find($('.paid')).val();
            var discount = row.find($('.Discount')).val();
            var netAmount = row.find($('.NetAmount')).val();

            if ($(this).is(":checked")) {
                info.push({
                    Fee_Id: id,
                    FeeHeadName: fname,
                    sname: sname,
                    cname: cname,
                    Amount: amount,
                    Paid: paid,
                    Discount: discount,
                    NetAmount: netAmount
                });
                console.log(info);
            }
            else {
                if ($(this).not(":checked")) {
                    var x = info.indexOf($(this).val());
                    info.splice(x, 1);
                    console.log(info);
                }
            }
        });
    }
});```

答:
You have to loop inside the array and check which one have the id of the unchecked row</p>

```<code>if ($(this).not(":checked")) {
    var indexToRemove = -1;

    for (var i = 0; i < info.length; i++) {
        if (info[i].Fee_id == id) {
            indexToRemove = i;
            break;
        }
    }
    if (indexToRemove != -1) {
        info.splice(indexToRemove, 1);
    }
}
</code>```

Body:
You have to loop inside the array and check which one have the id of the unchecked row

if ($(this).not(":checked")) {
    var indexToRemove = -1;

    for (var i = 0; i < info.length; i++) {
        if (info[i].Fee_id == id) {
            indexToRemove = i;
            break;
        }
    }
    if (indexToRemove != -1) {
        info.splice(indexToRemove, 1);
    }
}


问:
Data Objects from $.ajax with json are shallow
I've got a JSON looking like this (design might be wrong)

```<code>{
  "Supermarkt": {
    "name": "Supermarkt",
    "translations": {
      "trolley": "Einkaufswagen",
      "vegetables": "Gemüse",
      "cocoa": "Kakao",
      "chocolate": "Schokolade"
    },
    "pronunciations": []
  },
  "Script1336Kidee": {
    "name": "Script1336Kidee",
    "translations": {
      "Trojaner": "RAT",
      "Laufzeit-Packer": "Magie",
      "PHP": "Der letzte Dreck",
      "JavaScript": "Wild-West"
    },
    "pronunciations": []
  }
}
</code>```

Which I get with a ajax call (already JSON-decoded through dataType: "json" $.ajax option):

```<code>let lessonCall = $.ajax("https://www2.htw-dresden.de/~s70357/vokabel.php/",{dataType: "json"});
lessonCall.fail((jqXHR, status, error) => {
    console.log(status);
    console.log(error);
});
lessonCall.done((data,status) => {
    console.log(status);
    console.log(data);
    for (let lesson in data){
        console.log(lesson);
        console.log(lesson.name);
    }
});
</code>```

Problem is lesson.name is undefined although console.log(data); show the healthy data Object with the healthy subsub-Objects, but lesson seems to be just a string-like thing.

How can I iterate through my "name"s?!

答:
Have you tried calling let jsonData = JSON.parse(data) before your for loop?

Would you be able to modify the json format? If so, you could turn it into an array:

```<code>[
  {
    "name": "Supermarkt",
    "translations": {
      "trolley": "Einkaufswagen",
      "vegetables": "Gemüse",
      "cocoa": "Kakao",
      "chocolate": "Schokolade"
    },
    "pronunciations": []
  },
  {
    "name": "Script1336Kidee",
    "translations": {
      "Trojaner": "RAT",
      "Laufzeit-Packer": "Magie",
      "PHP": "Der letzte Dreck",
      "JavaScript": "Wild-West"
    },
    "pronunciations": []
  }
]
</code>```

Body:
I've got a JSON looking like this (design might be wrong)

{
  "Supermarkt": {
    "name": "Supermarkt",
    "translations": {
      "trolley": "Einkaufswagen",
      "vegetables": "Gemüse",
      "cocoa": "Kakao",
      "chocolate": "Schokolade"
    },
    "pronunciations": []
  },
  "Script1336Kidee": {
    "name": "Script1336Kidee",
    "translations": {
      "Trojaner": "RAT",
      "Laufzeit-Packer": "Magie",
      "PHP": "Der letzte Dreck",
      "JavaScript": "Wild-West"
    },
    "pronunciations": []
  }
}

Which I get with a ajax call (already JSON-decoded through dataType: "json" $.ajax option):

let lessonCall = $.ajax("https://www2.htw-dresden.de/~s70357/vokabel.php/",{dataType: "json"});
lessonCall.fail((jqXHR, status, error) => {
    console.log(status);
    console.log(error);
});
lessonCall.done((data,status) => {
    console.log(status);
    console.log(data);
    for (let lesson in data){
        console.log(lesson);
        console.log(lesson.name);
    }
});

Problem is lesson.name is undefined although console.log(data); show the healthy data Object with the healthy subsub-Objects, but lesson seems to be just a string-like thing.

How can I iterate through my "name"s?!

Body:
Have you tried calling let jsonData = JSON.parse(data) before your for loop?

Would you be able to modify the json format? If so, you could turn it into an array:

[
  {
    "name": "Supermarkt",
    "translations": {
      "trolley": "Einkaufswagen",
      "vegetables": "Gemüse",
      "cocoa": "Kakao",
      "chocolate": "Schokolade"
    },
    "pronunciations": []
  },
  {
    "name": "Script1336Kidee",
    "translations": {
      "Trojaner": "RAT",
      "Laufzeit-Packer": "Magie",
      "PHP": "Der letzte Dreck",
      "JavaScript": "Wild-West"
    },
    "pronunciations": []
  }
]


问:
How to calculate g-force using x, y, z values from the accelerometer in Android 1.6
I can get the three x, y, and z values from the accelerometer in Android. How can I use these to calculate the g-force?</p>

答:
Just select TYPE_GRAVITY instead of TYPE_ACCELEROMETER as sensor type:

https://developer.android.com/guide/topics/sensors/sensors_motion.html#sensors-motion-grav


问:
is it possible to hide the hourglass during a $http.get request?
I have an $http.get request that takes a while to be finished. During its execution, the hourglass is shown on the screen, preventing the user to use it.

Can I simply hide the hourglass meanwhile the request is being processed?

Thanks.

答:
You can create boolean isLoad, set it true while executing function and set it false when finished.
So this flag can help you set CSS.

if you use Observable :

GetSomething():void {
  this.isLoad = true;
  this.apiMethod().subscribe(data=>{
    //do something with data
    this.isLoad = false;
  });
}```
</div>
</div>
</p>

<p>if you use calbacks:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>GetSomething():void {
  this.isLoad = true;
  this.apiMethod(data => {
    //do something with data
    this.isLoad = false;
  });
}</code>```

Body:
You can create boolean isLoad, set it true while executing function and set it false when finished.
So this flag can help you set CSS.

if you use Observable :

GetSomething():void {
  this.isLoad = true;
  this.apiMethod().subscribe(data=>{
    //do something with data
    this.isLoad = false;
  });
}

if you use calbacks:

GetSomething():void {
  this.isLoad = true;
  this.apiMethod(data => {
    //do something with data
    this.isLoad = false;
  });
}


问:
Is ASP.NET MVC's Checkbox Implementation Accessible / Screen Reader-Friendly?
If you've ever looked at what ASP.NET MVC actually renders when you use @Html.CheckBoxFor, then you've seen that each checkbox you request to be rendered actually results in the emission of not one but two input tags. One is the "true" value checkbox, and the other is for "false." The latter input is of type "hidden".

Generally this doesn't cause problems if you're using ASP.NET MVC correctly. You wouldn't notice the input doubling unless you tried to, for example, do something directly with Request.Form(e.g. Why does ASP.NET MVC Html.CheckBox output two INPUTs with the same name?)

My question, though, is how screen readers deal with this. For example, can they be relied upon to correctly report only the visible checkbox to the site user?

答: Screen readers will ignore hidden inputs.</p>


问:
accessing the 'ui' object in a jquery-ui event
So I am trying to get the height of an autcomplete input when the open function fires. My code looks like this

```<code> open: function(event, ui) {
                $('#paddingDiv').css('height', '300px');
            },
</code>```

I have tried looking for more information about how you access the object but keep just finding simple tutorials, nothing in the way "structure of the ui object in events" or something like that, I have tried various ways to get the height but nothing seems to work.

Where can I find more information about how to work with the ui object?

答:
I suspect you want:

```<code>$(this).autocomplete("widget").height();
</code>```

widget()

Returns a jQuery object containing the menu element. Although the menu items are constantly created and destroyed, the menu element itself is created during initialization and is constantly reused.

This method does not accept any arguments.

Then use it like:

```<code>open: function(event, ui) {
  $('#paddingDiv').css('height', '300px');
  console.log($(event.target).autocomplete("widget").height());
  // Not sure if $(this) = event.target
},
</code>```

Body:
So I am trying to get the height of an autcomplete input when the open function fires. My code looks like this

 open: function(event, ui) {
                $('#paddingDiv').css('height', '300px');
            },

I have tried looking for more information about how you access the object but keep just finding simple tutorials, nothing in the way "structure of the ui object in events" or something like that, I have tried various ways to get the height but nothing seems to work.

Where can I find more information about how to work with the ui object?

Body:
I suspect you want:

$(this).autocomplete("widget").height();

widget()

Returns a jQuery object containing the menu element. Although the menu items are constantly created and destroyed, the menu element itself is created during initialization and is constantly reused.

This method does not accept any arguments.

Then use it like:

open: function(event, ui) {
  $('#paddingDiv').css('height', '300px');
  console.log($(event.target).autocomplete("widget").height());
  // Not sure if $(this) = event.target
},


问:
No compiler found in your classpath! (you may need to add 'tools.jar') Axis 1.4 + Tomcat 9.0
I already did everything to correct this error, since the modified environment variables , already put the tools.jar within the tomcat9.0 / bin and / lib in addition to the axis / WEB -INF / lib.

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

-<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">

-<soapenv:Body>

-<soapenv:Fault>

<faultcode>soapenv:Server.userException</faultcode>

<faultstring>java.lang.RuntimeException: No compiler found in your classpath! (you may need to add 'tools.jar')</faultstring>

-<detail>

<ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">DESKTOP-MRKMOSG</ns1:hostname>

</detail>

</soapenv:Fault>

</soapenv:Body>

</soapenv:Envelope>```

AMBIENTE:

CATALINA_HOME=C:\Program Files\Apache Software Foundation\Tomcat 9.0

JAVA_HOME=C:\Program Files\Java\jdk1.8.0_77

PATH=%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%PATH%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin

CLASSPATH=%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%JAVA_HOME%;%JAVA_HOME%\bin;

答:
I know that is an old question but I just figure out a way to solve a same problem.

In the axis\lib folder there is no tools.jar file. That file is on your JDK\lib folder. So just copy that jar file and paste it on the axis\lib folder.

P.S. Make sure that you have already defined a system variable called AXISCLASSPATH with value the destination of the jar files (e.g. C:\Program Files\axis-1_4\lib).

Body:
I already did everything to correct this error, since the modified environment variables , already put the tools.jar within the tomcat9.0 / bin and / lib in addition to the axis / WEB -INF / lib.

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

-<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">

-<soapenv:Body>

-<soapenv:Fault>

<faultcode>soapenv:Server.userException</faultcode>

<faultstring>java.lang.RuntimeException: No compiler found in your classpath! (you may need to add 'tools.jar')</faultstring>

-<detail>

<ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">DESKTOP-MRKMOSG</ns1:hostname>

</detail>

</soapenv:Fault>

</soapenv:Body>

</soapenv:Envelope>

AMBIENTE:

CATALINA_HOME=C:\Program Files\Apache Software Foundation\Tomcat 9.0

JAVA_HOME=C:\Program Files\Java\jdk1.8.0_77

PATH=%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%PATH%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin

CLASSPATH=%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%JAVA_HOME%;%JAVA_HOME%\bin;


问:
Overriding hashCode() - is this good enough?
For a class whose fields are solely primitive, ex.:

```<code>class Foo
{
    int a;
    String b;
    boolean c;
    long d;

    boolean equals(Object o)
    {
        if (this == o) return true;
        if (!(o instanceof Foo)) return false;
        Foo other = (Foo) o;
        return a == other.a && b.equals(other.b) && c == other.c && d = other.d;
    }
}
</code>```

Is this a reasonably "good enough" way to write hashCode()?

```<code>boolean hashCode()
{
    return (b + a + c + d).hashCode();
}
</code>```

That is, I construct a String out of the same fields that equals() uses, and then just use String#hashCode().

Edit:  I've updated my question to include a long field. How should a long be handled in hashCode()? Just let it overflow int?

答:
Your hash code does satisfy the property that if two objects are equal, then their hash codes need to be equal.  So, in that way it is 'good enough'.  However, it is fairly simple to create collisions in the hash codes which will degrade the performance of hash based data structures.

I would implement it slightly differently though:

```<code>public int hashCode() {
    return a * 13 + b.hashCode() * 23 + (c? 31: 7);
}
</code>```

You should check out the documentation for the hashCode() method of Object.  It lays out the things that the hash code must satisfy.

Body:
For a class whose fields are solely primitive, ex.:

class Foo
{
    int a;
    String b;
    boolean c;
    long d;

    boolean equals(Object o)
    {
        if (this == o) return true;
        if (!(o instanceof Foo)) return false;
        Foo other = (Foo) o;
        return a == other.a && b.equals(other.b) && c == other.c && d = other.d;
    }
}

Is this a reasonably "good enough" way to write hashCode()?

boolean hashCode()
{
    return (b + a + c + d).hashCode();
}

That is, I construct a String out of the same fields that equals() uses, and then just use String#hashCode().

Edit:  I've updated my question to include a long field. How should a long be handled in hashCode()? Just let it overflow int?

Body:
Your hash code does satisfy the property that if two objects are equal, then their hash codes need to be equal.  So, in that way it is 'good enough'.  However, it is fairly simple to create collisions in the hash codes which will degrade the performance of hash based data structures.

I would implement it slightly differently though:

public int hashCode() {
    return a * 13 + b.hashCode() * 23 + (c? 31: 7);
}

You should check out the documentation for the hashCode() method of Object.  It lays out the things that the hash code must satisfy.


问:
Exit android app on back pressed
I am building an Android App. How to exit an Android App when back is pressed. Android version is 2.3.3 and above. The Android App goes to previous activity which i don't want.</p>

答:
You can clear all the back stack doing this. </p>

```<code>@Override
public void onBackPressed() {
    finishAffinity();
}
</code>```

Title: Exit android app on back pressed

Body:
You can clear all the back stack doing this.

@Override
public void onBackPressed() {
    finishAffinity();
}


问:
Substring of string matching regex in a bash shell
In a bash shell, I want to take the take a given string that matches a regex, and then take the part of the string.

For example, given https://github.com/PatrickConway/repo-name.git, I want to extract the repo-name substring.

How would I go about doing this? Should I do this all in a shell script, or is there another way to approach this?

答:
You can use the =~ matching operator inside a [[ ... ]] condition:

```<code>#!/bin/bash
url=https://github.com/PatrickConway/repo-name.git
if [[ $url =~ ([^/]*)\.git ]] ; then
    echo "${BASH_REMATCH[1]}"
fi
</code>```

Each part enclosed in parentheses creates a capture group, the corresponding matching substring can be found in the same position in the BASH_REMATCH array.

[...] defines a character class

[/] matches a character class consisting of a single character, a slash

^ negates a character class, [^/] matches anything but a slash

* means "zero or more times"

\. matches a dot, as . without a backslash matches any character

So, it reads: remember a substring of non-slashes, followed by a dot and "git".

Or maybe a simple parameter expansion:

```<code>#!/bin/bash
url=https://github.com/PatrickConway/repo-name.git
url_without_extension=${url%.git}
name=${url_without_extension##*/}
echo $name
</code>```

% removes from the right, # removes from the left, doubling the symbol makes the matching greedy, i.e. wildcards try to match as much as possible.

Body:
You can use the =~ matching operator inside a [[ ... ]] condition:

#!/bin/bash
url=https://github.com/PatrickConway/repo-name.git
if [[ $url =~ ([^/]*)\.git ]] ; then
    echo "${BASH_REMATCH[1]}"
fi

Each part enclosed in parentheses creates a capture group, the corresponding matching substring can be found in the same position in the BASH_REMATCH array.

[...] defines a character class

[/] matches a character class consisting of a single character, a slash

^ negates a character class, [^/] matches anything but a slash

* means "zero or more times"

\. matches a dot, as . without a backslash matches any character

So, it reads: remember a substring of non-slashes, followed by a dot and "git".

Or maybe a simple parameter expansion:

#!/bin/bash
url=https://github.com/PatrickConway/repo-name.git
url_without_extension=${url%.git}
name=${url_without_extension##*/}
echo $name

% removes from the right, # removes from the left, doubling the symbol makes the matching greedy, i.e. wildcards try to match as much as possible.