Programs & Examples On #Hibernate mapping

Hibernate uses mapping metadata to find out how to load and store objects of the persistent class. The Hibernate mapping could be specified using configuration files or annotations.

Can someone explain mappedBy in JPA and Hibernate?

Table relationship vs. entity relationship

In a relational database system, a one-to-many table relationship looks as follows:

one-to-many table relationship

Note that the relationship is based on the Foreign Key column (e.g., post_id) in the child table.

So, there is a single source of truth when it comes to managing a one-to-many table relationship.

Now, if you take a bidirectional entity relationship that maps on the one-to-many table relationship we saw previously:

Bidirectional One-To-Many entity association

If you take a look at the diagram above, you can see that there are two ways to manage this relationship.

In the Post entity, you have the comments collection:

@OneToMany(
    mappedBy = "post",
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();

And, in the PostComment, the post association is mapped as follows:

@ManyToOne(
    fetch = FetchType.LAZY
)
@JoinColumn(name = "post_id")
private Post post;

Because there are two ways to represent the Foreign Key column, you must define which is the source of truth when it comes to translating the association state change into its equivalent Foreign Key column value modification.

MappedBy

The mappedBy attribute tells that the @ManyToOne side is in charge of managing the Foreign Key column, and the collection is used only to fetch the child entities and to cascade parent entity state changes to children (e.g., removing the parent should also remove the child entities).

Synchronize both sides of a bidirectional association

Now, even if you defined the mappedBy attribute and the child-side @ManyToOne association manages the Foreign Key column, you still need to synchronize both sides of the bidirectional association.

The best way to do that is to add these two utility methods:

public void addComment(PostComment comment) {
    comments.add(comment);
    comment.setPost(this);
}

public void removeComment(PostComment comment) {
    comments.remove(comment);
    comment.setPost(null);
}

The addComment and removeComment methods ensure that both sides are synchronized. So, if we add a child entity, the child entity needs to point to the parent and the parent entity should have the child contained in the child collection.

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

It seems you are connecting to the wrong database. R u sure "jdbc:postgresql://localhost/testDB" will connect you to the actual datasource ?

Generally they are of the form "jdbc://hostname/databasename". Look into Postgresql log file.

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.

The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.

Below can be the required mapping,

<class name="com.example.CompanyEntity" table="COMPANY">
    <id name="id" column="COMPANY_ID"/>
    <set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
        <key column="COMPANY_ID" not-null="true"/>
        <one-to-many entity-name="vendorName"/>
    </set>
</class>

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

One other cause may be using lombok.

@Builder - causes to save Collections.emptyList() even if you say .myCollection(new ArrayList());

@Singular - ignores the class level defaults and leaves field null even if the class field was declared as myCollection = new ArrayList()

My 2 cents, just spent 2 hours with the same :)

Hibernate table not mapped error in HQL query

Thanks everybody. Lots of good ideas. This is my first application in Spring and Hibernate.. so a little more patience when dealing with "novices" like me..

Please read Tom Anderson and Roman C.'s answers. They explained very well the problem. And all of you helped me.I replaced

SELECT COUNT(*) FROM Books

with

select count(book.id) from Book book

And of course, I have this Spring config:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="packagesToScan" value="extjs.model"/>

Thank you all again!

How to map calculated properties with JPA and Hibernate

You have three options:

  • either you are calculating the attribute using a @Transient method
  • you can also use @PostLoad entity listener
  • or you can use the Hibernate specific @Formula annotation

While Hibernate allows you to use @Formula, with JPA, you can use the @PostLoad callback to populate a transient property with the result of some calculation:

@Column(name = "price")
private Double price;

@Column(name = "tax_percentage")
private Double taxes;

@Transient
private Double priceWithTaxes;

@PostLoad
private void onLoad() {
    this.priceWithTaxes = price * taxes;
}

So, you can use the Hibernate @Formula like this:

@Formula("""
    round(
       (interestRate::numeric / 100) *
       cents *
       date_part('month', age(now(), createdOn)
    )
    / 12)
    / 100::numeric
    """)
private double interestDollars;

In which case do you use the JPA @JoinTable annotation?

@ManyToMany associations

Most often, you will need to use @JoinTable annotation to specify the mapping of a many-to-many table relationship:

  • the name of the link table and
  • the two Foreign Key columns

So, assuming you have the following database tables:

Many-to-many table relationship

In the Post entity, you would map this relationship, like this:

@ManyToMany(cascade = {
    CascadeType.PERSIST,
    CascadeType.MERGE
})
@JoinTable(
    name = "post_tag",
    joinColumns = @JoinColumn(name = "post_id"),
    inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private List<Tag> tags = new ArrayList<>();

The @JoinTable annotation is used to specify the table name via the name attribute, as well as the Foreign Key column that references the post table (e.g., joinColumns) and the Foreign Key column in the post_tag link table that references the Tag entity via the inverseJoinColumns attribute.

Notice that the cascade attribute of the @ManyToMany annotation is set to PERSIST and MERGE only because cascading REMOVE is a bad idea since we the DELETE statement will be issued for the other parent record, tag in our case, not to the post_tag record.

Unidirectional @OneToMany associations

The unidirectional @OneToMany associations, that lack a @JoinColumn mapping, behave like many-to-many table relationships, rather than one-to-many.

So, assuming you have the following entity mappings:

@Entity(name = "Post")
@Table(name = "post")
public class Post {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String title;
 
    @OneToMany(
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();
 
    //Constructors, getters and setters removed for brevity
}
 
@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String review;
 
    //Constructors, getters and setters removed for brevity
}

Hibernate will assume the following database schema for the above entity mapping:

Unidirectional @OneToMany JPA association database tables

As already explained, the unidirectional @OneToMany JPA mapping behaves like a many-to-many association.

To customize the link table, you can also use the @JoinTable annotation:

@OneToMany(
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
@JoinTable(
    name = "post_comment_ref",
    joinColumns = @JoinColumn(name = "post_id"),
    inverseJoinColumns = @JoinColumn(name = "post_comment_id")
)
private List<PostComment> comments = new ArrayList<>();

And now, the link table is going to be called post_comment_ref and the Foreign Key columns will be post_id, for the post table, and post_comment_id, for the post_comment table.

Unidirectional @OneToMany associations are not efficient, so you are better off using bidirectional @OneToMany associations or just the @ManyToOne side.

How can I mark a foreign key constraint using Hibernate annotations?

@Column is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions to Question, since an instance represents a single question, and not several ones. Then create the association:

@Entity
@Table(name = "UserAnswer")
public class UserAnswer {

    // this entity needs an ID:
    @Id
    @Column(name="useranswer_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "question_id")
    private Question question;

    @Column(name = "response")
    private String response;

    //getter and setter 
}

The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.

Get path to execution directory of Windows Forms application

string apppath = 
    (new System.IO.FileInfo
    (System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).DirectoryName;

How can you strip non-ASCII characters from a string? (in C#)

I found the following slightly altered range useful for parsing comment blocks out of a database, this means that you won't have to contend with tab and escape characters which would cause a CSV field to become upset.

parsememo = Regex.Replace(parsememo, @"[^\u001F-\u007F]", string.Empty);

If you want to avoid other special characters or particular punctuation check the ascii table

How can I check if a Perl array contains a particular value?

If you need to know the amount of every element in array besides existing of that element you may use

my %bad_param_lookup;
@bad_param_lookup{ @bad_params } = ( 1 ) x @bad_params;
%bad_param_lookup = map { $_ => $bad_param_lookup{$_}++} @bad_params;

and then for every $i that is in @bad_params, $bad_param_lookup{$i} contains amount of $i in @bad_params

How to implement a lock in JavaScript

Here's a simple lock mechanism, implemented via closure

_x000D_
_x000D_
const createLock = () => {

    let lockStatus = false

    const release = () => {
        lockStatus = false
    }

    const acuire = () => {
        if (lockStatus == true)
            return false
        lockStatus = true
        return true
    }
    
    return {
        lockStatus: lockStatus, 
        acuire: acuire,
        release: release,
    }
}

lock = createLock() // create a lock
lock.acuire() // acuired a lock

if (lock.acuire()){
  console.log("Was able to acuire");
} else {
  console.log("Was not to acuire"); // This will execute
}

lock.release() // now the lock is released

if(lock.acuire()){
  console.log("Was able to acuire"); // This will execute
} else {
  console.log("Was not to acuire"); 
}

lock.release() // Hey don't forget to release
_x000D_
_x000D_
_x000D_

How to make use of ng-if , ng-else in angularJS

The syntax for ng if else in angular is :

<div class="case" *ngIf="data.id === '5'; else elsepart; ">
    <input type="checkbox" id="{{data.id}}" value="{{data.displayName}}" 
    data-ng-model="customizationCntrl.check[data.id1]" data-ng-checked="
    {{data.status}}=='1'" onclick="return false;">{{data.displayName}}<br>
</div>
<ng-template #elsepart>
    <div class="case">
        <input type="checkbox" id="{{data.id}}" value={{data.displayName}}"  
        data-ng-model="customizationCntrl.check[data.id]" data-ng-checked="
        {{data.status}}=='1'">{{data.displayName}}<br>
    </div> 
</ng-template>

How to check for DLL dependency?

Please refer SysInternal toolkit from Microsoft from below link, https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer

Goto the download folder, Open "Procexp64.exe" as admin privilege. Open Find Menu-> "Find Handle or DLL" option or Ctrl+F shortcut way.

enter image description here

How to commit my current changes to a different branch in Git

You can just create a new branch and switch onto it. Commit your changes then:

git branch dirty
git checkout dirty
// And your commit follows ...

Alternatively, you can also checkout an existing branch (just git checkout <name>). But only, if there are no collisions (the base of all edited files is the same as in your current branch). Otherwise you will get a message.

Passing multiple values to a single PowerShell script parameter

I call a scheduled script who must connect to a list of Server this way:

Powershell.exe -File "YourScriptPath" "Par1,Par2,Par3"

Then inside the script:

param($list_of_servers)
...
Connect-Viserver $list_of_servers.split(",")

The split operator returns an array of string

Search for a string in Enum and return the Enum

You can cast the int to an enum

(MyColour)2

There is also the option of Enum.Parse

(MyColour)Enum.Parse(typeof(MyColour), "Red")

SQL Server: converting UniqueIdentifier to string in a case statement

Instead of Str(RequestID), try convert(varchar(38), RequestID)

Fix columns in horizontal scrolling

SOLVED

http://jsfiddle.net/DJqPf/7/

.table-wrapper { 
    overflow-x:scroll;
    overflow-y:visible;
    width:250px;
    margin-left: 120px;
}
td, th {
    padding: 5px 20px;
    width: 100px;
}
th:first-child {
    position: fixed;
    left: 5px
}

UPDATE

_x000D_
_x000D_
$(function () {  _x000D_
  $('.table-wrapper tr').each(function () {_x000D_
    var tr = $(this),_x000D_
        h = 0;_x000D_
    tr.children().each(function () {_x000D_
      var td = $(this),_x000D_
          tdh = td.height();_x000D_
      if (tdh > h) h = tdh;_x000D_
    });_x000D_
    tr.css({height: h + 'px'});_x000D_
  });_x000D_
});
_x000D_
body {_x000D_
    position: relative;_x000D_
}_x000D_
.table-wrapper { _x000D_
    overflow-x:scroll;_x000D_
    overflow-y:visible;_x000D_
    width:200px;_x000D_
    margin-left: 120px;_x000D_
}_x000D_
_x000D_
_x000D_
td, th {_x000D_
    padding: 5px 20px;_x000D_
    width: 100px;_x000D_
}_x000D_
tbody tr {_x000D_
  _x000D_
}_x000D_
th:first-child {_x000D_
    position: absolute;_x000D_
    left: 5px_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>_x000D_
  <meta charset="utf-8">_x000D_
  <title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
    <h1>SOME RANDOM TEXT</h1>_x000D_
</div>_x000D_
<div class="table-wrapper">_x000D_
    <table id="consumption-data" class="data">_x000D_
        <thead class="header">_x000D_
            <tr>_x000D_
                <th>Month</th>_x000D_
                <th>Item 1</th>_x000D_
                <th>Item 2</th>_x000D_
                <th>Item 3</th>_x000D_
                <th>Item 4</th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody class="results">_x000D_
            <tr>_x000D_
                <th>Jan is an awesome month</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Feb</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Mar</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Apr</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>  _x000D_
            </tr>_x000D_
            <tr>    _x000D_
                <th>May</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Jun</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
_x000D_
            <tr>_x000D_
                <th>...</th>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I see the extensions loaded by PHP?

If you want to test if a particular extension is loaded you can also use the extension_loaded function, see documentation here

php -r "var_dump(extension_loaded('json'));"

The ternary (conditional) operator in C

It's syntatic sugar and a handy shorthand for brief if/else blocks that only contain one statement. Functionally, both constructs should perform identically.

How to copy files from 'assets' folder to sdcard?

Using some of the concepts in the answers to this question, I wrote up a class called AssetCopier to make copying /assets/ simple. It's available on github and can be accessed with jitpack.io:

new AssetCopier(MainActivity.this)
        .withFileScanning()
        .copy("tocopy", destDir);

See https://github.com/flipagram/android-assetcopier for more details.

What is the difference between logical data model and conceptual data model?

In this table you can see the difference between each model: Difference between data models

See http://www.1keydata.com/datawarehousing/data-modeling-levels.html for more information and some data model examples.

How do I create variable variables?

Whenever you want to use variable variables, it's probably better to use a dictionary. So instead of writing

$foo = "bar"
$$foo = "baz"

you write

mydict = {}
foo = "bar"
mydict[foo] = "baz"

This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you can have different "namespaces".

PHP session lost after redirect

I had the same problem and found the easiest way. I simply redirected to a redirect .html with 1 line of JS

<!DOCTYPE html>
<html>
<script type="text/javascript">
<!--
window.location = "admin_index.php";
//–>
</script>
</html>

instead of PHP

header_remove();
header('Location: admin_login.php');
die;

I hope this helps.

Love Gram

How to open an elevated cmd using command line for Windows?

I ran into the same problem and the only way I was able to open the CMD as administrator from CMD was doing the following:

  1. Open CMD
  2. Write powershell -Command "Start-Process cmd -Verb RunAs" and press Enter
  3. A pop-up window will appear asking to open a CMD as administrator

When should I use a table variable vs temporary table in sql server?

I totally agree with Abacus (sorry - don't have enough points to comment).

Also, keep in mind it doesn't necessarily come down to how many records you have, but the size of your records.

For instance, have you considered the performance difference between 1,000 records with 50 columns each vs 100,000 records with only 5 columns each?

Lastly, maybe you're querying/storing more data than you need? Here's a good read on SQL optimization strategies. Limit the amount of data you're pulling, especially if you're not using it all (some SQL programmers do get lazy and just select everything even though they only use a tiny subset). Don't forget the SQL query analyzer may also become your best friend.

PDF Blob - Pop up window not showing content

You need to set the responseType to arraybuffer if you would like to create a blob from your response data:

$http.post('/fetchBlobURL',{myParams}, {responseType: 'arraybuffer'})
   .success(function (data) {
       var file = new Blob([data], {type: 'application/pdf'});
       var fileURL = URL.createObjectURL(file);
       window.open(fileURL);
});

more information: Sending_and_Receiving_Binary_Data

Initial bytes incorrect after Java AES/CBC decryption

This is an improvement over the accepted answer.

Changes:

(1) Using random IV and prepend it to the encrypted text

(2) Using SHA-256 to generate a key from a passphrase

(3) No dependency on Apache Commons

public static void main(String[] args) throws GeneralSecurityException {
    String plaintext = "Hello world";
    String passphrase = "My passphrase";
    String encrypted = encrypt(passphrase, plaintext);
    String decrypted = decrypt(passphrase, encrypted);
    System.out.println(encrypted);
    System.out.println(decrypted);
}

private static SecretKeySpec getKeySpec(String passphrase) throws NoSuchAlgorithmException {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    return new SecretKeySpec(digest.digest(passphrase.getBytes(UTF_8)), "AES");
}

private static Cipher getCipher() throws NoSuchPaddingException, NoSuchAlgorithmException {
    return Cipher.getInstance("AES/CBC/PKCS5PADDING");
}

public static String encrypt(String passphrase, String value) throws GeneralSecurityException {
    byte[] initVector = new byte[16];
    SecureRandom.getInstanceStrong().nextBytes(initVector);
    Cipher cipher = getCipher();
    cipher.init(Cipher.ENCRYPT_MODE, getKeySpec(passphrase), new IvParameterSpec(initVector));
    byte[] encrypted = cipher.doFinal(value.getBytes());
    return DatatypeConverter.printBase64Binary(initVector) +
            DatatypeConverter.printBase64Binary(encrypted);
}

public static String decrypt(String passphrase, String encrypted) throws GeneralSecurityException {
    byte[] initVector = DatatypeConverter.parseBase64Binary(encrypted.substring(0, 24));
    Cipher cipher = getCipher();
    cipher.init(Cipher.DECRYPT_MODE, getKeySpec(passphrase), new IvParameterSpec(initVector));
    byte[] original = cipher.doFinal(DatatypeConverter.parseBase64Binary(encrypted.substring(24)));
    return new String(original);
}

Turning off eslint rule for a specific file

You can turn off specific rule for a file by using /*eslint [<rule: "off"], >]*/

/* eslint no-console: "off", no-mixed-operators: "off" */

Version: [email protected]

How to parse JSON response from Alamofire API in Swift?

I'm neither a JSON expert nor a Swift expert, but the following is working for me. :) I have extracted the code from my current app, and only changed "MyLog to println", and indented with spaces to get it to show as a code block (hopefully I didn't break it).

func getServerCourseVersion(){

    Alamofire.request(.GET,"\(PUBLIC_URL)/vtcver.php")
        .responseJSON { (_,_, JSON, _) in
          if let jsonResult = JSON as? Array<Dictionary<String,String>> {
            let courseName = jsonResult[0]["courseName"]
            let courseVersion = jsonResult[0]["courseVersion"]
            let courseZipFile = jsonResult[0]["courseZipFile"]

            println("JSON:    courseName: \(courseName)")
            println("JSON: courseVersion: \(courseVersion)")
            println("JSON: courseZipFile: \(courseZipFile)")

          }
      }
}

Hope this helps.

Edit:

For reference, here is what my PHP Script returns:

[{"courseName": "Training Title","courseVersion": "1.01","courseZipFile": "101/files.zip"}]

How do you find out the caller function in JavaScript?

heystewart's answer and JiarongWu's answer both mentioned that the Error object has access to the stack.

Here's an example:

_x000D_
_x000D_
function main() {
  Hello();
}

function Hello() {
  var stack = new Error().stack;
  // N.B. stack === "Error\n  at Hello ...\n  at main ... \n...."
  var m = stack.match(/.*?Hello.*?\n(.*?)\n/);
  if (m) {
    var caller_name = m[1];
    console.log("Caller is:", caller_name)
  }
}

main();
_x000D_
_x000D_
_x000D_

Different browsers shows the stack in different string formats:

Safari  : Caller is: main@https://stacksnippets.net/js:14:8
Firefox : Caller is: main@https://stacksnippets.net/js:14:3
Chrome  : Caller is:     at main (https://stacksnippets.net/js:14:3)
IE Edge : Caller is:    at main (https://stacksnippets.net/js:14:3)
IE      : Caller is:    at main (https://stacksnippets.net/js:14:3)

Most browsers will set the stack with var stack = (new Error()).stack. In Internet Explorer the stack will be undefined - you have to throw a real exception to retrieve the stack.

Conclusion: It's possible to determine "main" is the caller to "Hello" using the stack in the Error object. In fact it will work in cases where the callee / caller approach doesn't work. It will also show you context, i.e. source file and line number. However effort is required to make the solution cross platform.

What is event bubbling and capturing?

If there are two elements element 1 and element 2. Element 2 is inside element 1 and we attach an event handler with both the elements lets say onClick. Now when we click on element 2 then eventHandler for both the elements will be executed. Now here the question is in which order the event will execute. If the event attached with element 1 executes first it is called event capturing and if the event attached with element 2 executes first this is called event bubbling. As per W3C the event will start in the capturing phase until it reaches the target comes back to the element and then it starts bubbling

The capturing and bubbling states are known by the useCapture parameter of addEventListener method

eventTarget.addEventListener(type,listener,[,useCapture]);

By Default useCapture is false. It means it is in the bubbling phase.

_x000D_
_x000D_
var div1 = document.querySelector("#div1");_x000D_
var div2 = document.querySelector("#div2");_x000D_
_x000D_
div1.addEventListener("click", function (event) {_x000D_
  alert("you clicked on div 1");_x000D_
}, true);_x000D_
_x000D_
div2.addEventListener("click", function (event) {_x000D_
  alert("you clicked on div 2");_x000D_
}, false);
_x000D_
#div1{_x000D_
  background-color:red;_x000D_
  padding: 24px;_x000D_
}_x000D_
_x000D_
#div2{_x000D_
  background-color:green;_x000D_
}
_x000D_
<div id="div1">_x000D_
  div 1_x000D_
  <div id="div2">_x000D_
    div 2_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Please try with changing true and false.

validate natural input number with ngpattern

<label>Mobile Number(*)</label>
<input id="txtMobile" ng-maxlength="10" maxlength="10" Validate-phone  required  name='strMobileNo' ng-model="formModel.strMobileNo" type="text"  placeholder="Enter Mobile Number">
<span style="color:red" ng-show="regForm.strMobileNo.$dirty && regForm.strMobileNo.$invalid"><span ng-show="regForm.strMobileNo.$error.required">Phone is required.</span>

the following code will help for phone number validation and the respected directive is

app.directive('validatePhone', function() {
var PHONE_REGEXP = /^[789]\d{9}$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = PHONE_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

jquery - disable click

If you're using jQuery versions 1.4.3+:

$('selector').click(false);

If not:

$('selector').click(function(){return false;});

Set icon for Android application

Put your images in mipmap folder and set in manifest file... like as

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

App Folder Directory :

enter image description here

Icon Size & Format : enter image description here

How to get base url in CodeIgniter 2.*

You need to load the URL Helper in order to use base_url(). In your controller, do:

$this->load->helper('url');

Then in your view you can do:

echo base_url();

Postgresql: error "must be owner of relation" when changing a owner object

Thanks to Mike's comment, I've re-read the doc and I've realised that my current user (i.e. userA that already has the create privilege) wasn't a direct/indirect member of the new owning role...

So the solution was quite simple - I've just done this grant:

grant userB to userA;

That's all folks ;-)


Update:

Another requirement is that the object has to be owned by user userA before altering it...

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{

  @Autowired
  MyService service;
...
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException
    {
        // Do something with the context here
    }
}

Use of ~ (tilde) in R programming Language

The thing on the right of <- is a formula object. It is often used to denote a statistical model, where the thing on the left of the ~ is the response and the things on the right of the ~ are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".

The myFormula <- part of that line stores the formula in an object called myFormula so you can use it in other parts of your R code.


Other common uses of formula objects in R

The lattice package uses them to specify the variables to plot.
The ggplot2 package uses them to specify panels for plotting.
The dplyr package uses them for non-standard evaulation.

SQL Server: Extract Table Meta-Data (description, fields and their data types)

I liked @Andomar's answer best, but I needed the column descriptions also. Here is his query modified to include those also. (Uncomment the last part of the WHERE clause to return only rows where either description is non-null).

SELECT
    TableName = tbl.table_schema + '.' + tbl.table_name, 
    TableDescription = tableProp.value,
    ColumnName = col.column_name, 
    ColumnDataType = col.data_type,
    ColumnDescription = colDesc.ColumnDescription
FROM information_schema.tables tbl
INNER JOIN information_schema.columns col 
    ON col.table_name = tbl.table_name
LEFT JOIN sys.extended_properties tableProp 
    ON tableProp.major_id = object_id(tbl.table_schema + '.' + tbl.table_name) 
        AND tableProp.minor_id = 0
        AND tableProp.name = 'MS_Description' 
LEFT JOIN (
    SELECT sc.object_id, sc.column_id, sc.name, colProp.[value] AS ColumnDescription
    FROM sys.columns sc
    INNER JOIN sys.extended_properties colProp
        ON colProp.major_id = sc.object_id
            AND colProp.minor_id = sc.column_id
            AND colProp.name = 'MS_Description' 
) colDesc
    ON colDesc.object_id = object_id(tbl.table_schema + '.' + tbl.table_name)
        AND colDesc.name = col.COLUMN_NAME
WHERE tbl.table_type = 'base table'
--AND tableProp.[value] IS NOT NULL OR colDesc.ColumnDescription IS NOT null

forEach is not a function error with JavaScript array

If you are trying to loop over a NodeList like this:

const allParagraphs = document.querySelectorAll("p");

I highly recommend loop it this way:

Array.prototype.forEach.call(allParagraphs , function(el) {
    // Write your code here
})

Personally, I've tried several ways but most of them didn't work as I wanted to loop over a NodeList, but this one works like a charm, give it a try!

The NodeList isn't an Array, but we treat it as an Array, using Array. So, you need to know that it is not supported in older browsers!

Need more information about NodeList? Please read its documentation on MDN.

How to dispatch a Redux action with a timeout?

Don’t fall into the trap of thinking a library should prescribe how to do everything. If you want to do something with a timeout in JavaScript, you need to use setTimeout. There is no reason why Redux actions should be any different.

Redux does offer some alternative ways of dealing with asynchronous stuff, but you should only use those when you realize you are repeating too much code. Unless you have this problem, use what the language offers and go for the simplest solution.

Writing Async Code Inline

This is by far the simplest way. And there’s nothing specific to Redux here.

store.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' })
setTimeout(() => {
  store.dispatch({ type: 'HIDE_NOTIFICATION' })
}, 5000)

Similarly, from inside a connected component:

this.props.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' })
setTimeout(() => {
  this.props.dispatch({ type: 'HIDE_NOTIFICATION' })
}, 5000)

The only difference is that in a connected component you usually don’t have access to the store itself, but get either dispatch() or specific action creators injected as props. However this doesn’t make any difference for us.

If you don’t like making typos when dispatching the same actions from different components, you might want to extract action creators instead of dispatching action objects inline:

// actions.js
export function showNotification(text) {
  return { type: 'SHOW_NOTIFICATION', text }
}
export function hideNotification() {
  return { type: 'HIDE_NOTIFICATION' }
}

// component.js
import { showNotification, hideNotification } from '../actions'

this.props.dispatch(showNotification('You just logged in.'))
setTimeout(() => {
  this.props.dispatch(hideNotification())
}, 5000)

Or, if you have previously bound them with connect():

this.props.showNotification('You just logged in.')
setTimeout(() => {
  this.props.hideNotification()
}, 5000)

So far we have not used any middleware or other advanced concept.

Extracting Async Action Creator

The approach above works fine in simple cases but you might find that it has a few problems:

  • It forces you to duplicate this logic anywhere you want to show a notification.
  • The notifications have no IDs so you’ll have a race condition if you show two notifications fast enough. When the first timeout finishes, it will dispatch HIDE_NOTIFICATION, erroneously hiding the second notification sooner than after the timeout.

To solve these problems, you would need to extract a function that centralizes the timeout logic and dispatches those two actions. It might look like this:

// actions.js
function showNotification(id, text) {
  return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
  return { type: 'HIDE_NOTIFICATION', id }
}

let nextNotificationId = 0
export function showNotificationWithTimeout(dispatch, text) {
  // Assigning IDs to notifications lets reducer ignore HIDE_NOTIFICATION
  // for the notification that is not currently visible.
  // Alternatively, we could store the timeout ID and call
  // clearTimeout(), but we’d still want to do it in a single place.
  const id = nextNotificationId++
  dispatch(showNotification(id, text))

  setTimeout(() => {
    dispatch(hideNotification(id))
  }, 5000)
}

Now components can use showNotificationWithTimeout without duplicating this logic or having race conditions with different notifications:

// component.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged in.')

// otherComponent.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged out.')    

Why does showNotificationWithTimeout() accept dispatch as the first argument? Because it needs to dispatch actions to the store. Normally a component has access to dispatch but since we want an external function to take control over dispatching, we need to give it control over dispatching.

If you had a singleton store exported from some module, you could just import it and dispatch directly on it instead:

// store.js
export default createStore(reducer)

// actions.js
import store from './store'

// ...

let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
  const id = nextNotificationId++
  store.dispatch(showNotification(id, text))

  setTimeout(() => {
    store.dispatch(hideNotification(id))
  }, 5000)
}

// component.js
showNotificationWithTimeout('You just logged in.')

// otherComponent.js
showNotificationWithTimeout('You just logged out.')    

This looks simpler but we don’t recommend this approach. The main reason we dislike it is because it forces store to be a singleton. This makes it very hard to implement server rendering. On the server, you will want each request to have its own store, so that different users get different preloaded data.

A singleton store also makes testing harder. You can no longer mock a store when testing action creators because they reference a specific real store exported from a specific module. You can’t even reset its state from outside.

So while you technically can export a singleton store from a module, we discourage it. Don’t do this unless you are sure that your app will never add server rendering.

Getting back to the previous version:

// actions.js

// ...

let nextNotificationId = 0
export function showNotificationWithTimeout(dispatch, text) {
  const id = nextNotificationId++
  dispatch(showNotification(id, text))

  setTimeout(() => {
    dispatch(hideNotification(id))
  }, 5000)
}

// component.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged in.')

// otherComponent.js
showNotificationWithTimeout(this.props.dispatch, 'You just logged out.')    

This solves the problems with duplication of logic and saves us from race conditions.

Thunk Middleware

For simple apps, the approach should suffice. Don’t worry about middleware if you’re happy with it.

In larger apps, however, you might find certain inconveniences around it.

For example, it seems unfortunate that we have to pass dispatch around. This makes it trickier to separate container and presentational components because any component that dispatches Redux actions asynchronously in the manner above has to accept dispatch as a prop so it can pass it further. You can’t just bind action creators with connect() anymore because showNotificationWithTimeout() is not really an action creator. It does not return a Redux action.

In addition, it can be awkward to remember which functions are synchronous action creators like showNotification() and which are asynchronous helpers like showNotificationWithTimeout(). You have to use them differently and be careful not to mistake them with each other.

This was the motivation for finding a way to “legitimize” this pattern of providing dispatch to a helper function, and help Redux “see” such asynchronous action creators as a special case of normal action creators rather than totally different functions.

If you’re still with us and you also recognize as a problem in your app, you are welcome to use the Redux Thunk middleware.

In a gist, Redux Thunk teaches Redux to recognize special kinds of actions that are in fact functions:

import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'

const store = createStore(
  reducer,
  applyMiddleware(thunk)
)

// It still recognizes plain object actions
store.dispatch({ type: 'INCREMENT' })

// But with thunk middleware, it also recognizes functions
store.dispatch(function (dispatch) {
  // ... which themselves may dispatch many times
  dispatch({ type: 'INCREMENT' })
  dispatch({ type: 'INCREMENT' })
  dispatch({ type: 'INCREMENT' })

  setTimeout(() => {
    // ... even asynchronously!
    dispatch({ type: 'DECREMENT' })
  }, 1000)
})

When this middleware is enabled, if you dispatch a function, Redux Thunk middleware will give it dispatch as an argument. It will also “swallow” such actions so don’t worry about your reducers receiving weird function arguments. Your reducers will only receive plain object actions—either emitted directly, or emitted by the functions as we just described.

This does not look very useful, does it? Not in this particular situation. However it lets us declare showNotificationWithTimeout() as a regular Redux action creator:

// actions.js
function showNotification(id, text) {
  return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
  return { type: 'HIDE_NOTIFICATION', id }
}

let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
  return function (dispatch) {
    const id = nextNotificationId++
    dispatch(showNotification(id, text))

    setTimeout(() => {
      dispatch(hideNotification(id))
    }, 5000)
  }
}

Note how the function is almost identical to the one we wrote in the previous section. However it doesn’t accept dispatch as the first argument. Instead it returns a function that accepts dispatch as the first argument.

How would we use it in our component? Definitely, we could write this:

// component.js
showNotificationWithTimeout('You just logged in.')(this.props.dispatch)

We are calling the async action creator to get the inner function that wants just dispatch, and then we pass dispatch.

However this is even more awkward than the original version! Why did we even go that way?

Because of what I told you before. If Redux Thunk middleware is enabled, any time you attempt to dispatch a function instead of an action object, the middleware will call that function with dispatch method itself as the first argument.

So we can do this instead:

// component.js
this.props.dispatch(showNotificationWithTimeout('You just logged in.'))

Finally, dispatching an asynchronous action (really, a series of actions) looks no different than dispatching a single action synchronously to the component. Which is good because components shouldn’t care whether something happens synchronously or asynchronously. We just abstracted that away.

Notice that since we “taught” Redux to recognize such “special” action creators (we call them thunk action creators), we can now use them in any place where we would use regular action creators. For example, we can use them with connect():

// actions.js

function showNotification(id, text) {
  return { type: 'SHOW_NOTIFICATION', id, text }
}
function hideNotification(id) {
  return { type: 'HIDE_NOTIFICATION', id }
}

let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
  return function (dispatch) {
    const id = nextNotificationId++
    dispatch(showNotification(id, text))

    setTimeout(() => {
      dispatch(hideNotification(id))
    }, 5000)
  }
}

// component.js

import { connect } from 'react-redux'

// ...

this.props.showNotificationWithTimeout('You just logged in.')

// ...

export default connect(
  mapStateToProps,
  { showNotificationWithTimeout }
)(MyComponent)

Reading State in Thunks

Usually your reducers contain the business logic for determining the next state. However, reducers only kick in after the actions are dispatched. What if you have a side effect (such as calling an API) in a thunk action creator, and you want to prevent it under some condition?

Without using the thunk middleware, you’d just do this check inside the component:

// component.js
if (this.props.areNotificationsEnabled) {
  showNotificationWithTimeout(this.props.dispatch, 'You just logged in.')
}

However, the point of extracting an action creator was to centralize this repetitive logic across many components. Fortunately, Redux Thunk offers you a way to read the current state of the Redux store. In addition to dispatch, it also passes getState as the second argument to the function you return from your thunk action creator. This lets the thunk read the current state of the store.

let nextNotificationId = 0
export function showNotificationWithTimeout(text) {
  return function (dispatch, getState) {
    // Unlike in a regular action creator, we can exit early in a thunk
    // Redux doesn’t care about its return value (or lack of it)
    if (!getState().areNotificationsEnabled) {
      return
    }

    const id = nextNotificationId++
    dispatch(showNotification(id, text))

    setTimeout(() => {
      dispatch(hideNotification(id))
    }, 5000)
  }
}

Don’t abuse this pattern. It is good for bailing out of API calls when there is cached data available, but it is not a very good foundation to build your business logic upon. If you use getState() only to conditionally dispatch different actions, consider putting the business logic into the reducers instead.

Next Steps

Now that you have a basic intuition about how thunks work, check out Redux async example which uses them.

You may find many examples in which thunks return Promises. This is not required but can be very convenient. Redux doesn’t care what you return from a thunk, but it gives you its return value from dispatch(). This is why you can return a Promise from a thunk and wait for it to complete by calling dispatch(someThunkReturningPromise()).then(...).

You may also split complex thunk action creators into several smaller thunk action creators. The dispatch method provided by thunks can accept thunks itself, so you can apply the pattern recursively. Again, this works best with Promises because you can implement asynchronous control flow on top of that.

For some apps, you may find yourself in a situation where your asynchronous control flow requirements are too complex to be expressed with thunks. For example, retrying failed requests, reauthorization flow with tokens, or a step-by-step onboarding can be too verbose and error-prone when written this way. In this case, you might want to look at more advanced asynchronous control flow solutions such as Redux Saga or Redux Loop. Evaluate them, compare the examples relevant to your needs, and pick the one you like the most.

Finally, don’t use anything (including thunks) if you don’t have the genuine need for them. Remember that, depending on the requirements, your solution might look as simple as

store.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' })
setTimeout(() => {
  store.dispatch({ type: 'HIDE_NOTIFICATION' })
}, 5000)

Don’t sweat it unless you know why you’re doing this.

Why does an SSH remote command get fewer environment variables then when run manually?

How about sourcing the profile before running the command?

ssh user@host "source /etc/profile; /path/script.sh"

You might find it best to change that to ~/.bash_profile, ~/.bashrc, or whatever.

(As here (linuxquestions.org))

python - checking odd/even numbers and changing outputs on number size

Modulus method is the usual method. We can also do this to check if odd or even:

def f(a):
    if (a//2)*2 == a:
        return 'even'
    else:
        return 'odd'

Integer division by 2 followed by multiplication by two.

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

How to push elements in JSON from javascript array

If you want to stick with the way you're populating the values array, you can then assign this array like so:

BODY.values = values;

after the loop.

It should look like this:

var BODY = {
    "recipients": {
      "values": [
     ]
    },
   "subject": title,
   "body": message
}

var values = [];
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
    "person": {
            "_path": "/people/"+names[ln],
            },
};
values.push(item1);
}
BODY.values = values;
alert(BODY);

JSON.stringify() will be useful once you pass it as parameter for an AJAX call. Remember: the values array in your BODY object is different from the var values = []. You must assign that outer values[] to BODY.values. This is one of the good things about OOP.

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

in JDK 8, jdbc odbc bridge is no longer used and thus removed fro the JDK. to use Microsoft Access database in JAVA, you need 5 extra JAR libraries.

1- hsqldb.jar

2- jackcess 2.0.4.jar

3- commons-lang-2.6.jar

4- commons-logging-1.1.1.jar

5- ucanaccess-2.0.8.jar

add these libraries to your java project and start with following lines.

Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<Path to your database i.e. MS Access DB>");
Statement s = conn.createStatement();

path could be like E:/Project/JAVA/DBApp

and then your query to be executed. Like

ResultSet rs = s.executeQuery("SELECT * FROM Course");
while(rs.next())
    System.out.println(rs.getString("Title") + " " + rs.getString("Code") + " " + rs.getString("Credits"));

certain imports to be used. try catch block must be used and some necessary things no to be forgotten.

Remember, no need of bridging drivers like jdbc odbc or any stuff.

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

How to convert string to char array in C++?

You could use strcpy(), like so:

strcpy(tab2, tmp.c_str());

Watch out for buffer overflow.

NLTK and Stopwords Fail #lookuperror

import nltk

nltk.download()

  • A GUI pops up and in that go the Corpora section, select the required corpus.
  • Verified Result

PHP CSV string to array

Try this, it's working for me:

$delimiter = ",";
  $enclosure = '"';
  $escape = "\\" ;
  $rows = array_filter(explode(PHP_EOL, $content));
  $header = NULL;
  $data = [];

  foreach($rows as $row)
  {
    $row = str_getcsv ($row, $delimiter, $enclosure , $escape);

    if(!$header) {
      $header = $row;
    } else {
      $data[] = array_combine($header, $row);
    }
  }

UML diagram shapes missing on Visio 2013

Microsoft Visio 2013 Standard Edition does not provide UML shapes, you have to upgrade to Microsoft Visio 2013 Professional.

Visio 2013 Professional

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

How to get all values from python enum class?

Based on the answer by @Jeff, refactored to use a classmethod so that you can reuse the same code for any of your enums:

from enum import Enum

class ExtendedEnum(Enum):

    @classmethod
    def list(cls):
        return list(map(lambda c: c.value, cls))

class OperationType(ExtendedEnum):
    CREATE = 'CREATE'
    STATUS = 'STATUS'
    EXPAND = 'EXPAND'
    DELETE = 'DELETE'

print(OperationType.list())

Produces:

['CREATE', 'STATUS', 'EXPAND', 'DELETE']

How to set web.config file to show full error message

If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

Regular expression to remove HTML tags from a string

You should not attempt to parse HTML with regex. HTML is not a regular language, so any regex you come up with will likely fail on some esoteric edge case. Please refer to the seminal answer to this question for specifics. While mostly formatted as a joke, it makes a very good point.


The following examples are Java, but the regex will be similar -- if not identical -- for other languages.


String target = someString.replaceAll("<[^>]*>", "");

Assuming your non-html does not contain any < or > and that your input string is correctly structured.

If you know they're a specific tag -- for example you know the text contains only <td> tags, you could do something like this:

String target = someString.replaceAll("(?i)<td[^>]*>", "");

Edit: Omega brought up a good point in a comment on another post that this would result in multiple results all being squished together if there were multiple tags.

For example, if the input string were <td>Something</td><td>Another Thing</td>, then the above would result in SomethingAnother Thing.

In a situation where multiple tags are expected, we could do something like:

String target = someString.replaceAll("(?i)<td[^>]*>", " ").replaceAll("\\s+", " ").trim();

This replaces the HTML with a single space, then collapses whitespace, and then trims any on the ends.

bash: shortest way to get n-th column of output

It looks like you already have a solution. To make things easier, why not just put your command in a bash script (with a short name) and just run that instead of typing out that 'long' command every time?

Where can I find "make" program for Mac OS X Lion?

You need to install Xcode from App Store.

Then start Xcode, go to Xcode->Preferences->Downloads and install component named "Command Line Tools". After that all the relevant tools will be placed in /usr/bin folder and you will be able to use it just as it was in 10.6.

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

What's the best way to check if a file exists in C?

FILE *file;
    if((file = fopen("sample.txt","r"))!=NULL)
        {
            // file exists
            fclose(file);
        }
    else
        {
            //File not found, no memory leak since 'file' == NULL
            //fclose(file) would cause an error
        }

/** and /* in Java Comments

I don't think the existing answers adequately addressed this part of the question:

When should I use them?

If you're writing an API that will be published or reused within your organization, you should write comprehensive Javadoc comments for every public class, method, and field, as well as protected methods and fields of non-final classes. Javadoc should cover everything that cannot be conveyed by the method signature, such as preconditions, postconditions, valid arguments, runtime exceptions, internal calls, etc.

If you're writing an internal API (one that's used by different parts of the same program), Javadoc is arguably less important. But for the benefit of maintenance programmers, you should still write Javadoc for any method or field where the correct usage or meaning is not immediately obvious.

The "killer feature" of Javadoc is that it's closely integrated with Eclipse and other IDEs. A developer only needs to hover their mouse pointer over an identifier to learn everything they need to know about it. Constantly referring to the documentation becomes second nature for experienced Java developers, which improves the quality of their own code. If your API isn't documented with Javadoc, experienced developers will not want to use it.

Disable single warning error

Example:

#pragma warning(suppress:0000)  // (suppress one error in the next line)

This pragma is valid for C++ starting with Visual Studio 2005.
https://msdn.microsoft.com/en-us/library/2c8f766e(v=vs.80).aspx

The pragma is NOT valid for C# through Visual Studio 2005 through Visual Studio 2015.
Error: "Expected disable or restore".
(I guess they never got around to implementing suppress ...)
https://msdn.microsoft.com/en-us/library/441722ys(v=vs.140).aspx

C# needs a different format. It would look like this (but not work):

#pragma warning suppress 0642  // (suppress one error in the next line)

Instead of suppress, you have to disable and enable:

if (condition)
#pragma warning disable 0642
    ;  // Empty statement HERE provokes Warning: "Possible mistaken empty statement" (CS0642)
#pragma warning restore 0642
else

That is SO ugly, I think it is smarter to just re-style it:

if (condition)
{
    // Do nothing (because blah blah blah).
}
else

How to find elements by class

Specific to BeautifulSoup 3:

soup.findAll('div',
             {'class': lambda x: x 
                       and 'stylelistrow' in x.split()
             }
            )

Will find all of these:

<div class="stylelistrow">
<div class="stylelistrow button">
<div class="button stylelistrow">

Is there a way to make npm install (the command) to work behind proxy?

This worked for me-

npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080
npm set strict-ssl=false

Custom Python list sorting

Just like this example. You want sort this list.

[('c', 2), ('b', 2), ('a', 3)]

output:

[('a', 3), ('b', 2), ('c', 2)]

you should sort the tuples by the second item, then the first:

def letter_cmp(a, b):
    if a[1] > b[1]:
        return -1
    elif a[1] == b[1]:
        if a[0] > b[0]:
            return 1
        else:
            return -1
    else:
        return 1

Then convert it to a key function:

from functools import cmp_to_key
letter_cmp_key = cmp_to_key(letter_cmp))

Now you can use your custom sort order:

[('c', 2), ('b', 2), ('a', 3)].sort(key=letter_cmp_key)

How to make popup look at the centre of the screen?

In order to get the popup exactly centered, it's a simple matter of applying a negative top margin of half the div height, and a negative left margin of half the div width. For this example, like so:

.div {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 50%;
}

Remove an entire column from a data.frame in R

(For completeness) If you want to remove columns by name, you can do this:

cols.dont.want <- "genome"
cols.dont.want <- c("genome", "region") # if you want to remove multiple columns

data <- data[, ! names(data) %in% cols.dont.want, drop = F]

Including drop = F ensures that the result will still be a data.frame even if only one column remains.

Reliable way for a Bash script to get the full path to itself

The accepted solution has the inconvenient (for me) to not be "source-able":
if you call it from a "source ../../yourScript", $0 would be "bash"!

The following function (for bash >= 3.0) gives me the right path, however the script might be called (directly or through source, with an absolute or a relative path):
(by "right path", I mean the full absolute path of the script being called, even when called from another path, directly or with "source")

#!/bin/bash
echo $0 executed

function bashscriptpath() {
  local _sp=$1
  local ascript="$0"
  local asp="$(dirname $0)"
  #echo "b1 asp '$asp', b1 ascript '$ascript'"
  if [[ "$asp" == "." && "$ascript" != "bash" && "$ascript" != "./.bashrc" ]] ; then asp="${BASH_SOURCE[0]%/*}"
  elif [[ "$asp" == "." && "$ascript" == "./.bashrc" ]] ; then asp=$(pwd)
  else
    if [[ "$ascript" == "bash" ]] ; then
      ascript=${BASH_SOURCE[0]}
      asp="$(dirname $ascript)"
    fi  
    #echo "b2 asp '$asp', b2 ascript '$ascript'"
    if [[ "${ascript#/}" != "$ascript" ]]; then asp=$asp ;
    elif [[ "${ascript#../}" != "$ascript" ]]; then
      asp=$(pwd)
      while [[ "${ascript#../}" != "$ascript" ]]; do
        asp=${asp%/*}
        ascript=${ascript#../}
      done
    elif [[ "${ascript#*/}" != "$ascript" ]];  then
      if [[ "$asp" == "." ]] ; then asp=$(pwd) ; else asp="$(pwd)/${asp}"; fi
    fi  
  fi  
  eval $_sp="'$asp'"
}

bashscriptpath H
export H=${H}

The key is to detect the "source" case and to use ${BASH_SOURCE[0]} to get back the actual script.

$("#form1").validate is not a function

I had this issue, jquery URL was valid, everything looked good and validation still worked. After a hard refresh CTL+F5 the error went away in Chrome.

How to get client's IP address using JavaScript?

One problem with some of the other services I've seen here is that they either do not support IPv6, or they act unpredictably in the presence of IPv6.

Because I needed this capability myself in a dual stack environment, I put together my own IP address service, which you can find at http://myip.addr.space/ . There's also a quick reference at /help.

To use it with jQuery, use the /ip endpoint. You will get back plain text containing the IP address, depending on the subdomain you use:

$.get("http://myip.addr.space/ip") returns either IPv6 or IPv4, depending on what is available to the system. (JSFiddle)

$.get("http://ipv4.myip.addr.space/ip") always returns IPv4 (or fails if no IPv4).

$.get("http://ipv6.myip.addr.space/ip") always returns IPv6 (or fails if no IPv6).

C# ASP.NET Single Sign-On Implementation

There are several Identity providers with SSO support out of the box, also third-party** products.

** The only problem with third party products is that they charge per user/month, and it can be quite expensive.

Some of the tools available and with APIs for .NET are:

If you decide to go with your own implementation, you could use the frameworks below categorized by programming language.

  • C#

    • IdentityServer3 (OAuth/OpenID protocols, OWIN/Katana)
    • IdentityServer4 (OAuth/OpenID protocols, ASP.NET Core)
    • OAuth 2.0 by Okta
  • Javascript

    • passport-openidconnect (node.js)
    • oidc-provider (node.js)
    • openid-client (node.js)
  • Python

    • pyoidc
    • Django OIDC Provider

I would go with IdentityServer4 and ASP.NET Core application, it's easy configurable and you can also add your own authentication provider. It uses OAuth/OpenID protocols which are newer than SAML 2.0 and WS-Federation.

Linq code to select one item

I'll tell you what worked for me:

int id = int.Parse(insertItem.OwnerTableView.DataKeyValues[insertItem.ItemIndex]["id_usuario"].ToString());

var query = user.First(x => x.id_usuario == id);
tbUsername.Text = query.username;
tbEmail.Text = query.email;
tbPassword.Text = query.password;

My id is the row I want to query, in this case I got it from a radGrid, then I used it to query, but this query returns a row, then you can assign the values you got from the query to textbox, or anything, I had to assign those to textbox.

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

How can I extract all values from a dictionary in Python?

Pythonic duck-typing should in principle determine what an object can do, i.e., its properties and methods. By looking at a dictionary object one may try to guess it has at least one of the following: dict.keys() or dict.values() methods. You should try to use this approach for future work with programming languages whose type checking occurs at runtime, especially those with the duck-typing nature.

Align two inline-blocks left and right on same line

Taking advantage of @skip405's answer, I've made a Sass mixin for it:

@mixin inline-block-lr($container,$left,$right){
    #{$container}{        
        text-align: justify; 

        &:after{
            content: '';
            display: inline-block;
            width: 100%;
            height: 0;
            font-size:0;
            line-height:0;
        }
    }

    #{$left} {
        display: inline-block;
        vertical-align: middle; 
    }

    #{$right} {
        display: inline-block;
        vertical-align: middle; 
    }
}

It accepts 3 parameters. The container, the left and the right element. For example, to fit the question, you could use it like this:

@include inline-block-lr('header', 'h1', 'nav');

Python sum() function with list parameter

In the last answer, you don't need to make a list from numbers; it is already a list:

numbers = [1, 2, 3]
numsum = sum(numbers)
print(numsum)

Possible heap pollution via varargs parameter

The reason is because varargs give the option of being called with a non-parametrized object array. So if your type was List < A > ... , it can also be called with List[] non-varargs type.

Here is an example:

public static void testCode(){
    List[] b = new List[1];
    test(b);
}

@SafeVarargs
public static void test(List<A>... a){
}

As you can see List[] b can contain any type of consumer, and yet this code compiles. If you use varargs, then you are fine, but if you use the method definition after type-erasure - void test(List[]) - then the compiler will not check the template parameter types. @SafeVarargs will suppress this warning.

Image UriSource and Data Binding

you may use

ImageSourceConverter class

to get what you want

    img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("/Assets/check.png");

Laravel 5 - redirect to HTTPS

This is for Larave 5.2.x and greater. If you want to have an option to serve some content over HTTPS and others over HTTP here is a solution that worked for me. You may wonder, why would someone want to serve only some content over HTTPS? Why not serve everything over HTTPS?

Although, it's totally fine to serve the whole site over HTTPS, severing everything over HTTPS has an additional overhead on your server. Remember encryption doesn't come cheap. The slight overhead also has an impact on your app response time. You could argue that commodity hardware is cheap and the impact is negligible but I digress :) I don't like the idea of serving marketing content big pages with images etc over https. So here it goes. It's similar to what others have suggest above using middleware but it's a full solution that allows you to toggle back and forth between HTTP/HTTPS.

First create a middleware.

php artisan make:middleware ForceSSL

This is what your middleware should look like.

<?php

namespace App\Http\Middleware;

use Closure;

class ForceSSL
{

    public function handle($request, Closure $next)
    {

        if (!$request->secure()) {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}

Note that I'm not filtering based on environment because I have HTTPS setup for both local dev and production so there is not need to.

Add the following to your routeMiddleware \App\Http\Kernel.php so that you can pick and choose which route group should force SSL.

    protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'forceSSL' => \App\Http\Middleware\ForceSSL::class,
];

Next, I'd like to secure two basic groups login/signup etc and everything else behind Auth middleware.

Route::group(array('middleware' => 'forceSSL'), function() {
/*user auth*/
Route::get('login', 'AuthController@showLogin');
Route::post('login', 'AuthController@doLogin');

// Password reset routes...
Route::get('password/reset/{token}', 'Auth\PasswordController@getReset');
Route::post('password/reset', 'Auth\PasswordController@postReset');

//other routes like signup etc

});


Route::group(['middleware' => ['auth','forceSSL']], function()
 {
Route::get('dashboard', function(){
    return view('app.dashboard');
});
Route::get('logout', 'AuthController@doLogout');

//other routes for your application
});

Confirm that your middlewares are applied to your routes properly from console.

php artisan route:list

Now you have secured all the forms or sensitive areas of your application, the key now is to use your view template to define your secure and public (non https) links.

Based on the example above you would render your secure links as follows -

<a href="{{secure_url('/login')}}">Login</a>
<a href="{{secure_url('/signup')}}">SignUp</a>

Non secure links can be rendered as

<a href="{{url('/aboutus',[],false)}}">About US</a></li>
<a href="{{url('/promotion',[],false)}}">Get the deal now!</a></li>

What this does is renders a fully qualified URL such as https://yourhost/login and http://yourhost/aboutus

If you were not render fully qualified URL with http and use a relative link url('/aboutus') then https would persists after a user visits a secure site.

Hope this helps!

jquery/javascript convert date string to date

If you're running with jQuery you can use the datepicker UI library's parseDate function to convert your string to a date:

var d = $.datepicker.parseDate("DD, MM dd, yy",  "Sunday, February 28, 2010");

and then follow it up with the formatDate method to get it to the string format you want

var datestrInNewFormat = $.datepicker.formatDate( "mm/dd/yy", d);

If you're not running with jQuery of course its probably not the best plan given you'd need jQuery core as well as the datepicker UI module... best to go with the suggestion from Segfault above to use date.js.

HTH

How to Add Date Picker To VBA UserForm

You could try the "Microsoft Date and Time Picker Control". To use it, in the Toolbox, you right-click and choose "Additional Controls...". Then you check "Microsoft Date and Time Picker Control 6.0" and OK. You will have a new control in the Toolbox to do what you need.

I just found some printscreen of this on : http://www.logicwurks.com/CodeExamplePages/EDatePickerControl.html Forget the procedures, just check the printscreens.

fail to change placeholder color with Bootstrap 3

Assign the placeholder to a class selector like this:

.form-control::-webkit-input-placeholder { color: white; }  /* WebKit, Blink, Edge */
.form-control:-moz-placeholder { color: white; }  /* Mozilla Firefox 4 to 18 */
.form-control::-moz-placeholder { color: white; }  /* Mozilla Firefox 19+ */
.form-control:-ms-input-placeholder { color: white; }  /* Internet Explorer 10-11 */
.form-control::-ms-input-placeholder { color: white; }  /* Microsoft Edge */

It will work then since a stronger selector was probably overriding your global. I'm on a tablet so i cant inspect and confirm which stronger selector it was :) But it does work I tried it in your fiddle.

This also answers your second question. By assigning it to a class or id and giving an input only that class you can control what inputs to style.

How to check "hasRole" in Java Code with Spring Security?

You can retrieve the security context and then use that:

    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.context.SecurityContext;
    import org.springframework.security.core.context.SecurityContextHolder;

    protected boolean hasRole(String role) {
        // get security context from thread local
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null)
            return false;

        Authentication authentication = context.getAuthentication();
        if (authentication == null)
            return false;

        for (GrantedAuthority auth : authentication.getAuthorities()) {
            if (role.equals(auth.getAuthority()))
                return true;
        }

        return false;
    }

How to make Firefox headless programmatically in Selenium with Python?

The first answer does't work anymore.

This worked for me:

from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver

options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get("http://google.com")

References with text in LaTeX

I think you can do this with the hyperref package, although I've not tried it myself. From the relevant LaTeX Wikibook section:

The hyperref package introduces another useful command; \autoref{}. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command \autoref{sec:intro} would create a hyperlink to the \label{sec:intro} command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining \typeautorefname to the prefix you want, as in:

\def\subsectionautorefname{section}

How to start a background process in Python?

Both capture output and run on background with threading

As mentioned on this answer, if you capture the output with stdout= and then try to read(), then the process blocks.

However, there are cases where you need this. For example, I wanted to launch two processes that talk over a port between them, and save their stdout to a log file and stdout.

The threading module allows us to do that.

First, have a look at how to do the output redirection part alone in this question: Python Popen: Write to stdout AND log file simultaneously

Then:

main.py

#!/usr/bin/env python3

import os
import subprocess
import sys
import threading

def output_reader(proc, file):
    while True:
        byte = proc.stdout.read(1)
        if byte:
            sys.stdout.buffer.write(byte)
            sys.stdout.flush()
            file.buffer.write(byte)
        else:
            break

with subprocess.Popen(['./sleep.py', '0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc1, \
     subprocess.Popen(['./sleep.py', '10'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc2, \
     open('log1.log', 'w') as file1, \
     open('log2.log', 'w') as file2:
    t1 = threading.Thread(target=output_reader, args=(proc1, file1))
    t2 = threading.Thread(target=output_reader, args=(proc2, file2))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

sleep.py

#!/usr/bin/env python3

import sys
import time

for i in range(4):
    print(i + int(sys.argv[1]))
    sys.stdout.flush()
    time.sleep(0.5)

After running:

./main.py

stdout get updated every 0.5 seconds for every two lines to contain:

0
10
1
11
2
12
3
13

and each log file contains the respective log for a given process.

Inspired by: https://eli.thegreenplace.net/2017/interacting-with-a-long-running-child-process-in-python/

Tested on Ubuntu 18.04, Python 3.6.7.

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

In one of my projects there was a nuget packages with higher version of System.Net.Http. and in my startup project there reference to System.Net.Http v 4.0.0 , i just installed System.Net.Http nuget package in my startup project and the problem solved

How to get the seconds since epoch from the time + date output of gmtime()?

t = datetime.strptime('Jul 9, 2009 @ 20:02:58 UTC',"%b %d, %Y @ %H:%M:%S %Z")

Set timeout for ajax (jQuery)

You could use the timeout setting in the ajax options like this:

$.ajax({
    url: "test.html",
    timeout: 3000,
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});

Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/

Remember that when a timeout occurs, the error handler is triggered and not the success handler :)

Java 8 stream reverse order

How about this utility method?

public static <T> Stream<T> getReverseStream(List<T> list) {
    final ListIterator<T> listIt = list.listIterator(list.size());
    final Iterator<T> reverseIterator = new Iterator<T>() {
        @Override
        public boolean hasNext() {
            return listIt.hasPrevious();
        }

        @Override
        public T next() {
            return listIt.previous();
        }
    };
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
            reverseIterator,
            Spliterator.ORDERED | Spliterator.IMMUTABLE), false);
}

Seems to work with all cases without duplication.

How to make a .jar out from an Android Studio project

.jar file will be automatically generate when u compile/run your application.

You can find your class.jar file from root_folder/app/build/intermediates/bundles/debug

jar file location

"Unorderable types: int() < str()"

Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.

Run a JAR file from the command line and specify classpath

You can do these in unix shell:

java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

You can do these in windows powershell:

java -cp "MyJar.jar;lib\*" com.somepackage.subpackage.Main

SQL Server insert if not exists best practice

Additionally, if you have multiple columns to insert and want to check if they exists or not use the following code

Insert Into [Competitors] (cName, cCity, cState)
Select cName, cCity, cState from 
(
    select new.* from 
    (
        select distinct cName, cCity, cState 
        from [Competitors] s, [City] c, [State] s
    ) new
    left join 
    (   
        select distinct cName, cCity, cState 
        from [Competitors] s
    ) existing
    on new.cName = existing.cName and new.City = existing.City and new.State = existing.State
    where existing.Name is null  or existing.City is null or existing.State is null
)

Gerrit error when Change-Id in commit messages are missing

You need to follow below 2 steps instructions:

[Issue] remote: Hint: To automatically insert Change-Id, install the hook:

1) gitdir=$(git rev-parse --git-dir);

2) scp -p -P 29418 <username>@gerrit.xyz.se:hooks/commit-msg ${gitdir}/hooks/

normally $gitdir = ".git". You need to update the username and the Gerrit link.

How do I add an existing Solution to GitHub from Visual Studio 2013

OK this worked for me.

  1. Open the solution in Visual Studio 2013
  2. Select File | Add to Source Control
  3. Select the Microsoft Git Provider

That creates a local GIT repository

  1. Surf to GitHub
  2. Create a new repository DO NOT SELECT Initialize this repository with a README

That creates an empty repository with no Master branch

  1. Once created open the repository and copy the URL (it's on the right of the screen in the current version)
  2. Go back to Visual Studio
    • Make sure you have the Microsoft Git Provider selected under Tools/Options/Source Control/Plug-in Selection
  3. Open Team Explorer
  4. Select Home | Unsynced Commits
  5. Enter the GitHub URL into the yellow box (use HTTPS URL, not the default shown SSH one)
  6. Click Publish
  7. Select Home | Changes
  8. Add a Commit comment
  9. Select Commit and Push from the drop down

Your solution is now in GitHub

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

WAITING at sun.misc.Unsafe.park(Native Method)

I had a similar issue, and following previous answers (thanks!), I was able to search and find how to handle correctly the ThreadPoolExecutor terminaison.

In my case, that just fix my progressive increase of similar blocked threads:

  • I've used ExecutorService::awaitTermination(x, TimeUnit) and ExecutorService::shutdownNow() (if necessary) in my finally clause.
  • For information, I've used the following commands to detect thread count & list locked threads:

    ps -u javaAppuser -L|wc -l

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayA.log

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayAPlusOne.log

    cat threadPrint*.log |grep "pool-"|wc -l

Using HTML data-attribute to set CSS background-image url

You will need a little JavaScript for that:

var list = document.getElementsByClassName('thumb');

for (var i = 0; i < list.length; i++) {
  var src = list[i].getAttribute('data-image-src');
  list[i].style.backgroundImage="url('" + src + "')";
}

Wrap that in <script> tags at the bottom just before the </body> tag or wrap in a function that you call once the page loaded.

C++ variable has initializer but incomplete type?

I got a similar error and hit this page while searching the solution.

With Qt this error can happen if you forget to add the QT_WRAP_CPP( ... ) step in your build to run meta object compiler (moc). Including the Qt header is not sufficient.

Where are shared preferences stored?

I just tried to get path of shared preferences below like this.This is work for me.

File f = getDatabasePath("MyPrefsFile.xml");

if (f != null)
    Log.i("TAG", f.getAbsolutePath());

Java SSLException: hostname in certificate didn't match

Thanks Vineet Reynolds. The link you provided held a lot of user comments - one of which I tried in desperation and it helped. I added this method :

// Do not do this in production!!!
HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
    public boolean verify(String string,SSLSession ssls) {
        return true;
    }
});

This seems fine for me now, though I know this solution is temporary. I am working with the network people to identify why my hosts file is being ignored.

SQL Server, division returns zero

if you declare it as float or any decimal format it will display

0

only

E.g :

declare @weight float;

SET @weight= 47 / 638; PRINT @weight

Output : 0

If you want the output as

0.073667712

E.g

declare @weight float;

SET @weight= 47.000000000 / 638.000000000; PRINT @weight

What is the difference between Integrated Security = True and Integrated Security = SSPI?

Many questions get answers if we use .Net Reflector to see the actual code of SqlConnection :) true and sspi are the same:

internal class DbConnectionOptions

...

internal bool ConvertValueToIntegratedSecurityInternal(string stringValue)
{
    if ((CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true")) || CompareInsensitiveInvariant(stringValue, "yes"))
    {
        return true;
    }
}

...

EDIT 20.02.2018 Now in .Net Core we can see its open source on github! Search for ConvertValueToIntegratedSecurityInternal method:

https://github.com/dotnet/corefx/blob/fdbb160aeb0fad168b3603dbdd971d568151a0c8/src/System.Data.SqlClient/src/System/Data/Common/DbConnectionOptions.cs

error opening trace file: No such file or directory (2)

I think this is the problem

A little background

Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance. Enabling it creates a .trace file in the sdcard root folder which can then be extracted by ADB and processed by traceview bat file for processing. It also can get added by the DDMS.

It is a system used internally by the logger. In general unless you are using traceview to extract the trace file this error shouldnt bother you. You should look at error/logs directly related to your application

How do I enable it:

There are two ways to generate trace logs:

  1. Include the Debug class in your code and call its methods such as startMethodTracing() and stopMethodTracing(), to start and stop logging of trace information to disk. This option is very precise because you can specify exactly where to start and stop logging trace data in your code.

  2. Use the method profiling feature of DDMS to generate trace logs. This option is less precise because you do not modify code, but rather specify when to start and stop logging with DDMS. Although you have less control on exactly where logging starts and stops, this option is useful if you don't have access to the application's code, or if you do not need precise log timing.

But the following restrictions exist for the above

If you are using the Debug class, your application must have permission to write to external storage (WRITE_EXTERNAL_STORAGE).

If you are using DDMS: Android 2.1 and earlier devices must have an SD card present and your application must have permission to write to the SD card. Android 2.2 and later devices do not need an SD card. The trace log files are streamed directly to your development machine.

So in essence the traceFile access requires two things

1.) Permission to write a trace log file i.e. WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE for good measure

2.) An emulator with an SDCard attached with sufficient space. The doc doesnt say if this is only for DDMS but also for debug, so I am assuming this is also true for debugging via the application.

What do I do with this error:

Now the error is essentially a fall out of either not having the sdcard path to create a tracefile or not having permission to access it. This is an old thread, but the dev behind the bounty, check if are meeting the two prerequisites. You can then go search for the .trace file in the sdcard folder in your emulator. If it exists it shouldn't be giving you this problem, if it doesnt try creating it by adding the startMethodTracing to your app.
I'm not sure why it automatically looks for this file when the logger kicks in. I think when an error/log event occurs , the logger internally tries to write to trace file and does not find it, in which case it throws the error.Having scoured through the docs, I don't find too many references to why this is automatically on. But in general this doesn't affect you directly, you should check direct application logs/errors. Also as an aside Android 2.2 and later devices do not need an SD card for DDMS trace logging. The trace log files are streamed directly to your development machine.

Additional information on Traceview:

Copying Trace Files to a Host Machine

After your application has run and the system has created your trace files .trace on a device or emulator, you must copy those files to your development computer. You can use adb pull to copy the files. Here's an example that shows how to copy an example file, calc.trace, from the default location on the emulator to the /tmp directory on the emulator host machine:

adb pull /sdcard/calc.trace /tmp Viewing Trace Files in Traceview To run Traceview and view the trace files, enter traceview . For example, to run Traceview on the example files copied in the previous section, use:

traceview /tmp/calc Note: If you are trying to view the trace logs of an application that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated. You can use the Proguard mapping.txt file to figure out the original unobfuscated names. For more information on this file, see the Proguard documentation.

I think any other answer regarding positioning of oncreate statements or removing uses-sdk are not related, but this is Android and I could be wrong. Would be useful to redirect this question to an android engineer or post it as a bug

More in the docs

Remove '\' char from string c#

Try using

String sOld = ...;
String sNew =     sOld.Replace("\\", String.Empty);

Using Python 3 in virtualenv

I had the same ERROR message. tbrisker's solution did not work in my case. Instead this solved the issue:

$ python3 -m venv .env

Foreign key constraint may cause cycles or multiple cascade paths?

This is an error of type database trigger policies. A trigger is code and can add some intelligences or conditions to a Cascade relation like Cascade Deletion. You may need to specialize the related tables options around this like Turning off CascadeOnDelete:

protected override void OnModelCreating( DbModelBuilder modelBuilder )
{
    modelBuilder.Entity<TableName>().HasMany(i => i.Member).WithRequired().WillCascadeOnDelete(false);
}

Or Turn off this feature completely:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

How do I remove blue "selected" outline on buttons?

You can remove the blue outline by using outline: none.

However, I would highly recommend styling your focus states too. This is to help users who are visually impaired.

Check out: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#navigation-mechanisms-focus-visible. More reading here: http://outlinenone.com

Get the Highlighted/Selected text

Yes you can do it with simple JavaScript snippet:

document.addEventListener('mouseup', event => {  
    if(window.getSelection().toString().length){
       let exactText = window.getSelection().toString();        
    }
}

How do I keep CSS floats in one line?

Are you sure that floated block-level elements are the best solution to this problem?

Often with CSS difficulties in my experience it turns out that the reason I can't see a way of doing the thing I want is that I have got caught in a tunnel-vision with regard to my markup ( thinking "how can I make these elements do this?" ) rather than going back and looking at what exactly it is I need to achieve and maybe reworking my html slightly to facilitate that.

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

The short-circuiting boolean operators (and, or) can't be overriden because there is no satisfying way to do this without introducing new language features or sacrificing short circuiting. As you may or may not know, they evaluate the first operand for its truth value, and depending on that value, either evaluate and return the second argument, or don't evaluate the second argument and return the first:

something_true and x -> x
something_false and x -> something_false
something_true or x -> something_true
something_false or x -> x

Note that the (result of evaluating the) actual operand is returned, not truth value thereof.

The only way to customize their behavior is to override __nonzero__ (renamed to __bool__ in Python 3), so you can affect which operand gets returned, but not return something different. Lists (and other collections) are defined to be "truthy" when they contain anything at all, and "falsey" when they are empty.

NumPy arrays reject that notion: For the use cases they aim at, two different notions of truth are common: (1) Whether any element is true, and (2) whether all elements are true. Since these two are completely (and silently) incompatible, and neither is clearly more correct or more common, NumPy refuses to guess and requires you to explicitly use .any() or .all().

& and | (and not, by the way) can be fully overriden, as they don't short circuit. They can return anything at all when overriden, and NumPy makes good use of that to do element-wise operations, as they do with practically any other scalar operation. Lists, on the other hand, don't broadcast operations across their elements. Just as mylist1 - mylist2 doesn't mean anything and mylist1 + mylist2 means something completely different, there is no & operator for lists.

"Input string was not in a correct format."

I had a similar problem that I solved with the following technique:

The exception was thrown at the following line of code (see the text decorated with ** below):

static void Main(string[] args)
    {

        double number = 0;
        string numberStr = string.Format("{0:C2}", 100);

        **number = Double.Parse(numberStr);**

        Console.WriteLine("The number is {0}", number);
    }

After a bit of investigating, I realized that the problem was that the formatted string included a dollar sign ($) that the Parse/TryParse methods cannot resolve (i.e. - strip off). So using the Remove(...) method of the string object I changed the line to:

number = Double.Parse(numberStr.Remove(0, 1)); // Remove the "$" from the number

At that point the Parse(...) method worked as expected.

Best C++ IDE or Editor for Windows

SlickEdit is very cool, and does support something like intellisense. At my current company I now use Visual Studio, and I've mostly gotten used to it - but there are still some SlickEdit features I miss.

How to set cookies in laravel 5 independently inside controller

Here is a sample code with explanation.

 //Create a response instance
 $response = new Illuminate\Http\Response('Hello World');

 //Call the withCookie() method with the response method
 $response->withCookie(cookie('name', 'value', $minutes));

 //return the response
 return $response;

Cookie can be set forever by using the forever method as shown in the below code.

$response->withCookie(cookie()->forever('name', 'value'));

Retrieving a Cookie

//’name’ is the name of the cookie to retrieve the value of
$value = $request->cookie('name');

window.location.reload with clear cache

You can do this a few ways. One, simply add this meta tag to your head:

<meta http-equiv="Cache-control" content="no-cache">

If you want to remove the document from cache, expires meta tag should work to delete it by setting its content attribute to -1 like so:

<meta http-equiv="Expires" content="-1">

http://www.metatags.org/meta_http_equiv_cache_control

Also, IE should give you the latest content for the main page. If you are having issues with external documents, like CSS and JS, add a dummy param at the end of your URLs with the current time in milliseconds so that it's never the same. This way IE, and other browsers, will always serve you the latest version. Here is an example:

<script src="mysite.com/js/myscript.js?12345">

UPDATE 1

After reading the comments I realize you wanted to programmatically erase the cache and not every time. What you could do is have a function in JS like:

eraseCache(){
  window.location = window.location.href+'?eraseCache=true';
}

Then, in PHP let's say, you do something like this:

<head>
<?php
    if (isset($_GET['eraseCache'])) {
        echo '<meta http-equiv="Cache-control" content="no-cache">';
        echo '<meta http-equiv="Expires" content="-1">';
        $cache = '?' . time();
    }
?>
<!-- ... other head HTML -->
<script src="mysite.com/js/script.js<?= $cache ?>"
</head>

This isn't tested, but should work. Basically, your JS function, if invoked, will reload the page, but adds a GET param to the end of the URL. Your site would then have some back-end code that looks for this param. If it exists, it adds the meta tags and a cache variable that contains a timestamp and appends it to the scripts and CSS that you are having caching issues with.

UPDATE 2

The meta tag indeed won't erase the cache on page load. So, technically you would need to run the eraseCache function in JS, once the page loads, you would need to load it again for the changes to take place. You should be able to fix this with your server side language. You could run the same eraseCache JS function, but instead of adding the meta tags, you need to add HTTP Cache headers:

<?php
    header("Cache-Control: no-cache, must-revalidate");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
?>
<!-- Here you'd start your page... -->

This method works immediately without the need for page reload because it erases the cache before the page loads and also before anything is run.

How do I use regex in a SQLite query?

A SQLite UDF in PHP/PDO for the REGEXP keyword that mimics the behavior in MySQL:

$pdo->sqliteCreateFunction('regexp',
    function ($pattern, $data, $delimiter = '~', $modifiers = 'isuS')
    {
        if (isset($pattern, $data) === true)
        {
            return (preg_match(sprintf('%1$s%2$s%1$s%3$s', $delimiter, $pattern, $modifiers), $data) > 0);
        }

        return null;
    }
);

The u modifier is not implemented in MySQL, but I find it useful to have it by default. Examples:

SELECT * FROM "table" WHERE "name" REGEXP 'sql(ite)*';
SELECT * FROM "table" WHERE regexp('sql(ite)*', "name", '#', 's');

If either $data or $pattern is NULL, the result is NULL - just like in MySQL.

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

MySQL parameterized queries

Beware of using string interpolation for SQL queries, since it won't escape the input parameters correctly and will leave your application open to SQL injection vulnerabilities. The difference might seem trivial, but in reality it's huge.

Incorrect (with security issues)

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s" % (param1, param2))

Correct (with escaping)

c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))

It adds to the confusion that the modifiers used to bind parameters in a SQL statement varies between different DB API implementations and that the mysql client library uses printf style syntax instead of the more commonly accepted '?' marker (used by eg. python-sqlite).

Append TimeStamp to a File Name

you can use:

Stopwatch.GetTimestamp();

.NET - How do I retrieve specific items out of a Dataset?

The DataSet object has a Tables array. If you know the table you want, it will have a Row array, each object of which has an ItemArray array. In your case the code would most likely be

int var1 = int.Parse(ds.Tables[0].Rows[0].ItemArray[4].ToString());

and so forth. This would give you the 4th item in the first row. You can also use Columns instead of ItemArray and specify the column name as a string instead of remembering it's index. That approach can be easier to keep up with if the table structure changes. So that would be

int var1 = int.Parse(ds.Tables[0].Rows[0]["MyColumnName"].ToString());

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use a simple regex like this:

public static string StripHTML(string input)
{
   return Regex.Replace(input, "<.*?>", String.Empty);
}

Be aware that this solution has its own flaw. See Remove HTML tags in String for more information (especially the comments of @mehaase)

Another solution would be to use the HTML Agility Pack.
You can find an example using the library here: HTML agility pack - removing unwanted tags without removing content?

Save each sheet in a workbook to separate CSV files

Here is one that will give you a visual file chooser to pick the folder you want to save the files to and also lets you choose the CSV delimiter (I use pipes '|' because my fields contain commas and I don't want to deal with quotes):

' ---------------------- Directory Choosing Helper Functions -----------------------
' Excel and VBA do not provide any convenient directory chooser or file chooser
' dialogs, but these functions will provide a reference to a system DLL
' with the necessary capabilities
Private Type BROWSEINFO    ' used by the function GetFolderName
    hOwner As Long
    pidlRoot As Long
    pszDisplayName As String
    lpszTitle As String
    ulFlags As Long
    lpfn As Long
    lParam As Long
    iImage As Long
End Type

Private Declare Function SHGetPathFromIDList Lib "shell32.dll" _
                                             Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Private Declare Function SHBrowseForFolder Lib "shell32.dll" _
                                           Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long

Function GetFolderName(Msg As String) As String
    ' returns the name of the folder selected by the user
    Dim bInfo As BROWSEINFO, path As String, r As Long
    Dim X As Long, pos As Integer
    bInfo.pidlRoot = 0&    ' Root folder = Desktop
    If IsMissing(Msg) Then
        bInfo.lpszTitle = "Select a folder."
        ' the dialog title
    Else
        bInfo.lpszTitle = Msg    ' the dialog title
    End If
    bInfo.ulFlags = &H1    ' Type of directory to return
    X = SHBrowseForFolder(bInfo)    ' display the dialog
    ' Parse the result
    path = Space$(512)
    r = SHGetPathFromIDList(ByVal X, ByVal path)
    If r Then
        pos = InStr(path, Chr$(0))
        GetFolderName = Left(path, pos - 1)
    Else
        GetFolderName = ""
    End If
End Function
'---------------------- END Directory Chooser Helper Functions ----------------------

Public Sub DoTheExport()
    Dim FName As Variant
    Dim Sep As String
    Dim wsSheet As Worksheet
    Dim nFileNum As Integer
    Dim csvPath As String


    Sep = InputBox("Enter a single delimiter character (e.g., comma or semi-colon)", _
                   "Export To Text File")
    'csvPath = InputBox("Enter the full path to export CSV files to: ")

    csvPath = GetFolderName("Choose the folder to export CSV files to:")
    If csvPath = "" Then
        MsgBox ("You didn't choose an export directory. Nothing will be exported.")
        Exit Sub
    End If

    For Each wsSheet In Worksheets
        wsSheet.Activate
        nFileNum = FreeFile
        Open csvPath & "\" & _
             wsSheet.Name & ".csv" For Output As #nFileNum
        ExportToTextFile CStr(nFileNum), Sep, False
        Close nFileNum
    Next wsSheet

End Sub



Public Sub ExportToTextFile(nFileNum As Integer, _
                            Sep As String, SelectionOnly As Boolean)

    Dim WholeLine As String
    Dim RowNdx As Long
    Dim ColNdx As Integer
    Dim StartRow As Long
    Dim EndRow As Long
    Dim StartCol As Integer
    Dim EndCol As Integer
    Dim CellValue As String

    Application.ScreenUpdating = False
    On Error GoTo EndMacro:

    If SelectionOnly = True Then
        With Selection
            StartRow = .Cells(1).Row
            StartCol = .Cells(1).Column
            EndRow = .Cells(.Cells.Count).Row
            EndCol = .Cells(.Cells.Count).Column
        End With
    Else
        With ActiveSheet.UsedRange
            StartRow = .Cells(1).Row
            StartCol = .Cells(1).Column
            EndRow = .Cells(.Cells.Count).Row
            EndCol = .Cells(.Cells.Count).Column
        End With
    End If

    For RowNdx = StartRow To EndRow
        WholeLine = ""
        For ColNdx = StartCol To EndCol
            If Cells(RowNdx, ColNdx).Value = "" Then
                CellValue = ""
            Else
                CellValue = Cells(RowNdx, ColNdx).Value
            End If
            WholeLine = WholeLine & CellValue & Sep
        Next ColNdx
        WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep))
        Print #nFileNum, WholeLine
    Next RowNdx

EndMacro:
    On Error GoTo 0
    Application.ScreenUpdating = True

End Sub

java.lang.OutOfMemoryError: Java heap space in Maven

For those new to Maven (like me) here is the whole config that goes in the build section of your pom. Cheers.

<build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.19</version>
        <configuration>
            <argLine>-Xmx1024m</argLine>
        </configuration>
      </plugin>
    </plugins>
  </build>

ASP.net vs PHP (What to choose)

There are a couple of topics that might provide you with an answer. You could also run some tests yourself. Doesn't see too hard to get some loops started and adding a timer to calculate the execution time ;-)

What encoding/code page is cmd.exe using?

Yes, it’s frustrating—sometimes type and other programs print gibberish, and sometimes they do not.

First of all, Unicode characters will only display if the current console font contains the characters. So use a TrueType font like Lucida Console instead of the default Raster Font.

But if the console font doesn’t contain the character you’re trying to display, you’ll see question marks instead of gibberish. When you get gibberish, there’s more going on than just font settings.

When programs use standard C-library I/O functions like printf, the program’s output encoding must match the console’s output encoding, or you will get gibberish. chcp shows and sets the current codepage. All output using standard C-library I/O functions is treated as if it is in the codepage displayed by chcp.

Matching the program’s output encoding with the console’s output encoding can be accomplished in two different ways:

  • A program can get the console’s current codepage using chcp or GetConsoleOutputCP, and configure itself to output in that encoding, or

  • You or a program can set the console’s current codepage using chcp or SetConsoleOutputCP to match the default output encoding of the program.

However, programs that use Win32 APIs can write UTF-16LE strings directly to the console with WriteConsoleW. This is the only way to get correct output without setting codepages. And even when using that function, if a string is not in the UTF-16LE encoding to begin with, a Win32 program must pass the correct codepage to MultiByteToWideChar. Also, WriteConsoleW will not work if the program’s output is redirected; more fiddling is needed in that case.

type works some of the time because it checks the start of each file for a UTF-16LE Byte Order Mark (BOM), i.e. the bytes 0xFF 0xFE. If it finds such a mark, it displays the Unicode characters in the file using WriteConsoleW regardless of the current codepage. But when typeing any file without a UTF-16LE BOM, or for using non-ASCII characters with any command that doesn’t call WriteConsoleW—you will need to set the console codepage and program output encoding to match each other.


How can we find this out?

Here’s a test file containing Unicode characters:

ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??

Here’s a Java program to print out the test file in a bunch of different Unicode encodings. It could be in any programming language; it only prints ASCII characters or encoded bytes to stdout.

import java.io.*;

public class Foo {

    private static final String BOM = "\ufeff";
    private static final String TEST_STRING
        = "ASCII     abcde xyz\n"
        + "German    äöü ÄÖÜ ß\n"
        + "Polish    aezznl\n"
        + "Russian   ??????? ???\n"
        + "CJK       ??\n";

    public static void main(String[] args)
        throws Exception
    {
        String[] encodings = new String[] {
            "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE", "UTF-32BE" };

        for (String encoding: encodings) {
            System.out.println("== " + encoding);

            for (boolean writeBom: new Boolean[] {false, true}) {
                System.out.println(writeBom ? "= bom" : "= no bom");

                String output = (writeBom ? BOM : "") + TEST_STRING;
                byte[] bytes = output.getBytes(encoding);
                System.out.write(bytes);
                FileOutputStream out = new FileOutputStream("uc-test-"
                    + encoding + (writeBom ? "-bom.txt" : "-nobom.txt"));
                out.write(bytes);
                out.close();
            }
        }
    }
}

The output in the default codepage? Total garbage!

Z:\andrew\projects\sx\1259084>chcp
Active code page: 850

Z:\andrew\projects\sx\1259084>java Foo
== UTF-8
= no bom
ASCII     abcde xyz
German    +ñ+Â++ +ä+û+£ +ƒ
Polish    -à-Ö+¦+++ä+é
Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK       õ¢áÕÑ¢
= bom
´++ASCII     abcde xyz
German    +ñ+Â++ +ä+û+£ +ƒ
Polish    -à-Ö+¦+++ä+é
Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK       õ¢áÕÑ¢
== UTF-16LE
= no bom
A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h         ????z?|?D?B?
 R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
 C J K               `O}Y
 = bom
 ¦A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h         ????z?|?D?B?
 R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
 C J K               `O}Y
 == UTF-16BE
= no bom
 A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h        ?????z?|?D?B
 R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
 C J K              O`Y}
= bom
¦  A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h        ?????z?|?D?B
 R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
 C J K              O`Y}
== UTF-32LE
= no bom
A   S   C   I   I                       a   b   c   d   e       x   y   z
   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
   R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
?  O?
   C   J   K                               `O  }Y
   = bom
 ¦  A   S   C   I   I                       a   b   c   d   e       x   y   z

   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
   R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
?  O?
   C   J   K                               `O  }Y
   == UTF-32BE
= no bom
   A   S   C   I   I                       a   b   c   d   e       x   y   z
   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
   R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
  ?O
   C   J   K                              O`  Y}
= bom
  ¦    A   S   C   I   I                       a   b   c   d   e       x   y   z

   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
   R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
  ?O
   C   J   K                              O`  Y}

However, what if we type the files that got saved? They contain the exact same bytes that were printed to the console.

Z:\andrew\projects\sx\1259084>type *.txt

uc-test-UTF-16BE-bom.txt


¦  A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h        ?????z?|?D?B
 R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
 C J K              O`Y}

uc-test-UTF-16BE-nobom.txt


 A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h        ?????z?|?D?B
 R u s s i a n      ?0?1?2?3?4?5?6  ?M?N?O
 C J K              O`Y}

uc-test-UTF-16LE-bom.txt


ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??

uc-test-UTF-16LE-nobom.txt


A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h         ????z?|?D?B?
 R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
 C J K               `O}Y

uc-test-UTF-32BE-bom.txt


  ¦    A   S   C   I   I                       a   b   c   d   e       x   y   z

   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
   R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
  ?O
   C   J   K                              O`  Y}

uc-test-UTF-32BE-nobom.txt


   A   S   C   I   I                       a   b   c   d   e       x   y   z
   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                  ??  ??  ?z  ?|  ?D  ?B
   R   u   s   s   i   a   n              ?0  ?1  ?2  ?3  ?4  ?5  ?6      ?M  ?N
  ?O
   C   J   K                              O`  Y}

uc-test-UTF-32LE-bom.txt


 A S C I I           a b c d e   x y z
 G e r m a n         ä ö ü   Ä Ö Ü   ß
 P o l i s h         a e z z n l
 R u s s i a n       ? ? ? ? ? ? ?   ? ? ?
 C J K               ? ?

uc-test-UTF-32LE-nobom.txt


A   S   C   I   I                       a   b   c   d   e       x   y   z
   G   e   r   m   a   n                   õ   ÷   ³       -   Í   _       ¯
   P   o   l   i   s   h                   ??  ??  z?  |?  D?  B?
   R   u   s   s   i   a   n               0?  1?  2?  3?  4?  5?  6?      M?  N
?  O?
   C   J   K                               `O  }Y

uc-test-UTF-8-bom.txt


´++ASCII     abcde xyz
German    +ñ+Â++ +ä+û+£ +ƒ
Polish    -à-Ö+¦+++ä+é
Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK       õ¢áÕÑ¢

uc-test-UTF-8-nobom.txt


ASCII     abcde xyz
German    +ñ+Â++ +ä+û+£ +ƒ
Polish    -à-Ö+¦+++ä+é
Russian   ð¦ð¦ð¦ð¦ð¦ðÁð ÐìÐÄÐÅ
CJK       õ¢áÕÑ¢

The only thing that works is UTF-16LE file, with a BOM, printed to the console via type.

If we use anything other than type to print the file, we get garbage:

Z:\andrew\projects\sx\1259084>copy uc-test-UTF-16LE-bom.txt CON
 ¦A S C I I           a b c d e   x y z
 G e r m a n         õ ÷ ³   - Í _   ¯
 P o l i s h         ????z?|?D?B?
 R u s s i a n       0?1?2?3?4?5?6?  M?N?O?
 C J K               `O}Y
         1 file(s) copied.

From the fact that copy CON does not display Unicode correctly, we can conclude that the type command has logic to detect a UTF-16LE BOM at the start of the file, and use special Windows APIs to print it.

We can see this by opening cmd.exe in a debugger when it goes to type out a file:

enter image description here

After type opens a file, it checks for a BOM of 0xFEFF—i.e., the bytes 0xFF 0xFE in little-endian—and if there is such a BOM, type sets an internal fOutputUnicode flag. This flag is checked later to decide whether to call WriteConsoleW.

But that’s the only way to get type to output Unicode, and only for files that have BOMs and are in UTF-16LE. For all other files, and for programs that don’t have special code to handle console output, your files will be interpreted according to the current codepage, and will likely show up as gibberish.

You can emulate how type outputs Unicode to the console in your own programs like so:

#include <stdio.h>
#define UNICODE
#include <windows.h>

static LPCSTR lpcsTest =
    "ASCII     abcde xyz\n"
    "German    äöü ÄÖÜ ß\n"
    "Polish    aezznl\n"
    "Russian   ??????? ???\n"
    "CJK       ??\n";

int main() {
    int n;
    wchar_t buf[1024];

    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

    n = MultiByteToWideChar(CP_UTF8, 0,
            lpcsTest, strlen(lpcsTest),
            buf, sizeof(buf));

    WriteConsole(hConsole, buf, n, &n, NULL);

    return 0;
}

This program works for printing Unicode on the Windows console using the default codepage.


For the sample Java program, we can get a little bit of correct output by setting the codepage manually, though the output gets messed up in weird ways:

Z:\andrew\projects\sx\1259084>chcp 65001
Active code page: 65001

Z:\andrew\projects\sx\1259084>java Foo
== UTF-8
= no bom
ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??
? ???
CJK       ??
 ??
?
?
= bom
ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??
?? ???
CJK       ??
  ??
?
?
== UTF-16LE
= no bom
A S C I I           a b c d e   x y z
…

However, a C program that sets a Unicode UTF-8 codepage:

#include <stdio.h>
#include <windows.h>

int main() {
    int c, n;
    UINT oldCodePage;
    char buf[1024];

    oldCodePage = GetConsoleOutputCP();
    if (!SetConsoleOutputCP(65001)) {
        printf("error\n");
    }

    freopen("uc-test-UTF-8-nobom.txt", "rb", stdin);
    n = fread(buf, sizeof(buf[0]), sizeof(buf), stdin);
    fwrite(buf, sizeof(buf[0]), n, stdout);

    SetConsoleOutputCP(oldCodePage);

    return 0;
}

does have correct output:

Z:\andrew\projects\sx\1259084>.\test
ASCII     abcde xyz
German    äöü ÄÖÜ ß
Polish    aezznl
Russian   ??????? ???
CJK       ??

The moral of the story?

  • type can print UTF-16LE files with a BOM regardless of your current codepage
  • Win32 programs can be programmed to output Unicode to the console, using WriteConsoleW.
  • Other programs which set the codepage and adjust their output encoding accordingly can print Unicode on the console regardless of what the codepage was when the program started
  • For everything else you will have to mess around with chcp, and will probably still get weird output.

Can I change the color of Font Awesome's icon color?

For me the only thing that worked is inline css + overriding

<i class="fas fa-ellipsis-v fa-2x" style="color:red !important"></i>

How to install APK from PC?

Airdroid , android market install the app on android then go onto the computer type in the address given, type in the password given (or scan the QR code). Go to settings and under security (if your running the new ICS or Jellybean) or go to settings->apps->managment and select unknown sources(for gingerbread) then click on (I think) speed install, or something along those lines. it will be on the top of the page slightly towards the left. drag and drop as many .apks as you want then on you android just tap the install buttons that appear. Airdroid is wonderful and does a lot more than just apks.

How to read data From *.CSV file using javascript?

Actually you can use a light-weight library called any-text.

  • install dependencies
npm i -D any-text
  • use custom command to read files
var reader = require('any-text');
 
reader.getText(`path-to-file`).then(function (data) {
  console.log(data);
});

or use async-await :

var reader = require('any-text');
 
const chai = require('chai');
const expect = chai.expect;
 
describe('file reader checks', () => {
  it('check csv file content', async () => {
    expect(
      await reader.getText(`${process.cwd()}/test/files/dummy.csv`)
    ).to.contains('Lorem ipsum');
  });
});

Finding duplicate integers in an array and display how many times they occurred

Since you can't use LINQ, you can do this with collections and loops instead:

static void Main(string[] args)
{              
    int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
    var dict = new Dictionary<int, int>();

    foreach(var value in array)
    {
        if (dict.ContainsKey(value))
            dict[value]++;
        else
            dict[value] = 1;
    }

    foreach(var pair in dict)
        Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
    Console.ReadKey();
}

What's wrong with overridable method calls in constructors?

Here is an example that reveals the logical problems that can occur when calling an overridable method in the super constructor.

class A {

    protected int minWeeklySalary;
    protected int maxWeeklySalary;

    protected static final int MIN = 1000;
    protected static final int MAX = 2000;

    public A() {
        setSalaryRange();
    }

    protected void setSalaryRange() {
        throw new RuntimeException("not implemented");
    }

    public void pr() {
        System.out.println("minWeeklySalary: " + minWeeklySalary);
        System.out.println("maxWeeklySalary: " + maxWeeklySalary);
    }
}

class B extends A {

    private int factor = 1;

    public B(int _factor) {
        this.factor = _factor;
    }

    @Override
    protected void setSalaryRange() {
        this.minWeeklySalary = MIN * this.factor;
        this.maxWeeklySalary = MAX * this.factor;
    }
}

public static void main(String[] args) {
    B b = new B(2);
    b.pr();
}

The result would actually be:

minWeeklySalary: 0

maxWeeklySalary: 0

This is because the constructor of class B first calls the constructor of class A, where the overridable method inside B gets executed. But inside the method we are using the instance variable factor which has not yet been initialized (because the constructor of A has not yet finished), thus factor is 0 and not 1 and definitely not 2 (the thing that the programmer might think it will be). Imagine how hard would be to track an error if the calculation logic was ten times more twisted.

I hope that would help someone.

python NameError: name 'file' is not defined

file() is not supported in Python 3

Use open() instead; see Built-in Functions - open().

How do I draw a circle in iOS Swift?

Add in view did load

    //Circle Points

     var CircleLayer   = CAShapeLayer() 

    let center = CGPoint (x: myCircleView.frame.size.width / 2, y: myCircleView.frame.size.height / 2)
    let circleRadius = myCircleView.frame.size.width / 2
    let circlePath = UIBezierPath(arcCenter: center, radius: circleRadius, startAngle: CGFloat(M_PI), endAngle: CGFloat(M_PI * 4), clockwise: true)
    CircleLayer.path = circlePath.cgPath
   CircleLayer.strokeColor = UIColor.red.cgColor
    CircleLayer.fillColor = UIColor.blue.cgColor
    CircleLayer.lineWidth = 8
    CircleLayer.strokeStart = 0
    CircleLayer.strokeEnd  = 1
    Self.View.layer.addSublayer(CircleLayer)

What exactly does Double mean in java?

A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.

IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).

A Double in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double object.

Materialize CSS - Select Doesn't Seem to Render

First, make sure you initialize it in document.ready like this:

$(document).ready(function () {
    $('select').material_select();
});

Then, populate it with your data in the way you want. My example:

    function FillMySelect(myCustomData) {
       $("#mySelect").html('');

        $.each(myCustomData, function (key, value) {
           $("#mySelect").append("<option value='" + value.id+ "'>" + value.name + "</option>");
        });
}

Make sure after you are done with the population, to trigger this contentChanged like this:

$("#mySelect").trigger('contentChanged');

Converting file size in bytes to human-readable string

1551859712 / 1024 = 1515488
1515488 / 1024 = 1479.96875
1479.96875 / 1024 = 1.44528198242188

Your solution is correct. The important thing to realize is that in order to get from 1551859712 to 1.5, you have to do divisions by 1000, but bytes are counted in binary-to-decimal chunks of 1024, hence why the Gigabyte value is less.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

What LaTeX Editor do you suggest for Linux?

Honestly, I've always been happy with emacs. Then again, I started out using emacs, so I've no doubt that it colours my perceptions. Still, it gives syntax highlighting and formatting, and can easily be configured to build the LaTeX. Check out the TeX mode.

How to make a .NET Windows Service start right after the installation?

To add to ScottTx's answer, here's the actual code to start the service if you're doing it the Microsoft way (ie. using a Setup project etc...)

(excuse the VB.net code, but this is what I'm stuck with)

Private Sub ServiceInstaller1_AfterInstall(ByVal sender As System.Object, ByVal e As System.Configuration.Install.InstallEventArgs) Handles ServiceInstaller1.AfterInstall
    Dim sc As New ServiceController()
    sc.ServiceName = ServiceInstaller1.ServiceName

    If sc.Status = ServiceControllerStatus.Stopped Then
        Try
            ' Start the service, and wait until its status is "Running".
            sc.Start()
            sc.WaitForStatus(ServiceControllerStatus.Running)

            ' TODO: log status of service here: sc.Status
        Catch ex As Exception
            ' TODO: log an error here: "Could not start service: ex.Message"
            Throw
        End Try
    End If
End Sub

To create the above event handler, go to the ProjectInstaller designer where the 2 controlls are. Click on the ServiceInstaller1 control. Go to the properties window under events and there you'll find the AfterInstall event.

Note: Don't put the above code under the AfterInstall event for ServiceProcessInstaller1. It won't work, coming from experience. :)

Fragment onCreateView and onActivityCreated called twice

The two upvoted answers here show solutions for an Activity with navigation mode NAVIGATION_MODE_TABS, but I had the same issue with a NAVIGATION_MODE_LIST. It caused my Fragments to inexplicably lose their state when the screen orientation changed, which was really annoying. Thankfully, due to their helpful code I managed to figure it out.

Basically, when using a list navigation, ``onNavigationItemSelected()is automatically called when your activity is created/re-created, whether you like it or not. To prevent your Fragment'sonCreateView()from being called twice, this initial automatic call toonNavigationItemSelected()should check whether the Fragment is already in existence inside your Activity. If it is, return immediately, because there is nothing to do; if it isn't, then simply construct the Fragment and add it to the Activity like you normally would. Performing this check prevents your Fragment from needlessly being created again, which is what causesonCreateView()` to be called twice!

See my onNavigationItemSelected() implementation below.

public class MyActivity extends FragmentActivity implements ActionBar.OnNavigationListener
{
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

    private boolean mIsUserInitiatedNavItemSelection;

    // ... constructor code, etc.

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);

        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM))
        {
            getActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar().getSelectedNavigationIndex());

        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onNavigationItemSelected(int position, long id)
    {    
        Fragment fragment;
        switch (position)
        {
            // ... choose and construct fragment here
        }

        // is this the automatic (non-user initiated) call to onNavigationItemSelected()
        // that occurs when the activity is created/re-created?
        if (!mIsUserInitiatedNavItemSelection)
        {
            // all subsequent calls to onNavigationItemSelected() won't be automatic
            mIsUserInitiatedNavItemSelection = true;

            // has the same fragment already replaced the container and assumed its id?
            Fragment existingFragment = getSupportFragmentManager().findFragmentById(R.id.container);
            if (existingFragment != null && existingFragment.getClass().equals(fragment.getClass()))
            {
                return true; //nothing to do, because the fragment is already there 
            }
        }

        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
        return true;
    }
}

I borrowed inspiration for this solution from here.

Bootstrap Dropdown with Hover

In Twitter Bootstrap is not implemented but you can use the this plugin

Update 1:

Sames question here

How to kill a process running on particular port in Linux?

You can know list of all ports running in system along with its details (pid, address etc.) :

netstat -tulpn

You can know details of a particular port number by providing port number in following command :

sudo netstat -lutnp | grep -w '{port_number}'

ex: sudo netstat -lutnp | grep -w '8080' Details will be provided like this :

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name

if you want to kill a process using pid then : kill -9 {PID}

if you want to kill a process using port number : fuser -n tcp {port_number}

use sudo if you are not able to access any.

Angular directive how to add an attribute to the element?

A directive which adds another directive to the same element:

Similar answers:

Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {
  return {
    priority:1001, // compiles first
    terminal:true, // prevent lower priority directives to compile after it
    compile: function(el) {
      el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
      el.attr('ng-click', 'fxn()');
      var fn = $compile(el);
      return function(scope){
        fn(scope);
      };
    }
  };
});

Much cleaner solution - not to use ngClick at all:

A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

app.directive("myDir", function($parse) {
  return {
    compile: function(tElm,tAttrs){
      var exp = $parse('fxn()');
      return function (scope,elm){
        elm.bind('click',function(){
          exp(scope);
        });  
      };
    }
  };
});

How to get a subset of a javascript object's properties

Destructuring into dynamically named variables is impossible in JavaScript as discussed in this question.

To set keys dynamically, you can use reduce function without mutating object as follows:

_x000D_
_x000D_
const getSubset = (obj, ...keys) => keys.reduce((a, c) => ({ ...a, [c]: obj[c] }), {});_x000D_
_x000D_
const elmo = { _x000D_
  color: 'red',_x000D_
  annoying: true,_x000D_
  height: 'unknown',_x000D_
  meta: { one: '1', two: '2'}_x000D_
}_x000D_
_x000D_
const subset = getSubset(elmo, 'color', 'annoying')_x000D_
console.log(subset)
_x000D_
_x000D_
_x000D_

Should note that you're creating a new object on every iteration though instead of updating a single clone. – mpen

below is a version using reduce with single clone (updating initial value passed in to reduce).

_x000D_
_x000D_
const getSubset = (obj, ...keys) => keys.reduce((acc, curr) => {_x000D_
  acc[curr] = obj[curr]_x000D_
  return acc_x000D_
}, {})_x000D_
_x000D_
const elmo = { _x000D_
  color: 'red',_x000D_
  annoying: true,_x000D_
  height: 'unknown',_x000D_
  meta: { one: '1', two: '2'}_x000D_
}_x000D_
_x000D_
const subset = getSubset(elmo, 'annoying', 'height', 'meta')_x000D_
console.log(subset)
_x000D_
_x000D_
_x000D_

HttpURLConnection timeout settings

I could get solution for such a similar problem with addition of a simple line

HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");

My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.

Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.

Is there a way to change the spacing between legend items in ggplot2?

Looks like the best approach (in 2018) is to use legend.key.size under the theme object. (e.g., see here).

#Set-up:
    library(ggplot2)
    library(gridExtra)

    gp <- ggplot(data = mtcars, aes(mpg, cyl, colour = factor(cyl))) +
        geom_point()

This is real easy if you are using theme_bw():

  gpbw <- gp + theme_bw()

#Change spacing size:

  g1bw <- gpbw + theme(legend.key.size = unit(0, 'lines'))
  g2bw <- gpbw + theme(legend.key.size = unit(1.5, 'lines'))
  g3bw <- gpbw + theme(legend.key.size = unit(3, 'lines'))

  grid.arrange(g1bw,g2bw,g3bw,nrow=3)

enter image description here

However, this doesn't work quite so well otherwise (e.g., if you need the grey background on your legend symbol):

  g1 <- gp + theme(legend.key.size = unit(0, 'lines'))
  g2 <- gp + theme(legend.key.size = unit(1.5, 'lines'))
  g3 <- gp + theme(legend.key.size = unit(3, 'lines'))

  grid.arrange(g1,g2,g3,nrow=3)

#Notice that the legend symbol squares get bigger (that's what legend.key.size does). 

#Let's [indirectly] "control" that, too:
  gp2 <- g3
  g4 <- gp2 + theme(legend.key = element_rect(size = 1))
  g5 <- gp2 + theme(legend.key = element_rect(size = 3))
  g6 <- gp2 + theme(legend.key = element_rect(size = 10))

  grid.arrange(g4,g5,g6,nrow=3)   #see picture below, left

Notice that white squares begin blocking legend title (and eventually the graph itself if we kept increasing the value).

  #This shows you why:
    gt <- gp2 + theme(legend.key = element_rect(size = 10,color = 'yellow' ))

enter image description here

I haven't quite found a work-around for fixing the above problem... Let me know in the comments if you have an idea, and I'll update accordingly!

  • I wonder if there is some way to re-layer things using $layers...

Symbolicating iPhone App Crash Reports

The combination that worked for me was:

  1. Copy the dSYM file into the directory where the crash report was
  2. Unzip the ipa file containing the app ('unzip MyApp.ipa')
  3. Copy the application binary from the resulting exploded payload into the same folder as the crash report and symbol file (Something like "MyApp.app/MyApp")
  4. Import or Re-symbolicate the crash report from within Xcode's organizer

Using atos I wasn't able to resolve the correct symbol information with the addresses and offsets that were in the crash report. When I did this, I see something more meaningful, and it seems to be a legitimate stack trace.

MySQL Query to select data from last week?

If you're looking to retrieve records within the last 7 days, you can use the snippet below:

SELECT date FROM table_name WHERE DATE(date) >= CURDATE() - INTERVAL 7 DAY;

How to get the previous page URL using JavaScript?

You can use the following to get the previous URL.

var oldURL = document.referrer;
alert(oldURL);

How to change Jquery UI Slider handle

This change only first handle in multihandle slider. In apiDoc you can see:"For example, if you specify values: [ 1, 5, 18 ] and create one custom handle, the plugin will create the other two."

How to select element using XPATH syntax on Selenium for Python?

Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.

> def get_browser():
>     """Get the browser (a "driver")."""
>     # find the path with 'which chromedriver'
>     path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
>                             'venv/bin/chromedriver')
>     download_dir = "/home/moose/selenium-download/"
>     print("Is directory: {}".format(os.path.isdir(download_dir)))
> 
>     from selenium.webdriver.chrome.options import Options
>     chrome_options = Options()
>     chrome_options.add_experimental_option('prefs', {
>         "plugins.plugins_list": [{"enabled": False,
>                                   "name": "Chrome PDF Viewer"}],
>         "download": {
>             "prompt_for_download": False,
>             "default_directory": download_dir
>         }
>     })
> 
>     browser = webdriver.Chrome(path_to_chromedriver,
>                                chrome_options=chrome_options)
>     return browser

jQuery .ready in a dynamically inserted iframe

Found the solution to the problem.

When you click on a thickbox link that open a iframe, it insert an iframe with an id of TB_iframeContent.

Instead of relying on the $(document).ready event in the iframe code, I just have to bind to the load event of the iframe in the parent document:

$('#TB_iframeContent', top.document).load(ApplyGalleria);

This code is in the iframe but binds to an event of a control in the parent document. It works in FireFox and IE.

Add item to Listview control

  • Very Simple

    private void button1_Click(object sender, EventArgs e)
    {
        ListViewItem item = new ListViewItem();
        item.SubItems.Add(textBox2.Text);
        item.SubItems.Add(textBox3.Text);
        item.SubItems.Add(textBox4.Text);
        listView1.Items.Add(item);
        textBox2.Clear();
        textBox3.Clear();
        textBox4.Clear();
    }
    
  • You can also Do this stuff...

        ListViewItem item = new ListViewItem();
        item.SubItems.Add("Santosh");
        item.SubItems.Add("26");
        item.SubItems.Add("India");
    

Storing WPF Image Resources

Yes, it is the right way.

You could use the image in the resource file just using the path:

<Image Source="..\Media\Image.png" />

You must set the build action of the image file to "Resource".

How to force composer to reinstall a library?

As user @aaracrr pointed out in a comment on another answer probably the best answer is to re-require the package with the same version constraint.

ie.

composer require vendor/package

or specifying a version constraint

composer require vendor/package:^1.0.0

How to reset Jenkins security settings from the command line?

\.jenkins\secrets\initialAdminPassword

Copy the password from the initialAdminPassword file and paste it into the Jenkins.

How to change button background image on mouseOver?

In the case of winforms:

If you include the images to your resources you can do it like this, very simple and straight forward:

public Form1()
          {
               InitializeComponent();
               button1.MouseEnter += new EventHandler(button1_MouseEnter);
               button1.MouseLeave += new EventHandler(button1_MouseLeave);
          }

          void button1_MouseLeave(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
          }


          void button1_MouseEnter(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

I would not recommend hardcoding image paths.

As you have altered your question ...

There is no (on)MouseOver in winforms afaik, there are MouseHover and MouseMove events, but if you change image on those, it will not change back, so the MouseEnter + MouseLeave are what you are looking for I think. Anyway, changing the image on Hover or Move :

in the constructor:
button1.MouseHover += new EventHandler(button1_MouseHover); 
button1.MouseMove += new MouseEventHandler(button1_MouseMove);

void button1_MouseMove(object sender, MouseEventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

          void button1_MouseHover(object sender, EventArgs e)
          {
               this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
          }

To add images to your resources: Projectproperties/resources/add/existing file

CSS selectors ul li a {...} vs ul > li > a {...}

ul>li selects all li that are a direct child of ul whereas ul li selects all li that are anywhere within (descending as deep as you like) a ul

For HTML:

<ul>
  <li><span><a href='#'>Something</a></span></li>
  <li><a href='#'>or Other</a></li>
</ul>

And CSS:

li a{ color: green; }
li>a{ color: red; }

The colour of Something will remain green but or Other will be red

Part 2, you should write the rule to be appropriate to the situation, I think the speed difference would be incredibly small, and probably overshadowed by the extra characters involved in writing more code, and definitely overshadowed by the time taken by the developer to think about it.

However, as a rule of thumb, the more specific you are with your rules, the faster the CSS engines can locate the DOM elements you want to apply it to, so I expect li>a is faster than li a as the DOM search can be cut short earlier. It also means that nested anchors are not styled with that rule, is that what you want? <~~ much more pertinent question.

how to download file in react js

Triggering browser download from front-end is not reliable.

What you should do is, create an endpoint that when called, will provide the correct response headers, thus triggering the browser download.

Front-end code can only do so much. The 'download' attribute for example, might just open the file in a new tab depending on the browser.

The response headers you need to look at are probably Content-Type and Content-Disposition. You should check this answer for more detailed explanation.

working with negative numbers in python

Thanks everyone, you all helped me learn a lot. This is what I came up with using some of your suggestions

#this is apparently a better way of getting multiple inputs at the same time than the 
#way I was doing it
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
numa = int(split_text[0])
numb = int(split_text[1])

#standing variables
total = 0

if numb > 0:
    repeat = numb
else:
    repeat = -numb

#for loops work better than while loops and are cheaper
#output the total
for count in range(repeat):
    total += numa


#check to make sure the output is accurate
if numb < 0:
    total = -total


print total

Thanks for all the help everyone.

How to add a "sleep" or "wait" to my Lua Script?

function wait(time)
    local duration = os.time() + time
    while os.time() < duration do end
end

This is probably one of the easiest ways to add a wait/sleep function to your script

Python argparse command line flags without arguments

As you have it, the argument w is expecting a value after -w on the command line. If you are just looking to flip a switch by setting a variable True or False, have a look here (specifically store_true and store_false)

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-w', action='store_true')

where action='store_true' implies default=False.

Conversely, you could haveaction='store_false', which implies default=True.

"Use the new keyword if hiding was intended" warning

@wdavo is correct. The same is also true for functions.

If you override a base function, like Update, then in your subclass you need:

new void Update()
{
  //do stufff
}

Without the new at the start of the function decleration you will get the warning flag.

How to search if dictionary value contains certain string with Python

import re
for i in range(len(myDict.values())):
    for j in range(len(myDict.values()[i])):
         match=re.search(r'Mary', myDict.values()[i][j])
         if match:
                 print match.group() #Mary
                 print myDict.keys()[i] #firstName
                 print myDict.values()[i][j] #Mary-Ann

Add list to set?

Use set.update() or |=

>>> a = set('abc')
>>> l = ['d', 'e']
>>> a.update(l)
>>> a
{'e', 'b', 'c', 'd', 'a'}

>>> l = ['f', 'g']
>>> a |= set(l)
>>> a
{'e', 'b', 'f', 'c', 'd', 'g', 'a'}

edit: If you want to add the list itself and not its members, then you must use a tuple, unfortunately. Set members must be hashable.

Better way to remove specific characters from a Perl string

Well if you're using the randomly-generated string so that it has a low probability of being matched by some intentional string that you might normally find in the data, then you probably want one string per file.

You take that string, call it $place_older say. And then when you want to eliminate the text, you call quotemeta, and you use that value to substitute:

my $subs = quotemeta $place_holder;
s/$subs//g;

dotnet ef not found in .NET Core 3

I was having this problem after I installed the dotnet-ef tool using Ansible with sudo escalated previllage on Ubuntu. I had to add become: no for the Playbook task, then the dotnet-ef tool became available to the current user.

  - name: install dotnet tool dotnet-ef
    command: dotnet tool install --global dotnet-ef --version {{dotnetef_version}}
    become: no

JavaScript chop/slice/trim off last character in string

@Jason S:

You can use slice! You just have to make sure you know how to use it. Positive #s are relative to the beginning, negative numbers are relative to the end.

js>"12345.00".slice(0,-1) 12345.0

Sorry for my graphomany but post was tagged 'jquery' earlier. So, you can't use slice() inside jQuery because slice() is jQuery method for operations with DOM elements, not substrings ... In other words answer @Jon Erickson suggest really perfect solution.

However, your method will works out of jQuery function, inside simple Javascript. Need to say due to last discussion in comments, that jQuery is very much more often renewable extension of JS than his own parent most known ECMAScript.

Here also exist two methods:

as our:

string.substring(from,to) as plus if 'to' index nulled returns the rest of string. so: string.substring(from) positive or negative ...

and some other - substr() - which provide range of substring and 'length' can be positive only: string.substr(start,length)

Also some maintainers suggest that last method string.substr(start,length) do not works or work with error for MSIE.

Plotting 4 curves in a single plot, with 3 y-axes

In your case there are 3 extra y axis (4 in total) and the best code that could be used to achieve what you want and deal with other cases is illustrated above:

clear
clc

x = linspace(0,1,10);
N = numel(x);
y = rand(1,N);
y_extra_1 = 5.*rand(1,N)+5;
y_extra_2 = 50.*rand(1,N)+20;
Y = [y;y_extra_1;y_extra_2];

xLimit = [min(x) max(x)];
xWidth = xLimit(2)-xLimit(1);
numberOfExtraPlots = 2;
a = 0.05;
N_ = numberOfExtraPlots+1;

for i=1:N_
    L=1-(numberOfExtraPlots*a)-0.2;
    axesPosition = [(0.1+(numberOfExtraPlots*a)) 0.1 L 0.8];
    if(i==1)
        color = [rand(1),rand(1),rand(1)];
        figure('Units','pixels','Position',[200 200 1200 600])
        axes('Units','normalized','Position',axesPosition,...
            'Color','w','XColor','k','YColor',color,...
            'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
            'NextPlot','add');
        plot(x,Y(i,:),'Color',color);
        xlabel('Time (s)');

        ylab = strcat('Values of dataset 0',num2str(i));
        ylabel(ylab)

        numberOfExtraPlots = numberOfExtraPlots - 1;
    else
        color = [rand(1),rand(1),rand(1)];
        axes('Units','normalized','Position',axesPosition,...
            'Color','none','XColor','k','YColor',color,...
            'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
            'XTick',[],'XTickLabel',[],'NextPlot','add');
        V = (xWidth*a*(i-1))/L;
        b=xLimit+[V 0];
        x_=linspace(b(1),b(2),10);
        plot(x_,Y(i,:),'Color',color);
        ylab = strcat('Values of dataset 0',num2str(i));
        ylabel(ylab)

        numberOfExtraPlots = numberOfExtraPlots - 1;
    end
end

The code above will produce something like this:

How to check size of a file using Bash?

Okay, if you're on a Mac, do this: stat -f %z "/Users/Example/config.log" That's it!

Text Editor For Linux (Besides Vi)?

If it's just you? Use what you want to use today; switch in mid-stream if you want.

Is it a team? Try to be editor-agnostic. Set standards for white-space (are tabs allowed? How many spaces does a tab represent?), but otherwise allow anyone to use whichever editor they want.

Is it a team doing pair-programming? That's where you may need a team-standard editor, just so that programmers can easily pass the keyboard.

To help implement a standard white-space policy in a shop where one or more coders is using Emacs: You can tell Emacs about your white-space policy with some comments stuck at the bottom of every file source file. For example,

# Local Variables:
# tab-width: 2
# ruby-indent-level: 2
# indent-tabs-mode: nil
# End:

Anyone using emacs (or xemacs) on that file will automatically get the group standard indentation.

Converting xml to string using C#

As Chris suggests, you can do it like this:

public string GetXMLAsString(XmlDocument myxml)
{
    return myxml.OuterXml;
}

Or like this:

public string GetXMLAsString(XmlDocument myxml)
    {

        StringWriter sw = new StringWriter();
        XmlTextWriter tx = new XmlTextWriter(sw);
        myxml.WriteTo(tx);

        string str = sw.ToString();// 
        return str;
    }

and if you really want to create a new XmlDocument then do this

XmlDocument newxmlDoc= myxml

How to connect to Mysql Server inside VirtualBox Vagrant?

This worked for me: Connect to MySQL in Vagrant

username: vagrant password: vagrant

sudo apt-get update sudo apt-get install build-essential zlib1g-dev
git-core sqlite3 libsqlite3-dev sudo aptitude install mysql-server
mysql-client


sudo nano /etc/mysql/my.cnf change: bind-address            = 0.0.0.0


mysql -u root -p

use mysql GRANT ALL ON *.* to root@'33.33.33.1' IDENTIFIED BY
'jarvis'; FLUSH PRIVILEGES; exit


sudo /etc/init.d/mysql restart




# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant::Config.run do |config|

  config.vm.box = "lucid32"

  config.vm.box_url = "http://files.vagrantup.com/lucid32.box"

  #config.vm.boot_mode = :gui

  # Assign this VM to a host-only network IP, allowing you to access
it   # via the IP. Host-only networks can talk to the host machine as
well as   # any other machines on the same network, but cannot be
accessed (through this   # network interface) by any external
networks.   # config.vm.network :hostonly, "192.168.33.10"

  # Assign this VM to a bridged network, allowing you to connect
directly to a   # network using the host's network device. This makes
the VM appear as another   # physical device on your network.   #
config.vm.network :bridged

  # Forward a port from the guest to the host, which allows for
outside   # computers to access the VM, whereas host only networking
does not.   # config.vm.forward_port 80, 8080

  config.vm.forward_port 3306, 3306

  config.vm.network :hostonly, "33.33.33.10"


end

VSCode single to double quote automatic replace

quote_type = single

add this inside .editorconfig

# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = false
insert_final_newline = false
quote_type = single

Find and replace Android studio

Press Ctrl+R to find and replace codes in the class where you are...

Find a value anywhere in a database

Based on bnkdev's answer I modified Narayana's Code to search all columns even numeric ones.

It'll run slower, but this version actually finds all matches not just those found in text columns.

I can't thank this guy enough. Saved me days of searching by hand!

CREATE PROC SearchAllTables 
(
@SearchStr nvarchar(100)
)
AS
BEGIN

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT


CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)                  
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(CONVERT(varchar(max), ' + @ColumnName + '), 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE CONVERT(varchar(max), ' + @ColumnName + ') LIKE ' + @SearchStr2
            )
        END
    END 
END

SELECT ColumnName, ColumnValue FROM #Results
END

How do I run a Java program from the command line on Windows?

Complile a Java file to generate a class:

javac filename.java

Execute the generated class:

java filename

How to validate an email address in PHP

Answered this in 'top question' about emails verification https://stackoverflow.com/a/41129750/1848217

For me the right way for checking emails is:

  1. Check that symbol @ exists, and before and after it there are some non-@ symbols: /^[^@]+@[^@]+$/
  2. Try to send an email to this address with some "activation code".
  3. When the user "activated" his email address, we will see that all is right.

Of course, you can show some warning or tooltip in front-end when user typed "strange" email to help him to avoid common mistakes, like no dot in domain part or spaces in name without quoting and so on. But you must accept the address "hello@world" if user really want it.

Also, you must remember that email address standard was and can evolute, so you can't just type some "standard-valid" regexp once and for all times. And you must remember that some concrete internet servers can fail some details of common standard and in fact work with own "modified standard".

So, just check @, hint user on frontend and send verification emails on given address.

Most efficient way to see if an ArrayList contains an object in Java

It depends on how efficient you need things to be. Simply iterating over the list looking for the element which satisfies a certain condition is O(n), but so is ArrayList.Contains if you could implement the Equals method. If you're not doing this in loops or inner loops this approach is probably just fine.

If you really need very efficient look-up speeds at all cost, you'll need to do two things:

  1. Work around the fact that the class is generated: Write an adapter class which can wrap the generated class and which implement equals() based on those two fields (assuming they are public). Don't forget to also implement hashCode() (*)
  2. Wrap each object with that adapter and put it in a HashSet. HashSet.contains() has constant access time, i.e. O(1) instead of O(n).

Of course, building this HashSet still has a O(n) cost. You are only going to gain anything if the cost of building the HashSet is negligible compared to the total cost of all the contains() checks that you need to do. Trying to build a list without duplicates is such a case.


* () Implementing hashCode() is best done by XOR'ing (^ operator) the hashCodes of the same fields you are using for the equals implementation (but multiply by 31 to reduce the chance of the XOR yielding 0)

Using Mockito to stub and execute methods for testing

You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.

Think of it like this…

  • I need to test a function of a class - let's call it myFunction
  • That function makes a call to a function on another class/service/database
  • That function also calls another method on the CUT

In the unit test

  • Should create a concrete CUT or @Spy on it
  • You can @Mock all of the other class/service/database (i.e. external dependencies)
  • You could stub the other function called in the CUT but it is not really how unit testing should be done

In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mocked.

In this very simple example, a function that creates an object will be difficult to test

public void doSomethingCool(String foo) {
    MyObject obj = new MyObject(foo);

    // can't do much with obj in a unit test unless it is returned
}

But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.

public void doSomethingCool(String foo) {
    MyObject obj = MyObjectService.getMeAnObject(foo);
}

as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

How to read xml file contents in jQuery and display in html elements?

Get the XML using Ajax call, find the main element, loop through all the element and append data in table.

Sample code

 //ajax call to load XML and parse it
        $.ajax({
            type: 'GET',
            url: 'https://res.cloudinary.com/dmsxwwfb5/raw/upload/v1591716537/book.xml',           // The file path.
            dataType: 'xml',    
            success: function(xml) {
               //find all book tags, loop them and append to table body
                $(xml).find('book').each(function() {
                    
                    // Append new data to the tbody element.
                    $('#tableBody').append(
                        '<tr>' +
                            '<td>' +
                                $(this).find('author').text() + '</td> ' +
                            '<td>' +
                                $(this).find('title').text() + '</td> ' +
                            '<td>' +
                                $(this).find('genre').text() + '</td> ' +
                                '<td>' +
                                $(this).find('price').text() + '</td> ' +
                                '<td>' +
                                $(this).find('description').text() + '</td> ' +
                        '</tr>');
                });
            }
        });

Fiddle link: https://jsfiddle.net/pn9xs8hf/2/

Source: Read XML using jQuery & load it in HTML Table

How to echo in PHP, HTML tags

There isn't any need to use echo, sir. Just use the tag <plaintext>:

<plaintext>
    <div>
        <h3><a href="#">First</a></h3>
        <div>Lorem ipsum dolor sit amet.</div>
    </div>

Visual Studio Code always asking for git credentials

You should be able to set your credentials like this:

git remote set-url origin https://<USERNAME>:<PASSWORD>@bitbucket.org/path/to/repo.git

You can get the remote url like this:

git config --get remote.origin.url

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

How to replace a substring of a string

In javascript:

var str = "abcdaaaaaabcdaabbccddabcd";
document.write(str.replace(/(abcd)/g,"----"));
//example output: ----aaaaa----aabbccdd----

In other languages, it would be something similar. Remember to enable global matches.

How to change a text with jQuery

Something like this should work

var text = $('#toptitle').text();
if (text == 'Profil'){
    $('#toptitle').text('New Word');
}

Eclipse Java error: This selection cannot be launched and there are no recent launches

Eclipse needs to see a main method in one of your project's source files in order to determine what kind of project it is so that it can offer the proper run options:

public static void main(String[] args)

Without that method signature (or with a malformed version of that method signature), the Run As menu item will not present any run options.

How to parse JSON Array (Not Json Object) in Android

@Stebra See this example. This may help you.

public class CustomerInfo 
{   
    @SerializedName("customerid")
    public String customerid;
    @SerializedName("picture")
    public String picture;

    @SerializedName("location")
    public String location;

    public CustomerInfo()
    {}
}

And when you get the result; parse like this

List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

I think groupby should work.

df.groupby(['A', 'B']).max()['C']

If you need a dataframe back you can chain the reset index call.

df.groupby(['A', 'B']).max()['C'].reset_index()

CSS white space at bottom of page despite having both min-height and height tag

This will remove the margin and padding from your page elements, since there is a paragraph with a script inside that is causing an added margin. this way you should reset it and then you can style the other elements of your page, or you could give that paragraph an id and set margin to zero only for it.

<style>
* {
   margin: 0;
   padding: 0;
}
</style>

Try to put this as the first style.

How do you divide each element in a list by an int?

The way you tried first is actually directly possible with numpy:

import numpy
myArray = numpy.array([10,20,30,40,50,60,70,80,90])
myInt = 10
newArray = myArray/myInt

If you do such operations with long lists and especially in any sort of scientific computing project, I would really advise using numpy.

How to write a multidimensional array to a text file?

If you don't need a human-readable output, another option you could try is to save the array as a MATLAB .mat file, which is a structured array. I despise MATLAB, but the fact that I can both read and write a .mat in very few lines is convenient.

Unlike Joe Kington's answer, the benefit of this is that you don't need to know the original shape of the data in the .mat file, i.e. no need to reshape upon reading in. And, unlike using pickle, a .mat file can be read by MATLAB, and probably some other programs/languages as well.

Here is an example:

import numpy as np
import scipy.io

# Some test data
x = np.arange(200).reshape((4,5,10))

# Specify the filename of the .mat file
matfile = 'test_mat.mat'

# Write the array to the mat file. For this to work, the array must be the value
# corresponding to a key name of your choice in a dictionary
scipy.io.savemat(matfile, mdict={'out': x}, oned_as='row')

# For the above line, I specified the kwarg oned_as since python (2.7 with 
# numpy 1.6.1) throws a FutureWarning.  Here, this isn't really necessary 
# since oned_as is a kwarg for dealing with 1-D arrays.

# Now load in the data from the .mat that was just saved
matdata = scipy.io.loadmat(matfile)

# And just to check if the data is the same:
assert np.all(x == matdata['out'])

If you forget the key that the array is named in the .mat file, you can always do:

print matdata.keys()

And of course you can store many arrays using many more keys.

So yes – it won't be readable with your eyes, but only takes 2 lines to write and read the data, which I think is a fair trade-off.

Take a look at the docs for scipy.io.savemat and scipy.io.loadmat and also this tutorial page: scipy.io File IO Tutorial

How to count digits, letters, spaces for a string in Python?

def match_string(words):
    nums = 0
    letter = 0
    other = 0
    for i in words :
        if i.isalpha():
            letter+=1
        elif i.isdigit():
            nums+=1
        else:
            other+=1
    return nums,letter,other

x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>

Changing CSS Values with Javascript

I don't have rep enough to comment so I'll format an answer, yet it is only a demonstration of the issue in question.

It seems, when element styles are defined in stylesheets they are not visible to getElementById("someElement").style

This code illustrates the issue... Code from below on jsFiddle.

In Test 2, on the first call, the items left value is undefined, and so, what should be a simple toggle gets messed up. For my use I will define my important style values inline, but it does seem to partially defeat the purpose of the stylesheet.

Here's the page code...

<html>
  <head>
    <style type="text/css">
      #test2a{
        position: absolute;
        left: 0px;
        width: 50px;
        height: 50px;
        background-color: green;
        border: 4px solid black;
      }
      #test2b{
        position: absolute;
        left: 55px;
        width: 50px;
        height: 50px;
        background-color: yellow;
        margin: 4px;
      }
    </style>
  </head>
  <body>

  <!-- test1 -->
    Swap left positions function with styles defined inline.
    <a href="javascript:test1();">Test 1</a><br>
    <div class="container">
      <div id="test1a" style="position: absolute;left: 0px;width: 50px; height: 50px;background-color: green;border: 4px solid black;"></div>
      <div id="test1b" style="position: absolute;left: 55px;width: 50px; height: 50px;background-color: yellow;margin: 4px;"></div>
    </div>
    <script type="text/javascript">
     function test1(){
       var a = document.getElementById("test1a");
       var b = document.getElementById("test1b");
       alert(a.style.left + " - " + b.style.left);
       a.style.left = (a.style.left == "0px")? "55px" : "0px";
       b.style.left = (b.style.left == "0px")? "55px" : "0px";
     }
    </script>
  <!-- end test 1 -->

  <!-- test2 -->
    <div id="moveDownThePage" style="position: relative;top: 70px;">
    Identical function with styles defined in stylesheet.
    <a href="javascript:test2();">Test 2</a><br>
    <div class="container">
      <div id="test2a"></div>
      <div id="test2b"></div>
    </div>
    </div>
    <script type="text/javascript">
     function test2(){
       var a = document.getElementById("test2a");
       var b = document.getElementById("test2b");
       alert(a.style.left + " - " + b.style.left);
       a.style.left = (a.style.left == "0px")? "55px" : "0px";
       b.style.left = (b.style.left == "0px")? "55px" : "0px";
     }
    </script>
  <!-- end test 2 -->

  </body>
</html>

I hope this helps to illuminate the issue.

Skip

How to use GROUP BY to concatenate strings in SQL Server?

Another example without the garbage: ",TYPE).value('(./text())[1]','VARCHAR(MAX)')"

WITH t AS (
    SELECT 1 n, 1 g, 1 v
    UNION ALL 
    SELECT 2 n, 1 g, 2 v
    UNION ALL 
    SELECT 3 n, 2 g, 3 v
)
SELECT g
        , STUFF (
                (
                    SELECT ', ' + CAST(v AS VARCHAR(MAX))
                    FROM t sub_t
                    WHERE sub_t.g = main_t.g
                    FOR XML PATH('')
                )
                , 1, 2, ''
        ) cg
FROM t main_t
GROUP BY g

Input-output is

*************************   ->  *********************
*   n   *   g   *   v   *       *   g   *   cg      *
*   -   *   -   *   -   *       *   -   *   -       *
*   1   *   1   *   1   *       *   1   *   1, 2    *
*   2   *   1   *   2   *       *   2   *   3       *
*   3   *   2   *   3   *       *********************
*************************   

How to get active user's UserDetails

You can try this: By Using Authentication Object from Spring we can get User details from it in the controller method . Below is the example , by passing Authentication object in the controller method along with argument.Once user is authenticated the details are populated in the Authentication Object.

@GetMapping(value = "/mappingEndPoint") <ReturnType> methodName(Authentication auth) {
   String userName = auth.getName(); 
   return <ReturnType>;
}

Chrome javascript debugger breakpoints don't do anything?

I got a similar problem. Breakpoints where not working unless I used debugger;. I fixed my breakpoints problem with "Restore defaults and reload". It's located in the Chrome Developer Tools, Settings, Restore defaults and reload.

How to remove the hash from window.location (URL) with JavaScript without page refresh?

const url = new URL(window.location);
url.hash = '';
history.replaceState(null, document.title, url);

Reading a single char in Java

Using nextline and System.in.read as often proposed requires the user to hit enter after typing a character. However, people searching for an answer to this question, may also be interested in directly respond to a key press in a console!

I found a solution to do so using jline3, wherein we first change the terminal into rawmode to directly respond to keys, and then wait for the next entered character:

var terminal = TerminalBuilder.terminal()
terminal.enterRawMode()
var reader = terminal.reader()

var c = reader.read()
<dependency>
    <groupId>org.jline</groupId>
    <artifactId>jline</artifactId>
    <version>3.12.3</version>
</dependency>

How to break out of a loop from inside a switch?

Even if you don't like goto, do not use an exception to exit a loop. The following sample shows how ugly it could be:

try {
  while ( ... ) {
    switch( ... ) {
      case ...:
        throw 777; // I'm afraid of goto
     }
  }
}
catch ( int )
{
}

I would use goto as in this answer. In this case goto will make code more clear then any other option. I hope that this question will be helpful.

But I think that using goto is the only option here because of the string while(true). You should consider refactoring of your loop. I'd suppose the following solution:

bool end_loop = false;
while ( !end_loop ) {
    switch( msg->state ) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
    case DONE:
        end_loop = true; break;
    }
}

Or even the following:

while ( msg->state != DONE ) {
    switch( msg->state ) {
    case MSGTYPE: // ... 
        break;
    // ... more stuff ...
}