问:
Changing the background color of a custom UIButton?
I've been setting the backgroundColor of buttons by doing self.layer.backgroundColor = someColor.

However, this doesn't seem to work with a custom class? I have this general class that I use:

```<code>class DarkButton: BaseButton {
    override func layoutSubviews() {
        super.layoutSubviews()

        self.layer.cornerRadius = 5
        self.setTitleColor(UIColor.black, for: .normal)
        self.setTitleColor(UIColor.lightGray, for: .highlighted)
        self.layer.backgroundColor = UIColor(red:0.77, green:0.77,
                                             blue:0.77, alpha: 1.0).cgColor
        self.clipsToBounds = false
    }

}
</code>```

the self.layer.backgroundColor works just fine. Now if I extend it, like so:

```<code>class SuperCoolButton: DarkButton {

    required init() {
        super.init()
        self.setUp()
    }

    required init(spacing: Spacing) {
        super.init(spacing: spacing)
        self.setUp()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setUp()
    }

    func setUp() {
        self.generateImage()
        self.changeBGColor()
    }

    func generateImage() {
        let image = UIImage(named: "logoSmall") as UIImage?
        self.setImage(image, for: .normal)
        self.imageEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)
        self.imageView?.contentMode = .scaleAspectFit
    }

    func changeBGColor() {
        self.layer.backgroundColor = UIColor.red.cgColor
    }

}
</code>```

the backgroundColor stays that of the DarkButton backgroundColor, however setting the image does indeed work >_>

答:
Do not call your setUp() method in init instead of this call it in layoutSubviews

```<code>class SuperCoolButton: DarkButton {

    required init() {
        super.init()
        //self.setUp()
    }

    required init(spacing: Spacing) {
        super.init(spacing: spacing)
        //self.setUp()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        //self.setUp()
    }

    func setUp() {
        self.generateImage()
        self.changeBGColor()
    }

    func generateImage() {
        let image = UIImage(named: "logoSmall") as UIImage?
        self.setImage(image, for: .normal)
        self.imageEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)
        self.imageView?.contentMode = .scaleAspectFit
    }

    func changeBGColor() {
        self.layer.backgroundColor = UIColor.red.cgColor
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        setUp()
    }
}
</code>```

Body:
I've been setting the backgroundColor of buttons by doing self.layer.backgroundColor = someColor.

However, this doesn't seem to work with a custom class? I have this general class that I use:

class DarkButton: BaseButton {
    override func layoutSubviews() {
        super.layoutSubviews()

        self.layer.cornerRadius = 5
        self.setTitleColor(UIColor.black, for: .normal)
        self.setTitleColor(UIColor.lightGray, for: .highlighted)
        self.layer.backgroundColor = UIColor(red:0.77, green:0.77,
                                             blue:0.77, alpha: 1.0).cgColor
        self.clipsToBounds = false
    }

}

the self.layer.backgroundColor works just fine. Now if I extend it, like so:

class SuperCoolButton: DarkButton {

    required init() {
        super.init()
        self.setUp()
    }

    required init(spacing: Spacing) {
        super.init(spacing: spacing)
        self.setUp()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setUp()
    }

    func setUp() {
        self.generateImage()
        self.changeBGColor()
    }

    func generateImage() {
        let image = UIImage(named: "logoSmall") as UIImage?
        self.setImage(image, for: .normal)
        self.imageEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)
        self.imageView?.contentMode = .scaleAspectFit
    }

    func changeBGColor() {
        self.layer.backgroundColor = UIColor.red.cgColor
    }

}

the backgroundColor stays that of the DarkButton backgroundColor, however setting the image does indeed work >_>

Body:
Do not call your setUp() method in init instead of this call it in layoutSubviews

class SuperCoolButton: DarkButton {

    required init() {
        super.init()
        //self.setUp()
    }

    required init(spacing: Spacing) {
        super.init(spacing: spacing)
        //self.setUp()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        //self.setUp()
    }

    func setUp() {
        self.generateImage()
        self.changeBGColor()
    }

    func generateImage() {
        let image = UIImage(named: "logoSmall") as UIImage?
        self.setImage(image, for: .normal)
        self.imageEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0)
        self.imageView?.contentMode = .scaleAspectFit
    }

    func changeBGColor() {
        self.layer.backgroundColor = UIColor.red.cgColor
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        setUp()
    }
}


来源: stackexchange

问:
Exception: java.lang.RuntimeException: Unable to instantiate application com.salesforce.androidsdk.phonegap.app.HybridApp
I developed a hybrid mobile app integrating SalesForce Mobile SDK with Ionic using Brett Nelson's set of blog posts -

After following the set of instructions in this post -
https://wipdeveloper.com/2017/06/27/saleforce-mobile-sdk-ionic-setup-mobile-sdk/
and setting up the org and running the app in Android Studio -> emulator, the app opened up alright.

After following these set of instructions -
https://wipdeveloper.com/author/brettmn/page/6/

wherein I integrated (basically copy pasted) - package.json elements, resources etc. - from the CLI generated Ionic app to the SalesForce SDK project in Step 1, I cannot get to run the project in emulator.

While running, the LogCat emits the following information:

0-4310/com.wipdeveloper.contacts E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.wipdeveloper.contacts, PID: 4310
                                                                         java.lang.RuntimeException: Unable to instantiate application com.salesforce.androidsdk.phonegap.app.HybridApp: java.lang.ClassNotFoundException: Didn't find class "com.salesforce.androidsdk.phonegap.app.HybridApp" on path: DexPathList[[zip file "/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/base.apk", zip file "/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/split_lib_dependencies_apk.apk", zip file "/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/split_lib_slice_0_apk.apk", zip file "/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/split_lib_slice_1_apk.apk", zip file "/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/split_lib_slice_2_apk.apk", zip file "/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/split_lib_slice_3_apk.apk", zip file "/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/split_lib_slice_4_apk.apk", zip file "/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/split_lib_slice_5_apk.apk", zip file "/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/split_lib_slice_6_apk.apk", zip file "/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/split_lib_slice_7_apk.apk", zip file "/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/split_lib_slice_8_apk.apk", zip file "/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.wipdeveloper.contacts-gVdyqj5Na6koBXGU6VuxfA==/lib/x86, /system/lib, /vendor/lib]]
                                                                             at android.app.LoadedApk.makeApplication(LoadedApk.java:989)
                                                                             at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5715)
                                                                             at android.app.ActivityThread.-wrap1(Unknown Source:0)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:106)

The manifest file looks like this ->

The project structure is as below ->

What is the configuration that is missing? Or incorrect?

Note: This question here seems to have a similar problem, but no resolution:
Unable to instantiate application com.salesforce.androidsdk.phonegap.app.HybridApp: java.lang.ClassNotFoundException:

答:
After step 2 in your question, you may have to remove and then re-add the platform you are targeting.

For iOS

```<code>ionic cordova platform remove ios
ionic cordova platform add ios@4.4.0
</code>```

Or for Android

```<code>ionic cordova platform remove android
ionic cordova platform add android@6.2.3
</code>```

If you do that and still have problems try removing and re-adding the salesforce mobile sdk.

```<code>cordova plugin remove com.salesforce
cordova plugin add https://github.com/forcedotcom/SalesforceMobileSDK-CordovaPlugin --force
</code>```

ContentLicense: CC BY-SA 3.0

Body:
After step 2 in your question, you may have to remove and then re-add the platform you are targeting.

For iOS

ionic cordova platform remove ios
ionic cordova platform add ios@4.4.0

Or for Android

ionic cordova platform remove android
ionic cordova platform add android@6.2.3

If you do that and still have problems try removing and re-adding the salesforce mobile sdk.

cordova plugin remove com.salesforce
cordova plugin add https://github.com/forcedotcom/SalesforceMobileSDK-CordovaPlugin --force


问:
jquery popup on load
i have used fancybox for popup effects.
please see this link
http://www.sudhakargolakaram.co.in/f...ncy/popup.html

here when the link is clicked a popup window appears with the effect created by fancybox

what i need is i want this popup window to appear by default when the page loads

how do i specify that i want this content in a popup window with the effect when the page loads

答:
Could you post your code? That link brings up a page with nothing on it, and I'm not familiar with fancbox, but I'd imagine you can do it pretty easily, with something like:

```<code>$(document).ready(function() {
    //execute popup
    });
</code>```

If you say the event is triggered when you click something, you could just use .trigger("click");

ContentLicense: CC BY-SA 2.5

Title: jquery popup on load

Body:
Could you post your code? That link brings up a page with nothing on it, and I'm not familiar with fancbox, but I'd imagine you can do it pretty easily, with something like:

$(document).ready(function() {
    //execute popup
    });

If you say the event is triggered when you click something, you could just use .trigger("click");


问:
How to check multiple dropdowns has got value or not using jquery?
I want to check if all those fields have got value or not if not then show an alert.

i have tried this :

```<code><script>
        $(document).ready(function(){
            var session = $('#getsessionid').val();
            var class_level = $('#getprogramLevelid').val();
            var class_student = $('#getprogramid').val();
            var medium = $('#getmediumid').val();
            var group = $('#getgroupid').val();
            var shift = $('#getshiftid').val();
            var section = $('#getsectionid').val();
            if((session && class_level && class_student && medium && group && shift && section) ==""){
                alert("Please Insert Values");
            }

        });
    </script>
</code>```

答:
A small demo to help you out. Hope this helps:

$('select').on('change', function() {
  var selected = $('option[value!="0"]:selected');
  if (selected.length == $('select').length) {
    console.log('All dropdowns have been selected.');
  } else {
    console.log('Some dropdowns have not yet selected.');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toggler_container">
  <select name="select" id="aaa">
        <option value="0">---</option>
        <option value="1">AAA</option>
        <option value="2">BBB</option>
    </select>
  <select name="select" id="bbb">
        <option value="0">---</option>
        <option value="1">AAA</option>
        <option value="2">BBB</option>
    </select>
  <select name="select" id="ccc">
        <option value="0">---</option>
        <option value="1">AAA</option>
        <option value="2">BBB</option>
    </select>
</div></code>```

Body:
A small demo to help you out. Hope this helps:

$('select').on('change', function() {
  var selected = $('option[value!="0"]:selected');
  if (selected.length == $('select').length) {
    console.log('All dropdowns have been selected.');
  } else {
    console.log('Some dropdowns have not yet selected.');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toggler_container">
  <select name="select" id="aaa">
        <option value="0">---</option>
        <option value="1">AAA</option>
        <option value="2">BBB</option>
    </select>
  <select name="select" id="bbb">
        <option value="0">---</option>
        <option value="1">AAA</option>
        <option value="2">BBB</option>
    </select>
  <select name="select" id="ccc">
        <option value="0">---</option>
        <option value="1">AAA</option>
        <option value="2">BBB</option>
    </select>
</div>


问:
Diff and patch didn't works as expected
Everytime when i try copy a file out from a folder, do some change and patch it, it always trys to patch into the new file. Why?</p>

```<code>$ mkdir test
$ vim test/1 (Write something)
$ cp test/1 ./1
$ vim 1 (Do some change)
$ diff -Naur test/1 1 > patch
$ patch -p0 < patch
   pathing file 1
   Reversed (or previously applied) patch detected!  Assume -R? [n]
</code>```

答:
Read carefully patch(1) and diff(1).

patch works (by default) in the current working directory. But you invoke diff on (a patch from) some other directory. Try with diff -Naur 1 test/1 > patch, it could work better. Order of arguments to diff matters a big lot !

Title: Diff and patch didn't works as expected

Body:
Everytime when i try copy a file out from a folder, do some change and patch it, it always trys to patch into the new file. Why?

$ mkdir test
$ vim test/1 (Write something)
$ cp test/1 ./1
$ vim 1 (Do some change)
$ diff -Naur test/1 1 > patch
$ patch -p0 < patch
   pathing file 1
   Reversed (or previously applied) patch detected!  Assume -R? [n]


答:
This is happening because layoutSubviews() implemented in the super class(DarkButton) gets called after setUp method of DarkButton. You need to override layoutSubviews in your class SuperCoolButton and call setUp there instead of at its init method.

```<code>override func layoutSubviews() {
        super.layoutSubviews()
        setUp()
}
</code>```

EDIT:
I think you should move the code which you have written inside [layoutSubviews][1] of DarkButton class.

layoutSubviews method gets called multiple times and only the code related to the layout of the view should be there.

Subclasses can override this method as needed to perform more precise
  layout of their subviews. You should override this method only if the
  autoresizing and constraint-based behaviors of the subviews do not
  offer the behavior you want.

The ideal place to change layer's corner radius and setTitleColor or background color is either at init of the custom view or at awakeFromNib:(only, if the view is always going to be designed in nib).

Because you want to change the backgroud color of button at some later time. You can simply call your changeBgColor method on SuperCoolButton. Earlier it was not working, because layoutSubviews must be setting the background color back to the default.

Title: Changing the background color of a custom UIButton?

Body:
This is happening because layoutSubviews() implemented in the super class(DarkButton) gets called after setUp method of DarkButton. You need to override layoutSubviews in your class SuperCoolButton and call setUp there instead of at its init method.

override func layoutSubviews() {
        super.layoutSubviews()
        setUp()
}

EDIT:
I think you should move the code which you have written inside [layoutSubviews][1] of DarkButton class.

layoutSubviews method gets called multiple times and only the code related to the layout of the view should be there.

Subclasses can override this method as needed to perform more precise
  layout of their subviews. You should override this method only if the
  autoresizing and constraint-based behaviors of the subviews do not
  offer the behavior you want.

The ideal place to change layer's corner radius and setTitleColor or background color is either at init of the custom view or at awakeFromNib:(only, if the view is always going to be designed in nib).

Because you want to change the backgroud color of button at some later time. You can simply call your changeBgColor method on SuperCoolButton. Earlier it was not working, because layoutSubviews must be setting the background color back to the default.


问:
How to fix unwanted new line in java?
I am trying to figure why my code is creating a new line every time a return method called is within a for-loop. The if statement within the main for-loop checks every Student Object inside the array list named list. After it is done comparing Student i to Student j (Student j being the second for-loop). Once Student i have found the best match, it is supposed to print out a statement saying either he/she has matched with someone.

Here is what it is supposed to return:

```<code>Abey matches with Melissa with score 60
John matches with Jeff with score 100
Craig has no matches.
</code>```

Instead, it returns this:

```<code>Abey matches with
Melissa with score 60

John matches with
Jeff with score 100

Craig has no matches.
</code>```

Here is the code:

```<code>    for (int i = 0; i < list.size(); i++) {
    int maxScore = 0;
    int currentScore = 0;
    int bestMatchScore = 0;
    int bestMatchStudent = 0;
    if (!list.get(i).isMatched()) {
        for (int j = i; j < list.size(); j++) {
            if (!list.get(j).isMatched()) {
                if (j != i) {
                currentScore = list.get(i).compare(list.get(j));
                if (currentScore > maxScore) {
                    maxScore = currentScore;
                    bestMatchStudent = j;
                    bestMatchScore = maxScore;
                }
                }
            }
        }
            if(bestMatchScore == 0) {
                System.out.println(list.get(i).getName() + " has no matches.");
                }
            else {
                list.get(i).setMatched(list.get(bestMatchStudent));

                System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent).getName() + " with score " + maxScore);
            }
        }
    }
</code>```

If I were to remove all of the getName() inside the if-else statement, I get an output that is sort of what I desire:

```<code>Student@6d3552ed matches with Student@47d77d9e with score 60
Student@147834eb matches with Student@5fda3acc with score 100
Student@704a583d has no matches.
</code>```

I suspect that it has to do something with calling the getName method. All it is is an accessor method...

Here is all the code to reproduce the problem:

Student Class

```<code>public class Student {
    private String name;
    private char gender;
    private Date birthdate;
    private Preference pref;
    private boolean matched;

public Student(String name, char gender, Date birthdate, Preference pref) {
    this.name = name;
    this.gender = gender;
    this.birthdate = birthdate;
    this.pref = pref;
}

public String getName() {
    return name;
}

public char getGender() {
    return gender;
}

public Date getBirthdate() {
    return birthdate;
}

public Preference getPref() {
    return pref;
}

public boolean isMatched() {
    return matched;
}

public void setMatched() {
    this.matched = true;
}

public void setMatched(Student roommate) {
    setMatched();
    roommate.setMatched();
}

public int compare(Student st) {
    if (st.getGender() != gender)
        return 0;
    return Math.abs((40 - pref.compare(st.getPref())) + (60 - birthdate.compare(st.getBirthdate())));
}

}
</code>```

Match Class

```<code>import java.io.*;
import java.util.Scanner;
import java.util.*;
public class Match {

public static void main(String[] args) throws FileNotFoundException {
    //Student[] fullRoster = new Student[5]; converted to ArrayList
    ArrayList<Student> list = new ArrayList<Student>();
    String fileName = "Students.txt";
    Scanner input = new Scanner(new FileReader(fileName));
    input.useDelimiter("[\t\r-]");
    //int studentIndex = 0; converted to ArrayList
    while(input.hasNext()) {
        String name = input.next();
        //System.out.println(name);
        char gender = input.next().charAt(0);
        //System.out.println(gender);
        int month = Integer.parseInt(input.next());
        //System.out.println(month);
        int day = Integer.parseInt(input.next());
        //System.out.println(day);
        int year = Integer.parseInt(input.next());
        //System.out.println(year);
        Date birthday = new Date(year, month, day);
        //System.out.println(birthday); //Printed out birthday
        int pref1 = Integer.parseInt(input.next());
        //System.out.println(pref1);
        int pref2 = Integer.parseInt(input.next());
        //System.out.println(pref2);
        int pref3 = Integer.parseInt(input.next());
        //System.out.println(pref3);
        int pref4 = Integer.parseInt(input.next());
        //System.out.println(pref4);
        Preference pref = new Preference(pref1, pref2, pref3, pref4);
        //System.out.println(pref); //Printed out pref
        //fullRoster[studentIndex] = new Student(name, gender, birthday, pref); converted to ArrayList
        list.add(new Student(name, gender, birthday, pref));
        //studentIndex++; converted to ArrayList
    }

    input.close();

    for (int i = 0; i < list.size(); i++) {
    int maxScore = 0;
    int currentScore = 0;
    int bestMatchScore = 0;
    int bestMatchStudent = 0;
    if (!list.get(i).isMatched()) {
        for (int j = i; j < list.size(); j++) {
            if (!list.get(j).isMatched()) {
                if (j != i) {
                currentScore = list.get(i).compare(list.get(j));
                if (currentScore > maxScore) {
                    maxScore = currentScore;
                    bestMatchStudent = j;
                    bestMatchScore = maxScore;
                }
                }
            }
        }
            if(bestMatchScore == 0) {
                System.out.println(list.get(i) + " has no matches.");
                }
            else {
                list.get(i).setMatched(list.get(bestMatchStudent));

                System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent) + " with score " + maxScore);
            }
        }
    }
}
}
</code>```

Preference Class

```<code>public class Preference {
private int quietTime, music, reading, chatting;

public Preference(int quietTime, int music, int reading, int chatting) {
    this.quietTime = quietTime;
    this.music = music;
    this.reading = reading;
    this.chatting = chatting;
}

public int getQuietTime() {
    return quietTime;
}

public int getMusic() {
    return music;
}

public int getReading() {
    return reading;
}

public int getChatting() {
    return chatting;
}

public int compare(Preference pref) {
    int difference = 0;
    difference += Math.abs(pref.getQuietTime() - this.getQuietTime());
    difference += Math.abs(pref.getMusic() - this.getMusic());
    difference += Math.abs(pref.getReading() - this.getReading());
    difference += Math.abs(pref.getChatting() - this.getChatting());
    return difference;
}

}
</code>```

Date Class

```<code>public class Date {
int year, month, day;

public Date(int year, int month, int day) {
    this.year = year;
    this.month = month;
    this.day = day;
}

public int getYear() {
    return year;
}

public int getMonth() {
    return month;
}

public int getDay() {
    return day;
}

public int compare(Date dt) {
    int yearsDifferenceInDays = (Math.abs(year - dt.getYear())) * 365;
    int daysDifference = Math.abs(dt.dayOfYear() - this.dayOfYear());
    int totalDifference = Math.abs(yearsDifferenceInDays - daysDifference);
    int monthsDifference = totalDifference / 30;
    if(monthsDifference > 60)
        return 60;
    return monthsDifference;
}

public int dayOfYear() {
    int totalDays = 0;
    switch (month) {
    case 12: totalDays += 30;
    case 11: totalDays += 31;
    case 10: totalDays += 30;
    case 9 : totalDays += 31;
    case 8 : totalDays += 31;
    case 7 : totalDays += 30;
    case 6 : totalDays += 31;
    case 5 : totalDays += 30;
    case 4 : totalDays += 31;
    case 3 : totalDays += 28;
    case 2 : totalDays += 31;
    }
    totalDays += day;
    return totalDays;
    }
}
</code>```

Match Class

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

public class Match {

public static void main(String[] args) throws FileNotFoundException {
    //Student[] fullRoster = new Student[5]; converted to ArrayList
    ArrayList<Student> list = new ArrayList<Student>();
    String fileName = "Students.txt";
    Scanner input = new Scanner(new FileReader(fileName));
    input.useDelimiter("[\t\r-]");
    //int studentIndex = 0; converted to ArrayList
    while(input.hasNext()) {
        String name = input.next();
        //System.out.println(name);
        char gender = input.next().charAt(0);
        //System.out.println(gender);
        int month = Integer.parseInt(input.next());
        //System.out.println(month);
        int day = Integer.parseInt(input.next());
        //System.out.println(day);
        int year = Integer.parseInt(input.next());
        //System.out.println(year);
        Date birthday = new Date(year, month, day);
        //System.out.println(birthday); //Printed out birthday
        int pref1 = Integer.parseInt(input.next());
        //System.out.println(pref1);
        int pref2 = Integer.parseInt(input.next());
        //System.out.println(pref2);
        int pref3 = Integer.parseInt(input.next());
        //System.out.println(pref3);
        int pref4 = Integer.parseInt(input.next());
        //System.out.println(pref4);
        Preference pref = new Preference(pref1, pref2, pref3, pref4);
        //System.out.println(pref); //Printed out pref
        //fullRoster[studentIndex] = new Student(name, gender, birthday, pref); converted to ArrayList
        list.add(new Student(name, gender, birthday, pref));
        //studentIndex++; converted to ArrayList
    }

    input.close();

    for (int i = 0; i < list.size(); i++) {
    int maxScore = 0;
    int currentScore = 0;
    int bestMatchScore = 0;
    int bestMatchStudent = 0;
    if (!list.get(i).isMatched()) {
        for (int j = i; j < list.size(); j++) {
            if (!list.get(j).isMatched()) {
                if (j != i) {
                currentScore = list.get(i).compare(list.get(j));
                if (currentScore > maxScore) {
                    maxScore = currentScore;
                    bestMatchStudent = j;
                    bestMatchScore = maxScore;
                }
                }
            }
        }
            if(bestMatchScore == 0) {
                System.out.println(list.get(i) + " has no matches.");
                }
            else {
                list.get(i).setMatched(list.get(bestMatchStudent));

                System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent) + " with score " + maxScore);
            }
        }
    }
}
}
</code>```

Students.txt

```<code>Abey    F   5-5-1996    0   0   0   0
John    M   5-5-1997    10  10  10  10
Melissa F   5-5-1996    10  10  10  10
Craig   M   5-5-1998    5   5   5   5
Jeff    M   5-5-1997    10  10  10  10
</code>```

答:
I can give a solution to resolve this problem like:
 without printing whole at a time like:

```<code>System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent).getName() + " with score " + maxScore);
</code>```

do it as follows:

```<code>String name  = list.get(i).getName().trim();
String bestMachStudentName = list.get(bestMatchStudent).getName().trim();
if(!name .equals("") &&  !bestMachStudentName.equals("") ){
System.out.println( name  + " matches with " + bestMachStudentName  + " with score " + maxScore);
}
else{
// other stuff......
}
</code>```

I don't know why this println() function is behaving like that it may be a possible problem in getting value from a list.

I hope it will work fine.

Title: How to fix unwanted new line in java?

Body:
I am trying to figure why my code is creating a new line every time a return method called is within a for-loop. The if statement within the main for-loop checks every Student Object inside the array list named list. After it is done comparing Student i to Student j (Student j being the second for-loop). Once Student i have found the best match, it is supposed to print out a statement saying either he/she has matched with someone.

Here is what it is supposed to return:

Abey matches with Melissa with score 60
John matches with Jeff with score 100
Craig has no matches.

Instead, it returns this:

Abey matches with
Melissa with score 60

John matches with
Jeff with score 100

Craig has no matches.

Here is the code:

    for (int i = 0; i < list.size(); i++) {
    int maxScore = 0;
    int currentScore = 0;
    int bestMatchScore = 0;
    int bestMatchStudent = 0;
    if (!list.get(i).isMatched()) {
        for (int j = i; j < list.size(); j++) {
            if (!list.get(j).isMatched()) {
                if (j != i) {
                currentScore = list.get(i).compare(list.get(j));
                if (currentScore > maxScore) {
                    maxScore = currentScore;
                    bestMatchStudent = j;
                    bestMatchScore = maxScore;
                }
                }
            }
        }
            if(bestMatchScore == 0) {
                System.out.println(list.get(i).getName() + " has no matches.");
                }
            else {
                list.get(i).setMatched(list.get(bestMatchStudent));

                System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent).getName() + " with score " + maxScore);
            }
        }
    }

If I were to remove all of the getName() inside the if-else statement, I get an output that is sort of what I desire:

Student@6d3552ed matches with Student@47d77d9e with score 60
Student@147834eb matches with Student@5fda3acc with score 100
Student@704a583d has no matches.

I suspect that it has to do something with calling the getName method. All it is is an accessor method...

Here is all the code to reproduce the problem:

Student Class

public class Student {
    private String name;
    private char gender;
    private Date birthdate;
    private Preference pref;
    private boolean matched;

public Student(String name, char gender, Date birthdate, Preference pref) {
    this.name = name;
    this.gender = gender;
    this.birthdate = birthdate;
    this.pref = pref;
}

public String getName() {
    return name;
}

public char getGender() {
    return gender;
}

public Date getBirthdate() {
    return birthdate;
}

public Preference getPref() {
    return pref;
}

public boolean isMatched() {
    return matched;
}

public void setMatched() {
    this.matched = true;
}

public void setMatched(Student roommate) {
    setMatched();
    roommate.setMatched();
}

public int compare(Student st) {
    if (st.getGender() != gender)
        return 0;
    return Math.abs((40 - pref.compare(st.getPref())) + (60 - birthdate.compare(st.getBirthdate())));
}

}

Match Class

import java.io.*;
import java.util.Scanner;
import java.util.*;
public class Match {

public static void main(String[] args) throws FileNotFoundException {
    //Student[] fullRoster = new Student[5]; converted to ArrayList
    ArrayList<Student> list = new ArrayList<Student>();
    String fileName = "Students.txt";
    Scanner input = new Scanner(new FileReader(fileName));
    input.useDelimiter("[\t\r-]");
    //int studentIndex = 0; converted to ArrayList
    while(input.hasNext()) {
        String name = input.next();
        //System.out.println(name);
        char gender = input.next().charAt(0);
        //System.out.println(gender);
        int month = Integer.parseInt(input.next());
        //System.out.println(month);
        int day = Integer.parseInt(input.next());
        //System.out.println(day);
        int year = Integer.parseInt(input.next());
        //System.out.println(year);
        Date birthday = new Date(year, month, day);
        //System.out.println(birthday); //Printed out birthday
        int pref1 = Integer.parseInt(input.next());
        //System.out.println(pref1);
        int pref2 = Integer.parseInt(input.next());
        //System.out.println(pref2);
        int pref3 = Integer.parseInt(input.next());
        //System.out.println(pref3);
        int pref4 = Integer.parseInt(input.next());
        //System.out.println(pref4);
        Preference pref = new Preference(pref1, pref2, pref3, pref4);
        //System.out.println(pref); //Printed out pref
        //fullRoster[studentIndex] = new Student(name, gender, birthday, pref); converted to ArrayList
        list.add(new Student(name, gender, birthday, pref));
        //studentIndex++; converted to ArrayList
    }

    input.close();

    for (int i = 0; i < list.size(); i++) {
    int maxScore = 0;
    int currentScore = 0;
    int bestMatchScore = 0;
    int bestMatchStudent = 0;
    if (!list.get(i).isMatched()) {
        for (int j = i; j < list.size(); j++) {
            if (!list.get(j).isMatched()) {
                if (j != i) {
                currentScore = list.get(i).compare(list.get(j));
                if (currentScore > maxScore) {
                    maxScore = currentScore;
                    bestMatchStudent = j;
                    bestMatchScore = maxScore;
                }
                }
            }
        }
            if(bestMatchScore == 0) {
                System.out.println(list.get(i) + " has no matches.");
                }
            else {
                list.get(i).setMatched(list.get(bestMatchStudent));

                System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent) + " with score " + maxScore);
            }
        }
    }
}
}

Preference Class

public class Preference {
private int quietTime, music, reading, chatting;

public Preference(int quietTime, int music, int reading, int chatting) {
    this.quietTime = quietTime;
    this.music = music;
    this.reading = reading;
    this.chatting = chatting;
}

public int getQuietTime() {
    return quietTime;
}

public int getMusic() {
    return music;
}

public int getReading() {
    return reading;
}

public int getChatting() {
    return chatting;
}

public int compare(Preference pref) {
    int difference = 0;
    difference += Math.abs(pref.getQuietTime() - this.getQuietTime());
    difference += Math.abs(pref.getMusic() - this.getMusic());
    difference += Math.abs(pref.getReading() - this.getReading());
    difference += Math.abs(pref.getChatting() - this.getChatting());
    return difference;
}

}

Date Class

public class Date {
int year, month, day;

public Date(int year, int month, int day) {
    this.year = year;
    this.month = month;
    this.day = day;
}

public int getYear() {
    return year;
}

public int getMonth() {
    return month;
}

public int getDay() {
    return day;
}

public int compare(Date dt) {
    int yearsDifferenceInDays = (Math.abs(year - dt.getYear())) * 365;
    int daysDifference = Math.abs(dt.dayOfYear() - this.dayOfYear());
    int totalDifference = Math.abs(yearsDifferenceInDays - daysDifference);
    int monthsDifference = totalDifference / 30;
    if(monthsDifference > 60)
        return 60;
    return monthsDifference;
}

public int dayOfYear() {
    int totalDays = 0;
    switch (month) {
    case 12: totalDays += 30;
    case 11: totalDays += 31;
    case 10: totalDays += 30;
    case 9 : totalDays += 31;
    case 8 : totalDays += 31;
    case 7 : totalDays += 30;
    case 6 : totalDays += 31;
    case 5 : totalDays += 30;
    case 4 : totalDays += 31;
    case 3 : totalDays += 28;
    case 2 : totalDays += 31;
    }
    totalDays += day;
    return totalDays;
    }
}

Match Class

import java.io.*;
import java.util.Scanner;
import java.util.*;

public class Match {

public static void main(String[] args) throws FileNotFoundException {
    //Student[] fullRoster = new Student[5]; converted to ArrayList
    ArrayList<Student> list = new ArrayList<Student>();
    String fileName = "Students.txt";
    Scanner input = new Scanner(new FileReader(fileName));
    input.useDelimiter("[\t\r-]");
    //int studentIndex = 0; converted to ArrayList
    while(input.hasNext()) {
        String name = input.next();
        //System.out.println(name);
        char gender = input.next().charAt(0);
        //System.out.println(gender);
        int month = Integer.parseInt(input.next());
        //System.out.println(month);
        int day = Integer.parseInt(input.next());
        //System.out.println(day);
        int year = Integer.parseInt(input.next());
        //System.out.println(year);
        Date birthday = new Date(year, month, day);
        //System.out.println(birthday); //Printed out birthday
        int pref1 = Integer.parseInt(input.next());
        //System.out.println(pref1);
        int pref2 = Integer.parseInt(input.next());
        //System.out.println(pref2);
        int pref3 = Integer.parseInt(input.next());
        //System.out.println(pref3);
        int pref4 = Integer.parseInt(input.next());
        //System.out.println(pref4);
        Preference pref = new Preference(pref1, pref2, pref3, pref4);
        //System.out.println(pref); //Printed out pref
        //fullRoster[studentIndex] = new Student(name, gender, birthday, pref); converted to ArrayList
        list.add(new Student(name, gender, birthday, pref));
        //studentIndex++; converted to ArrayList
    }

    input.close();

    for (int i = 0; i < list.size(); i++) {
    int maxScore = 0;
    int currentScore = 0;
    int bestMatchScore = 0;
    int bestMatchStudent = 0;
    if (!list.get(i).isMatched()) {
        for (int j = i; j < list.size(); j++) {
            if (!list.get(j).isMatched()) {
                if (j != i) {
                currentScore = list.get(i).compare(list.get(j));
                if (currentScore > maxScore) {
                    maxScore = currentScore;
                    bestMatchStudent = j;
                    bestMatchScore = maxScore;
                }
                }
            }
        }
            if(bestMatchScore == 0) {
                System.out.println(list.get(i) + " has no matches.");
                }
            else {
                list.get(i).setMatched(list.get(bestMatchStudent));

                System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent) + " with score " + maxScore);
            }
        }
    }
}
}

Students.txt

Abey    F   5-5-1996    0   0   0   0
John    M   5-5-1997    10  10  10  10
Melissa F   5-5-1996    10  10  10  10
Craig   M   5-5-1998    5   5   5   5
Jeff    M   5-5-1997    10  10  10  10

Body:
I can give a solution to resolve this problem like:
 without printing whole at a time like:

System.out.println(list.get(i).getName() + " matches with " + list.get(bestMatchStudent).getName() + " with score " + maxScore);

do it as follows:

String name  = list.get(i).getName().trim();
String bestMachStudentName = list.get(bestMatchStudent).getName().trim();
if(!name .equals("") &&  !bestMachStudentName.equals("") ){
System.out.println( name  + " matches with " + bestMachStudentName  + " with score " + maxScore);
}
else{
// other stuff......
}

I don't know why this println() function is behaving like that it may be a possible problem in getting value from a list.

I hope it will work fine.


问:
How to open native GoogleMaps App & Waze App
I want to open directions driving mode in both GoogleMaps & Waze in native app. How to do it?

```<code>func showActionSheet(vc: UIViewController) {
    let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

    actionSheet.addAction(UIAlertAction(title: "Google Maps", style: .default, handler: { (alert:UIAlertAction!) -> Void in
        self.openGoogleMaps()
    }))

    actionSheet.addAction(UIAlertAction(title: "Waze", style: .default, handler: { (alert:UIAlertAction!) -> Void in
        self.openWaze()
    }))

    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    vc.present(actionSheet, animated: true, completion: nil)
}
</code>```

Currently I've implement 2 functions, but I would like to know how to open in native apps for both maps

```<code>    func openGoogleMaps() {
//Don't want open in URL, want to open in native googlemaps app
        }

   func openWaze() {
  //Don't want open in URL, want to open in native Waze app
}
</code>```

答:
First check Waze or Google map apps are available or not on user's phone.
After that, you can open Waze/Google app from your app with URL Scheeme.

```<code>func openGoogleMaps() {
   if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) {  //First check Google Mpas installed on User's phone or not.
           UIApplication.shared.openURL(URL(string: "comgooglemaps://?center=40.765819,-73.975866&zoom=14&views=traffic")!) //It will open native google maps app.
   } else {
           print("Can't use comgooglemaps://");
    }
}

func openWaze() {
  if (UIApplication.shared.canOpenURL(URL(string:"waze://")!)) {  //First check Waze Mpas installed on User's phone or not.
       UIApplication.shared.openURL(URL(string: "waze://")!) //It will open native wazw maps app.
   } else {
           print("Can't use waze://");
   }
}
</code>```

When compiling with iOS SDK 9.0 and later, you must update your application's property list file with the following to include Waze:

```<code><key>LSApplicationQueriesSchemes</key>
<array>
  <string>waze</string>
</array>
</code>```

Body:
I want to open directions driving mode in both GoogleMaps & Waze in native app. How to do it?

func showActionSheet(vc: UIViewController) {
    let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

    actionSheet.addAction(UIAlertAction(title: "Google Maps", style: .default, handler: { (alert:UIAlertAction!) -> Void in
        self.openGoogleMaps()
    }))

    actionSheet.addAction(UIAlertAction(title: "Waze", style: .default, handler: { (alert:UIAlertAction!) -> Void in
        self.openWaze()
    }))

    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    vc.present(actionSheet, animated: true, completion: nil)
}

Currently I've implement 2 functions, but I would like to know how to open in native apps for both maps

    func openGoogleMaps() {
//Don't want open in URL, want to open in native googlemaps app
        }

   func openWaze() {
  //Don't want open in URL, want to open in native Waze app
}

Body:
First check Waze or Google map apps are available or not on user's phone.
After that, you can open Waze/Google app from your app with URL Scheeme.

func openGoogleMaps() {
   if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) {  //First check Google Mpas installed on User's phone or not.
           UIApplication.shared.openURL(URL(string: "comgooglemaps://?center=40.765819,-73.975866&zoom=14&views=traffic")!) //It will open native google maps app.
   } else {
           print("Can't use comgooglemaps://");
    }
}

func openWaze() {
  if (UIApplication.shared.canOpenURL(URL(string:"waze://")!)) {  //First check Waze Mpas installed on User's phone or not.
       UIApplication.shared.openURL(URL(string: "waze://")!) //It will open native wazw maps app.
   } else {
           print("Can't use waze://");
   }
}

When compiling with iOS SDK 9.0 and later, you must update your application's property list file with the following to include Waze:

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>waze</string>
</array>


答:
jQuery has an inbuilt function that executes after page load

```<code>$(document).ready(function() {
   // call function that is invoked on link click
 });
</code>```

That might help you

Title: jquery popup on load

Body:
i have used fancybox for popup effects.
please see this link
http://www.sudhakargolakaram.co.in/f...ncy/popup.html

here when the link is clicked a popup window appears with the effect created by fancybox

what i need is i want this popup window to appear by default when the page loads

how do i specify that i want this content in a popup window with the effect when the page loads

Body:
jQuery has an inbuilt function that executes after page load

$(document).ready(function() {
   // call function that is invoked on link click
 });

That might help you


问:
How to add dot net version 4.0 in target framework of visual studio 2010?

In my visual studio 2010, target framework only include (2.0, 3.0 and 3.5).

Does not include for 4.0.

So, may I know how can I add dot net 4.0 to show in target framework.

I already install dot net version 4 in my pc.
But doesn't show in target framework.

Please advice me.

答:
Visual studio checks this folder for .net assembly references

```<code>C:\Program Files\Reference Assemblies\Microsoft\Framework\xxx
</code>```

If that folder is missing 4.0 for you, installing a new version of visual studio may create that folder for you. You could also try copying that folder from a different machine.

If that doesn't work, try the answers suggested here:

dotnet Framework 4 missing from visual studio 2010

EDIT: Source for the first suggestion - http://www.anujvarma.com/visual-studio-does-not-display-4-0-or-4-5-framework-option-for-target-framework/

Body:
Visual studio checks this folder for .net assembly references

C:\Program Files\Reference Assemblies\Microsoft\Framework\xxx

If that folder is missing 4.0 for you, installing a new version of visual studio may create that folder for you. You could also try copying that folder from a different machine.

If that doesn't work, try the answers suggested here:

dotnet Framework 4 missing from visual studio 2010

EDIT: Source for the first suggestion - http://www.anujvarma.com/visual-studio-does-not-display-4-0-or-4-5-framework-option-for-target-framework/


问:
close button overlap scrollbar (position:fixed)

I'd like to fixed position right of the div inside the scrollable div.

But the fixed div just overlaps the parent div's scrollbar!
How to fix it?

(must be fixed, only css)

```<code>div {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
    overflow-y:auto
}

div a {
    position:fixed;
    right:15px;
    top:15px;
    width:30px;
    height:30px;
    background-color:red;
    border-radius:100%
}
</code>```

答:
You just need to increase your right pixels little more to move the button. Here is the updated CSS for your reference.

div {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
    overflow-y:auto
}

div a {
    position:fixed;
    right:25px;
    top:15px;
    width:30px;
    height:30px;
    background-color:red;
    border-radius:100%
}```

Body:
I'd like to fixed position right of the div inside the scrollable div.

But the fixed div just overlaps the parent div's scrollbar!
How to fix it?

(must be fixed, only css)

div {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
    overflow-y:auto
}

div a {
    position:fixed;
    right:15px;
    top:15px;
    width:30px;
    height:30px;
    background-color:red;
    border-radius:100%
}


问:
Deployment Laravel 5.4 - DigitalOcean - Nginx LEMP (16.04)
i'm deployment my laravel project in digitalocean, actually i have this situation:

DNS RECORDS - GODADDY

digitalocean ip server 104.131.16.82

DNS RECORDS DIGITALOCEAN

SERVER BLOCK ENABLED

i enabled my default server block in "/etc/nginx/sites-available/default" and created link in "/etc/nginx/sites-enabled/default" like this:

```<code>server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /var/www/mysite-test.com/public;
        index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name localhost;
        return 301 $scheme://mysite-test.com$request_uri;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ /index.php?$query_string;
        # Uncomment to enable naxsi on this location
        # include /etc/nginx/naxsi.rules
    }
        location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php7-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        }
}
</code>```

i followed this tutorial to install: https://gist.github.com/naveenyagati/5deec8fc40a2faaff20c629362dddf39

Actually if i go to 104.131.16.82 download a file, i don't know why, it doesn't work well, maybe i have error in server block? or DNS records?
thank you for your help!

答:
If you have deployed using ONE CLICK APP INSTALL in Digital Ocean you have to edit the file named "digitalocean" in "/etc/nginx/site-available" directory not the "default" file for changes to take effect. If not the default LEMP landing page would be shown there.

Command to edit the main file,in digital ocean ONE CLICK APP INSTALL

sudo nano /etc/nginx/sites-available/digitalocean

Now replace the contents of the file with the following code

```<code>server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        root /var/www/laravel/public;
        index index.php index.html index.htm;

        # Make site accessible from http://localhost/
        server_name <Your Domain name / Public IP Address>;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ /index.php?$query_string;
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
        }
        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }
}
</code>```

Replace the server_name part with your
  server IP or domain name

Further reference could be found in the following gist that I have made
https://gist.github.com/naveenyagati/5deec8fc40a2faaff20c629362dddf39

Body:
i'm deployment my laravel project in digitalocean, actually i have this situation:

DNS RECORDS - GODADDY

digitalocean ip server 104.131.16.82

DNS RECORDS DIGITALOCEAN

SERVER BLOCK ENABLED

i enabled my default server block in "/etc/nginx/sites-available/default" and created link in "/etc/nginx/sites-enabled/default" like this:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /var/www/mysite-test.com/public;
        index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name localhost;
        return 301 $scheme://mysite-test.com$request_uri;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ /index.php?$query_string;
        # Uncomment to enable naxsi on this location
        # include /etc/nginx/naxsi.rules
    }
        location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php7-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        }
}

i followed this tutorial to install: https://gist.github.com/naveenyagati/5deec8fc40a2faaff20c629362dddf39

Actually if i go to 104.131.16.82 download a file, i don't know why, it doesn't work well, maybe i have error in server block? or DNS records?
thank you for your help!

Body:
If you have deployed using ONE CLICK APP INSTALL in Digital Ocean you have to edit the file named "digitalocean" in "/etc/nginx/site-available" directory not the "default" file for changes to take effect. If not the default LEMP landing page would be shown there.

Command to edit the main file,in digital ocean ONE CLICK APP INSTALL

sudo nano /etc/nginx/sites-available/digitalocean

Now replace the contents of the file with the following code

server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        root /var/www/laravel/public;
        index index.php index.html index.htm;

        # Make site accessible from http://localhost/
        server_name <Your Domain name / Public IP Address>;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ /index.php?$query_string;
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
        }
        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }
}

Replace the server_name part with your
  server IP or domain name

Further reference could be found in the following gist that I have made
https://gist.github.com/naveenyagati/5deec8fc40a2faaff20c629362dddf39


问:
how to create reusable "widget" markup across modules in an ASP.NET MVC 2.0 site?
Scenario:

platform: ASP.NET 4.0, MVC 2.0 (doesn't have to be MVC if it's not the right solution)

Create various widgets that inherit the same core markup:

```<code><div class="widget">
    <div class="hd-widget">
        <!-- dynamically inject code here for each actual widget -->

    </div>
    <div class="bd-widget">
        <!-- dynamically inject code here for each actual widget -->
    </div>
    <div class="ft-widget">
        <!-- dynamically inject code here for each actual widget -->
    </div>
</div>
</code>```

The above "simplified" example should be in some reusable control or masterpage.

The flow is something like this:

Controller -> View -> Partial View (1..n) -> widget markup

User instantiates an action which calls a controller. The controller tries to render a view that contains content + multiple widgets (left rail, right rail, etc). The Widgets all have their own individual partial views but each partial view should inherit or consume a base set of widget markup and have controller areas where to embed functionality.

Functionality in the head, body, and footer can either be plain text, HTML, or additional custom controls.

What is the best recommended approach?

答:
I would be thinking you would have a WidgetModel which contains a set of properties regarding the widget.

Eg.

```<code>public class WidgetModel
{
   public string ControllerName { get; set; }
   public string HeaderAction { get; set; }
   public string BodyAction { get; set; }
   public string FooterAction { get; set; }
}
</code>```

And you have a Widget View like

```<code><div class="widget">
   <div class="hd-widget">
      <%: Html.RenderAction(Model.HeaderAction, Model.ControllerName) %>
   </div>
   <div class="bd-widget">
      <%: Html.RenderAction(Model.BodyAction, Model.ControllerName) %>
   </div>
   <div class="ft-widget">
      <%: Html.RenderAction(Model.FooterAction, Model.ControllerName) %>
   </div>
</div>
</code>```

Of course you could add more to it if you wanted.

Body:
Scenario:

platform: ASP.NET 4.0, MVC 2.0 (doesn't have to be MVC if it's not the right solution)

Create various widgets that inherit the same core markup:

The above "simplified" example should be in some reusable control or masterpage.

The flow is something like this:

Controller -> View -> Partial View (1..n) -> widget markup

User instantiates an action which calls a controller. The controller tries to render a view that contains content + multiple widgets (left rail, right rail, etc). The Widgets all have their own individual partial views but each partial view should inherit or consume a base set of widget markup and have controller areas where to embed functionality.

Functionality in the head, body, and footer can either be plain text, HTML, or additional custom controls.

What is the best recommended approach?

Body:
I would be thinking you would have a WidgetModel which contains a set of properties regarding the widget.

Eg.

public class WidgetModel
{
   public string ControllerName { get; set; }
   public string HeaderAction { get; set; }
   public string BodyAction { get; set; }
   public string FooterAction { get; set; }
}

And you have a Widget View like

<div class="widget">
   <div class="hd-widget">
      <%: Html.RenderAction(Model.HeaderAction, Model.ControllerName) %>
   </div>
   <div class="bd-widget">
      <%: Html.RenderAction(Model.BodyAction, Model.ControllerName) %>
   </div>
   <div class="ft-widget">
      <%: Html.RenderAction(Model.FooterAction, Model.ControllerName) %>
   </div>
</div>

Of course you could add more to it if you wanted.


问:
Aligning a text and line parallel

There are 4 div's which has text and a line. The text will be coming from the service call and it may vary. The issue is that the line is not properly displayed it is of different length.The main condition is
1)All the line should end at the same point.
2)The line should be of 30px right from the margin and
3)The gap between the text and line should be 12px.

.about{
    display: inline-block;
}
hr{
  display:inline-block;
  width:200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

<div class="about">Chapter</div><hr/></div>
<div>
<div class="about">Learning Objectives</div><hr/></div>
<div>
<div class="about">Pages</div><hr/></div>
<div>
<div class="about">Sections</div><hr/></div></code>```

I tried with min,max-width but unable find a solution.Can anyone give a better solution?

答:
You can get this simply with display:flex; to parent.

Try this solution.

.align{
   display:flex;
}

.about{
   padding-right:12px;

}
hr{
  width:200px;
     margin-left: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="align">

<div class="about">Chapter</div><hr /></div>
<div class="align">
<div class="about">Learning Objectives</div><hr/></div>
<div class="align">
<div class="about">Pages</div><hr/></div>
<div class="align">
<div class="about">hhhhhhhhhhhhhhh</div><hr/></div></code>```

Title: Aligning a text and line parallel

Body:
There are 4 div's which has text and a line. The text will be coming from the service call and it may vary. The issue is that the line is not properly displayed it is of different length.The main condition is
1)All the line should end at the same point.
2)The line should be of 30px right from the margin and
3)The gap between the text and line should be 12px.

.about{
    display: inline-block;
}
hr{
  display:inline-block;
  width:200px;
}

Chapter

Learning Objectives

Pages

Sections

I tried with min,max-width but unable find a solution.Can anyone give a better solution?

Body:
You can get this simply with display:flex; to parent.

Try this solution.

.align{
   display:flex;
}

.about{
   padding-right:12px;

}
hr{
  width:200px;
     margin-left: 0px;
}

<div class="align">

<div class="about">Chapter</div><hr /></div>
<div class="align">
<div class="about">Learning Objectives</div><hr/></div>
<div class="align">
<div class="about">Pages</div><hr/></div>
<div class="align">
<div class="about">hhhhhhhhhhhhhhh</div><hr/></div>


问:
Is there any way to detect when a CSS file has been fully loaded?
I've been testing a lot of lazy-loaders for JavaScript and CSS that insert

答:
try this:
1- preload css on head

```<code><link rel="preload" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" as="style" onload="this.rel='stylesheet'">
<link rel="preload" href="style.css" as="style" onload="this.rel='stylesheet'">
</code>```

2 - preload js file on footer

```<code>    <link rel="preload" as="script" href="https://ajax.googleapis.com/ajax/libs/jquery/2.2.1/jquery.min.js">
    <link rel="preload" as="script" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
    <link rel="preload" as="script" href="script.js">
</code>```

3 - before tag  add

```<code><script>
/**  load defer css - js*/
// defer css
var cssAll = document.querySelectorAll('[as="style"]');
for(i = 0; i < cssAll.length; i++){
    if(cssAll[i].getAttribute("rel") == "preload"){
        cssAll[i].setAttribute("rel", "stylesheet");
    }
}
//defer js
var jsAll = document.querySelectorAll('[as="script"]');
if(!window.jQuery)
{
    // load jquery lib
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = jsAll[0].getAttribute("href");
    document.getElementsByTagName('head')[0].appendChild(script);
   // load other lib after load jquery
    script.onload = function () {
        for(i = 1; i < jsAll.length; i++){
            var jsNext = document.createElement('script');
            jsNext.type = "text/javascript";
            jsNext.src = jsAll[i].getAttribute("href");
            document.getElementsByTagName('head')[0].appendChild(jsNext);
        }
    }
}
</script>
</code>```

I tested on firefox 57, chrome 61, yandex, not tested on opera and ie

Body:
try this:
1- preload css on head

<link rel="preload" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" as="style" onload="this.rel='stylesheet'">
<link rel="preload" href="style.css" as="style" onload="this.rel='stylesheet'">

2 - preload js file on footer

    <link rel="preload" as="script" href="https://ajax.googleapis.com/ajax/libs/jquery/2.2.1/jquery.min.js">
    <link rel="preload" as="script" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
    <link rel="preload" as="script" href="script.js">

3 - before tag </body> add

<script>
/**  load defer css - js*/
// defer css
var cssAll = document.querySelectorAll('[as="style"]');
for(i = 0; i < cssAll.length; i++){
    if(cssAll[i].getAttribute("rel") == "preload"){
        cssAll[i].setAttribute("rel", "stylesheet");
    }
}
//defer js
var jsAll = document.querySelectorAll('[as="script"]');
if(!window.jQuery)
{
    // load jquery lib
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = jsAll[0].getAttribute("href");
    document.getElementsByTagName('head')[0].appendChild(script);
   // load other lib after load jquery
    script.onload = function () {
        for(i = 1; i < jsAll.length; i++){
            var jsNext = document.createElement('script');
            jsNext.type = "text/javascript";
            jsNext.src = jsAll[i].getAttribute("href");
            document.getElementsByTagName('head')[0].appendChild(jsNext);
        }
    }
}
</script>

I tested on firefox 57, chrome 61, yandex, not tested on opera and ie


问:
file not dowloading in express and react
i want to download file from folder to browser . my first code works fine .the file gets downloaded immediately but when i try to find the file specificly by id it does not works . dont know why ?

///client works

```<code>      $.ajax({
      type: 'GET' ,
      url: '/download' ,

      success : function()

      {
        window.open('/download?foo=bar&xxx=yyy');

      }

    });
</code>```

/////server works

```<code>    app.get('/download', function(req, res) {

      res.download(__dirname + '/uploads/google.png');
    });
</code>```

////client not works

```<code>          $.ajax({
          type: 'GET' ,
          url: '/download/' + id ,

          success : function()

          {
            window.open('/download?foo=bar&xxx=yyy');

          }

        });
</code>```

/////server not working

```<code>      app.get('/download/:id', function(req, res) {

      var id  = req.params.id

      console.log("ddddddddddddddddddddddddddddddddddddddddd")

      console.log(id)

      res.download(__dirname + '/uploads/google' + id  +'.png');
    });
</code>```

答:
Because you are passing values as query parameters and not URL parameter from client.

Server side

```<code>app.get('/download', function(req, res) {

  var foo  = req.query.foo;
  var xxx = req.query.xxx;

  console.log(foo)
  console.log(xxx)

  //res.download(__dirname + '/uploads/google' + id  +'.png');
});
</code>```

Body:
i want to download file from folder to browser . my first code works fine .the file gets downloaded immediately but when i try to find the file specificly by id it does not works . dont know why ?

///client works

      $.ajax({
      type: 'GET' ,
      url: '/download' ,

      success : function()

      {
        window.open('/download?foo=bar&xxx=yyy');

      }

    });

/////server works

    app.get('/download', function(req, res) {

      res.download(__dirname + '/uploads/google.png');
    });

////client not works

          $.ajax({
          type: 'GET' ,
          url: '/download/' + id ,

          success : function()

          {
            window.open('/download?foo=bar&xxx=yyy');

          }

        });

/////server not working

      app.get('/download/:id', function(req, res) {

      var id  = req.params.id

      console.log("ddddddddddddddddddddddddddddddddddddddddd")

      console.log(id)

      res.download(__dirname + '/uploads/google' + id  +'.png');
    });

Body:
Because you are passing values as query parameters and not URL parameter from client.

Server side

app.get('/download', function(req, res) {

  var foo  = req.query.foo;
  var xxx = req.query.xxx;

  console.log(foo)
  console.log(xxx)

  //res.download(__dirname + '/uploads/google' + id  +'.png');
});


问:
Subtract t1 from t2 then add it to already exist t3 and display in t3 in javascript
I want txtFirstNumberValue - txtSecondNumberValue and then add it already exists txtThirdNumberValue value but in my case, it is not working.

function sub() {
    var txtFirstNumberValue = document.getElementById('payment_image').value;
    var txtSecondNumberValue = document.getElementById('pay_amount').value;
    var txtThirdNumberValue = document.getElementById('pay_balance').value;
    if (txtFirstNumberValue == "")
     txtFirstNumberValue = 0;
   if (txtSecondNumberValue == "")
     txtSecondNumberValue = 0;
   var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);

   if (!isNaN(result)) {
    document.getElementById('pay_balance').value += result;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="input-box">
   <span>Amount</span>
   <input placeholder="Payment Amount" type="text" name="payment_image" onkeyup="sub();"  id="payment_image" class="number">
 </div>
 <div class="input-box">
   <span>Expences</span>
   <input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onkeyup="sub();"  class="number">
 </div>
 <div class="input-box">
   <span>Balance</span>
   <input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance"   class="number">
 </div></code>```

txtThirdNumberValue is coming dynamically from PHP code

答:
call function second text onblur event

and change here

```<code>document.getElementById('pay_balance').value = parseInt(txtThirdNumberValue) + result;
</code>```

function sub() {
  var txtFirstNumberValue = document.getElementById('payment_image').value;
  var txtSecondNumberValue = document.getElementById('pay_amount').value;
  var txtThirdNumberValue = document.getElementById('pay_balance').value;
  if (txtFirstNumberValue == "")
    txtFirstNumberValue = 0;
  if (txtSecondNumberValue == "")
    txtSecondNumberValue = 0;
  var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);
  //alert(result);
  if (!isNaN(result)) {
    document.getElementById('pay_balance').value = parseInt(txtThirdNumberValue) + result;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="input-box">
  <span>Amount</span>
  <input placeholder="Payment Amount" type="text" name="payment_image" id="payment_image" class="number">
</div>
<div class="input-box">
  <span>Expences</span>
  <input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onblur="sub();" class="number">
</div>
<div class="input-box">
  <span>Balance</span>
  <input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance" class="number">
</div></code>```

Body:
I want txtFirstNumberValue - txtSecondNumberValue and then add it already exists txtThirdNumberValue value but in my case, it is not working.

function sub() {
    var txtFirstNumberValue = document.getElementById('payment_image').value;
    var txtSecondNumberValue = document.getElementById('pay_amount').value;
    var txtThirdNumberValue = document.getElementById('pay_balance').value;
    if (txtFirstNumberValue == "")
     txtFirstNumberValue = 0;
   if (txtSecondNumberValue == "")
     txtSecondNumberValue = 0;
   var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);

   if (!isNaN(result)) {
    document.getElementById('pay_balance').value += result;
  }
}

   Amount
   <input placeholder="Payment Amount" type="text" name="payment_image" onkeyup="sub();"  id="payment_image" class="number">

   Expences
   <input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onkeyup="sub();"  class="number">

   Balance
   <input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance"   class="number">

txtThirdNumberValue is coming dynamically from PHP code

Body:
call function second text onblur event

and change here

document.getElementById('pay_balance').value = parseInt(txtThirdNumberValue) + result;

function sub() {
  var txtFirstNumberValue = document.getElementById('payment_image').value;
  var txtSecondNumberValue = document.getElementById('pay_amount').value;
  var txtThirdNumberValue = document.getElementById('pay_balance').value;
  if (txtFirstNumberValue == "")
    txtFirstNumberValue = 0;
  if (txtSecondNumberValue == "")
    txtSecondNumberValue = 0;
  var result = parseInt(txtFirstNumberValue) - parseInt(txtSecondNumberValue);
  //alert(result);
  if (!isNaN(result)) {
    document.getElementById('pay_balance').value = parseInt(txtThirdNumberValue) + result;
  }
}

<div class="input-box">
  <span>Amount</span>
  <input placeholder="Payment Amount" type="text" name="payment_image" id="payment_image" class="number">
</div>
<div class="input-box">
  <span>Expences</span>
  <input placeholder="Expenses" type="text" name="expenses" id="pay_amount" onblur="sub();" class="number">
</div>
<div class="input-box">
  <span>Balance</span>
  <input placeholder="Balance" value="15" readonly="readonly" type="text" name="pay_balance" id="pay_balance" class="number">
</div>


问:
Pygame Error: Unsupported Image Format
Hi I'm trying to follow these instructions from my last question:
Pygame: how to load 150 images and present each one for only .5sec per trial

This is the code I currently have and I'm unsure where I'm going wrong.

```<code>import pygame, glob
pygame.init()
pygame.mixer.init()
clock=pygame.time.Clock()

#### Set up window
window=pygame.display.set_mode((0,0),pygame.FULLSCREEN)
centre=window.get_rect().center
pygame.mouse.set_visible(False)

#colours
black = (0, 0, 0)
white = (255, 255, 255)

types= '*.tif'
artfile_names= []
for files in types:
    artfile_names.extend(glob.glob(files))

image_list = []
for artwork in artfile_names:
    image_list.append(pygame.image.load(artwork).convert())

##Randomizing
index=0
current_image = image_list[index]

if image_list[index]>= 150:
    index=0

stimulus= pygame.image.load('image_list')
soundPlay=True
def artwork():
    window.blit(stimulus,pygame.FULLSCREEN)

while not soundPlay:
    for imageEvent in pygame.event.get():
        artwork()
        pygame.display.update()
        clock.tick()
</code>```

答:
The first mistake is the same as in your previous question: types= '*.tif'. That means types is a string, but you actually wanted a tuple with the allowed file types: types = '*.tif', (the comma turns it into a tuple). So you iterate over the letters in '*.tif' and pass them to glob.glob which gives you all files in the directory and of course image_list.append(pygame.image.load(artwork).convert()) can't work if you pass it for example a .py file.

The next mistake is the stimulus = pygame.image.load('image_list') line which doesn't work because you need to pass a complete file name or path to the load function. I think your stimulus variable should actually be the current_image.

Here's a complete example that also shows you how to implement a timer.

```<code>import glob
import random
import pygame

pygame.init()
clock = pygame.time.Clock()
window = pygame.display.set_mode((640, 480))

file_types = '*.tif',  # The comma turns it into a tuple.
# file_types = ['*.tif']  # Or use a list.
artfile_names = []
for file_type in file_types:
    artfile_names.extend(glob.glob(file_type))

image_list = []
for artwork in artfile_names:
    image_list.append(pygame.image.load(artwork).convert())

random.shuffle(image_list)

index = 0
current_image = image_list[index]
previous_time = pygame.time.get_ticks()

done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # Calcualte the passed time, then increment the index, use
    # modulo to keep it in the correct range and finally change
    # the image.
    current_time = pygame.time.get_ticks()
    if current_time - previous_time > 500: # milliseconds
        index += 1
        index %= len(image_list)
        current_image = image_list[index]
        previous_time = current_time

    # Draw everything.
    window.fill((30, 30, 30))  # Clear the screen.
    # Blit the current image.
    window.blit(current_image, (100, 100))

    pygame.display.update()
    clock.tick(30)
</code>```

Title: Pygame Error: Unsupported Image Format

Body:
Hi I'm trying to follow these instructions from my last question:
Pygame: how to load 150 images and present each one for only .5sec per trial

This is the code I currently have and I'm unsure where I'm going wrong.

import pygame, glob
pygame.init()
pygame.mixer.init()
clock=pygame.time.Clock()

#### Set up window
window=pygame.display.set_mode((0,0),pygame.FULLSCREEN)
centre=window.get_rect().center
pygame.mouse.set_visible(False)

#colours
black = (0, 0, 0)
white = (255, 255, 255)

types= '*.tif'
artfile_names= []
for files in types:
    artfile_names.extend(glob.glob(files))

image_list = []
for artwork in artfile_names:
    image_list.append(pygame.image.load(artwork).convert())

##Randomizing
index=0
current_image = image_list[index]

if image_list[index]>= 150:
    index=0

stimulus= pygame.image.load('image_list')
soundPlay=True
def artwork():
    window.blit(stimulus,pygame.FULLSCREEN)

while not soundPlay:
    for imageEvent in pygame.event.get():
        artwork()
        pygame.display.update()
        clock.tick()

Body:
The first mistake is the same as in your previous question: types= '*.tif'. That means types is a string, but you actually wanted a tuple with the allowed file types: types = '*.tif', (the comma turns it into a tuple). So you iterate over the letters in '*.tif' and pass them to glob.glob which gives you all files in the directory and of course image_list.append(pygame.image.load(artwork).convert()) can't work if you pass it for example a .py file.

The next mistake is the stimulus = pygame.image.load('image_list') line which doesn't work because you need to pass a complete file name or path to the load function. I think your stimulus variable should actually be the current_image.

Here's a complete example that also shows you how to implement a timer.

import glob
import random
import pygame

pygame.init()
clock = pygame.time.Clock()
window = pygame.display.set_mode((640, 480))

file_types = '*.tif',  # The comma turns it into a tuple.
# file_types = ['*.tif']  # Or use a list.
artfile_names = []
for file_type in file_types:
    artfile_names.extend(glob.glob(file_type))

image_list = []
for artwork in artfile_names:
    image_list.append(pygame.image.load(artwork).convert())

random.shuffle(image_list)

index = 0
current_image = image_list[index]
previous_time = pygame.time.get_ticks()

done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # Calcualte the passed time, then increment the index, use
    # modulo to keep it in the correct range and finally change
    # the image.
    current_time = pygame.time.get_ticks()
    if current_time - previous_time > 500: # milliseconds
        index += 1
        index %= len(image_list)
        current_image = image_list[index]
        previous_time = current_time

    # Draw everything.
    window.fill((30, 30, 30))  # Clear the screen.
    # Blit the current image.
    window.blit(current_image, (100, 100))

    pygame.display.update()
    clock.tick(30)


问:
Is there an easy way to add tooths to divs using JQuery?
A basic div is a rectangle.  But some websites (like Facebook) have little "tooth" on the top of it, pointing to the picture or something.

It gives it a outward tooth.

Is there an easy easy easy way to do this in JQuery?

答:
Not sure if this what you're looking for... There's a pure CSS way to do this, which I do quite a bit. It's described here, among other places.

To make a tooth pointing up, add a div for the tooth: and then style it using a thick bottom border on a 0 pixel rectangle...

```<code>.tooth {
  width: 0; height: 0;
  border-color: transparent transparent black transparent;
  border-style: solid;
  border-width: 20px;
}
</code>```

You'll need to position it absolutely and and adjust where it shows up.

As a jQuery plugin might look something like:

```<code>$.fn.addTooth = function(offset) {
    return $(this).each(function() {
      $('<div>').addClass('tooth').css({
         width: 0, height: 0,
         borderColor: 'transparent transparent black transparent',
         borderStyle: 'solid',
         borderWidth: '10px',
         position: 'absolute',
         top: -20,
         left: offset
      }).appendTo(this);
      $(this).css({position: 'relative'});
    });
  }
</code>```

The CSS will need lots of tweaking.

Creating a hallowed out triangle is a little more difficult, as you need to two rectangles masking each other. I've done this (and more complex things, actually), but to be honest, it's probably just easier to create a graphic, and then add it and position it in a similar manner.

Body:
Not sure if this what you're looking for... There's a pure CSS way to do this, which I do quite a bit. It's described here, among other places.

To make a tooth pointing up, add a div for the tooth: and then style it using a thick bottom border on a 0 pixel rectangle...

.tooth {
  width: 0; height: 0;
  border-color: transparent transparent black transparent;
  border-style: solid;
  border-width: 20px;
}

You'll need to position it absolutely and and adjust where it shows up.

As a jQuery plugin might look something like:

$.fn.addTooth = function(offset) {
    return $(this).each(function() {
      $('<div>').addClass('tooth').css({
         width: 0, height: 0,
         borderColor: 'transparent transparent black transparent',
         borderStyle: 'solid',
         borderWidth: '10px',
         position: 'absolute',
         top: -20,
         left: offset
      }).appendTo(this);
      $(this).css({position: 'relative'});
    });
  }

The CSS will need lots of tweaking.

Creating a hallowed out triangle is a little more difficult, as you need to two rectangles masking each other. I've done this (and more complex things, actually), but to be honest, it's probably just easier to create a graphic, and then add it and position it in a similar manner.


问:
How to check for empty cherry-picks in a bash script?
I have a bash script which runs following cherry-pick command:

```<code>if git cherry-pick -x "$commitId"; then
        ammed_commit "$BRANCH"
  else
      #here I want to check if this resulted in empty commit
fi
</code>```

I tried running the command again and getting output in a string and then compare the string, but the output is not what I see in console. I am testing with the following script:

```<code>#!/bin/bash

READ_STATUS=$(git cherry-pick -x 001e6beda)
SUB_STRING="The previous cherry-pick is now empty"

echo $READ_STATUS

stringContain() { [ -z "${2##*$1*}" ]; }

if stringContain "$READ_STATUS" 'The previous cherry-pick is now empty';then
  echo yes
else
  echo no
fi

exit
</code>```

Below is the output I receive when I run this script:

```<code>The previous cherry-pick is now empty, possibly due to conflict resolution.
If you wish to commit it anyway, use:

git commit --allow-empty

Otherwise, please use 'git reset'
//READ_STATUS gets this value and not the one above this line???
On branch test-stage Your branch is ahead of 'upstream/test-stage' by 1 commit. (use "git push" to publish your local commits) You are currently cherry-picking commit 001e6beda. nothing to commit, working tree clean
no
</code>```

So I have got two questions:

Why my string is not getting the complete output?

How can I resolve this and successfully check if cherry-pick results in an empty commit?

答:
The git sends its error messages to stderr, not stdout. READ_STATUS=$(git cherry-pick -x 001e6beda) captures the stdout and sets READ_STATUS to nothing when git fails.

You can rewrite your code this way:

```<code>read_status=$(git cherry-pick -x 001e6beda 2>&1)
empty_message="The previous cherry-pick is now empty"
if [[ $read_status = *"$empty_message"* ]]; then
  echo yes
else
  echo no
fi
</code>```

See also:

String contains in Bash

Body:
I have a bash script which runs following cherry-pick command:

if git cherry-pick -x "$commitId"; then
        ammed_commit "$BRANCH"
  else
      #here I want to check if this resulted in empty commit
fi

I tried running the command again and getting output in a string and then compare the string, but the output is not what I see in console. I am testing with the following script:

#!/bin/bash

READ_STATUS=$(git cherry-pick -x 001e6beda)
SUB_STRING="The previous cherry-pick is now empty"

echo $READ_STATUS

stringContain() { [ -z "${2##*$1*}" ]; }

if stringContain "$READ_STATUS" 'The previous cherry-pick is now empty';then
  echo yes
else
  echo no
fi

exit

Below is the output I receive when I run this script:

The previous cherry-pick is now empty, possibly due to conflict resolution.
If you wish to commit it anyway, use:

git commit --allow-empty

Otherwise, please use 'git reset'
//READ_STATUS gets this value and not the one above this line???
On branch test-stage Your branch is ahead of 'upstream/test-stage' by 1 commit. (use "git push" to publish your local commits) You are currently cherry-picking commit 001e6beda. nothing to commit, working tree clean
no

So I have got two questions:

Why my string is not getting the complete output?

How can I resolve this and successfully check if cherry-pick results in an empty commit?

Body:
The git sends its error messages to stderr, not stdout. READ_STATUS=$(git cherry-pick -x 001e6beda) captures the stdout and sets READ_STATUS to nothing when git fails.

You can rewrite your code this way:

read_status=$(git cherry-pick -x 001e6beda 2>&1)
empty_message="The previous cherry-pick is now empty"
if [[ $read_status = *"$empty_message"* ]]; then
  echo yes
else
  echo no
fi

See also:

String contains in Bash


问:
Yammer login with access token
I'm making use of the Yammer APIs and embed feed. I was wondering if it was possible to force a sign into Yammer using the user's access token (saved in some local storage). Is it possible to make the yam.getloginstatus() function return true with just the access token, instead of having the user login every time?</p>

答: There is a setAuthToken() method available which can be used to inject a token. You can continue to authorize a user to your Yammer app and store the token, or use the more advanced approach with impersonation as laid out in the article that is linked. Make sure to create threat models for your application so you have a plan to protect user tokens.</p>

Title: Yammer login with access token


问:
Make header text vertical align bottom
After rid of nowrap from header text I want to make it bottom
I was trying put vertical-align: bottom everywhere but without success.
Here is example where first column is aligned to top.

```<code>.ui-grid-cell-contents {
 ....

  vertical-align: bottom;
}
</code>```

http://plnkr.co/edit/JzJVRgjz2VLELcqcdR4I?p=preview

How to make header text in angular-ui-grid to be bottom?

答:
at first make parent tag css property display to table. then child tag (header contents tag) make css property display to table-cell, then vertical-align to bottom. like ..</p>

```<code>div[role="columnheader"] {
    display: table;
    width: 100%;
}

.ui-grid-header-cell .ui-grid-cell-contents {
    height: 58px;
    /* white-space: normal !important; */
    /* -ms-text-overflow: clip; */
    /* -o-text-overflow: clip; */
    /* text-overflow: clip; */
    /* overflow: visible; */
    /* text-align: center; */
    display: table-cell;
    vertical-align: bottom;
}
</code>```

Title: Make header text vertical align bottom

Body:
After rid of nowrap from header text I want to make it bottom
I was trying put vertical-align: bottom everywhere but without success.
Here is example where first column is aligned to top.

.ui-grid-cell-contents {
 ....

  vertical-align: bottom;
}

http://plnkr.co/edit/JzJVRgjz2VLELcqcdR4I?p=preview

How to make header text in angular-ui-grid to be bottom?

Body:
at first make parent tag css property display to table. then child tag (header contents tag) make css property display to table-cell, then vertical-align to bottom. like ..

div[role="columnheader"] {
    display: table;
    width: 100%;
}

.ui-grid-header-cell .ui-grid-cell-contents {
    height: 58px;
    /* white-space: normal !important; */
    /* -ms-text-overflow: clip; */
    /* -o-text-overflow: clip; */
    /* text-overflow: clip; */
    /* overflow: visible; */
    /* text-align: center; */
    display: table-cell;
    vertical-align: bottom;
}