Programs & Examples On #M2m

A type of relationship between entities of types A and B which associates a list of entities of type B to an entity of type A and vice versa. Types A and B may be the same type

How to decode JWT Token?

Extending on cooxkie answer, and dpix answer, when you are reading a jwt token (such as an access_token received from AD FS), you can merge the claims in the jwt token with the claims from "context.AuthenticationTicket.Identity" that might not have the same set of claims as the jwt token.

To Illustrate, in an Authentication Code flow using OpenID Connect,after a user is authenticated, you can handle the event SecurityTokenValidated which provides you with an authentication context, then you can use it to read the access_token as a jwt token, then you can "merge" tokens that are in the access_token with the standard list of claims received as part of the user identity:

    private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage,OpenIdConnectAuthenticationOptions> context)
    {
        //get the current user identity
        ClaimsIdentity claimsIdentity = (ClaimsIdentity)context.AuthenticationTicket.Identity;

        /*read access token from the current context*/
        string access_token = context.ProtocolMessage.AccessToken;

        JwtSecurityTokenHandler hand = new JwtSecurityTokenHandler();
        //read the token as recommended by Coxkie and dpix
        var tokenS = hand.ReadJwtToken(access_token);
        //here, you read the claims from the access token which might have 
        //additional claims needed by your application
        foreach (var claim in tokenS.Claims)
        {
            if (!claimsIdentity.HasClaim(claim.Type, claim.Value))
                claimsIdentity.AddClaim(claim);
        }

        return Task.FromResult(0);
    }

What's the difference between select_related and prefetch_related in Django ORM?

Gone through the already posted answers. Just thought it would be better if I add an answer with actual example.

Let' say you have 3 Django models which are related.

class M1(models.Model):
    name = models.CharField(max_length=10)

class M2(models.Model):
    name = models.CharField(max_length=10)
    select_relation = models.ForeignKey(M1, on_delete=models.CASCADE)
    prefetch_relation = models.ManyToManyField(to='M3')

class M3(models.Model):
    name = models.CharField(max_length=10)

Here you can query M2 model and its relative M1 objects using select_relation field and M3 objects using prefetch_relation field.

However as we've mentioned M1's relation from M2 is a ForeignKey, it just returns only 1 record for any M2 object. Same thing applies for OneToOneField as well.

But M3's relation from M2 is a ManyToManyField which might return any number of M1 objects.

Consider a case where you have 2 M2 objects m21, m22 who have same 5 associated M3 objects with IDs 1,2,3,4,5. When you fetch associated M3 objects for each of those M2 objects, if you use select related, this is how it's going to work.

Steps:

  1. Find m21 object.
  2. Query all the M3 objects related to m21 object whose IDs are 1,2,3,4,5.
  3. Repeat same thing for m22 object and all other M2 objects.

As we have same 1,2,3,4,5 IDs for both m21, m22 objects, if we use select_related option, it's going to query the DB twice for the same IDs which were already fetched.

Instead if you use prefetch_related, when you try to get M2 objects, it will make a note of all the IDs that your objects returned (Note: only the IDs) while querying M2 table and as last step, Django is going to make a query to M3 table with the set of all IDs that your M2 objects have returned. and join them to M2 objects using Python instead of database.

This way you're querying all the M3 objects only once which improves performance.

how to get curl to output only http response body (json) and no other headers etc

I was executing a get request an also want to see just the response and nothing else, seems like magic is done with -silent,-s option.

From the curl man page:

-s, --silent Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.

Below the examples:

curl -s "http://host:8080/some/resource"
curl -silent "http://host:8080/some/resource"

Using custom headers

curl -s -H "Accept: application/json" "http://host:8080/some/resource")

Using POST method with a header

curl -s -X POST -H "Content-Type: application/json" "http://host:8080/some/resource") -d '{ "myBean": {"property": "value"}}'

You can also customize the output for specific values with -w, below the options I use to get just response codes of the curl:

curl -s -o /dev/null -w "%{http_code}" "http://host:8080/some/resource"

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

How to use an existing database with an Android application

If you are having pre built data base than copy it in asset folder and create an new class as DataBaseHelper which implements SQLiteOpenHelper Than use following code:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelperClass extends SQLiteOpenHelper{
 //The Android's default system path of your application database.
private static String DB_PATH = "/data/data/package_name/databases/";
// Data Base Name.
private static final String DATABASE_NAME = "DBName.sqlite";
// Data Base Version.
private static final int DATABASE_VERSION = 1;
// Table Names of Data Base.
static final String TABLE_Name = "tableName";

public Context context;
static SQLiteDatabase sqliteDataBase;

/**
 * Constructor
 * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
 * @param context
 * Parameters of super() are    1. Context
 *                              2. Data Base Name.
 *                              3. Cursor Factory.
 *                              4. Data Base Version.
 */
public DataBaseHelperClass(Context context) {       
    super(context, DATABASE_NAME, null ,DATABASE_VERSION);
    this.context = context;
}

/**
 * Creates a empty database on the system and rewrites it with your own database.
 * By calling this method and empty database will be created into the default system path
 * of your application so we are gonna be able to overwrite that database with our database.
 * */
public void createDataBase() throws IOException{
    //check if the database exists
    boolean databaseExist = checkDataBase();

    if(databaseExist){
        // Do Nothing.
    }else{
        this.getWritableDatabase();         
        copyDataBase(); 
    }// end if else dbExist
} // end createDataBase().

/**
 * Check if the database already exist to avoid re-copying the file each time you open the application.
 * @return true if it exists, false if it doesn't
 */
public boolean checkDataBase(){
    File databaseFile = new File(DB_PATH + DATABASE_NAME);
    return databaseFile.exists();        
}

/**
 * Copies your database from your local assets-folder to the just created empty database in the
 * system folder, from where it can be accessed and handled.
 * This is done by transferring byte stream.
 * */
private void copyDataBase() throws IOException{ 
    //Open your local db as the input stream
    InputStream myInput = context.getAssets().open(DATABASE_NAME); 
    // Path to the just created empty db
    String outFileName = DB_PATH + DATABASE_NAME; 
    //Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName); 
    //transfer bytes from the input file to the output file
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0){
        myOutput.write(buffer, 0, length);
    }

    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close(); 
}

/**
 * This method opens the data base connection.
 * First it create the path up till data base of the device.
 * Then create connection with data base.
 */
public void openDataBase() throws SQLException{      
    //Open the database
    String myPath = DB_PATH + DATABASE_NAME;
    sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);  
}

/**
 * This Method is used to close the data base connection.
 */
@Override
public synchronized void close() { 
    if(sqliteDataBase != null)
        sqliteDataBase.close(); 
    super.close(); 
}

/**
* Apply your methods and class to fetch data using raw or queries on data base using 
* following demo example code as:
*/
public String getUserNameFromDB(){
    String query = "select User_First_Name From "+TABLE_USER_DETAILS;
    Cursor cursor = sqliteDataBase.rawQuery(query, null);
    String userName = null;
    if(cursor.getCount()>0){
        if(cursor.moveToFirst()){
    do{
                userName = cursor.getString(0);
            }while (cursor.moveToNext());
        }
    }
    return userName;
}


@Override
public void onCreate(SQLiteDatabase db) {
    // No need to write the create table query.
    // As we are using Pre built data base.
    // Which is ReadOnly.
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // No need to write the update table query.
    // As we are using Pre built data base.
    // Which is ReadOnly.
    // We should not update it as requirements of application.
}   
}

Hope this will help you...

Interfaces vs. abstract classes

Another thing to consider is that, since there is no multiple inheritance, if you want a class to be able to implement/inherit from your interface/abstract class, but inherit from another base class, use an interface.

How do you properly return multiple values from a Promise?

Simply return a tuple:

    async add(dto: TDto): Promise<TDto> {
    console.log(`${this.storeName}.add(${dto})`);
    return firebase.firestore().collection(this.dtoName)
      .withConverter<TDto>(this.converter)
      .add(dto)
      .then(d => [d.update(this.id, d.id), d.id] as [any, string])
      .then(x => this.get(x[1]));
  }

How do I find all of the symlinks in a directory tree?

Kindly find below one liner bash script command to find all broken symbolic links recursively in any linux based OS

a=$(find / -type l); for i in $(echo $a); do file $i ; done |grep -i broken 2> /dev/null

How to compare two dates to find time difference in SQL Server 2005, date manipulation

You can use the DATEDIFF function to get the difference in minutes, seconds, days etc.

SELECT DATEDIFF(MINUTE,job_start,job_end)

MINUTE obviously returns the difference in minutes, you can also use DAY, HOUR, SECOND, YEAR (see the books online link for the full list).

If you want to get fancy you can show this differently for example 75 minutes could be displayed like this: 01:15:00:0

Here is the code to do that for both SQL Server 2005 and 2008

-- SQL Server 2005
SELECT CONVERT(VARCHAR(10),DATEADD(MINUTE,DATEDIFF(MINUTE,job_start,job_end),'2011-01-01 00:00:00.000'),114)

-- SQL Server 2008
SELECT CAST(DATEADD(MINUTE,DATEDIFF(MINUTE,job_start,job_end),'2011-01-01 00:00:00.000') AS TIME)

How to resize image (Bitmap) to a given size?

You can scale bitmaps by using canvas.drawBitmap with providing matrix, for example:

public static Bitmap scaleBitmap(Bitmap bitmap, int wantedWidth, int wantedHeight) {
        Bitmap output = Bitmap.createBitmap(wantedWidth, wantedHeight, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        Matrix m = new Matrix();
        m.setScale((float) wantedWidth / bitmap.getWidth(), (float) wantedHeight / bitmap.getHeight());
        canvas.drawBitmap(bitmap, m, new Paint());

        return output;
    }

How to split csv whose columns may contain ,

With Cinchoo ETL - an open source library, it can automatically handles columns values containing separators.

string csv = @"2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,""Corvallis, OR"",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";

using (var p = ChoCSVReader.LoadText(csv)
    )
{
    Console.WriteLine(p.Dump());
}

Output:

Key: Column1 [Type: String]
Value: 2
Key: Column2 [Type: String]
Value: 1016
Key: Column3 [Type: String]
Value: 7/31/2008 14:22
Key: Column4 [Type: String]
Value: Geoff Dalgas
Key: Column5 [Type: String]
Value: 6/5/2011 22:21
Key: Column6 [Type: String]
Value: http://stackoverflow.com
Key: Column7 [Type: String]
Value: Corvallis, OR
Key: Column8 [Type: String]
Value: 7679
Key: Column9 [Type: String]
Value: 351
Key: Column10 [Type: String]
Value: 81
Key: Column11 [Type: String]
Value: b437f461b3fd27387c5d8ab47a293d35
Key: Column12 [Type: String]
Value: 34

For more information, please visit codeproject article.

Hope it helps.

Java finished with non-zero exit value 2 - Android Gradle

This error is because of using more number of libraries.in my case 'compile 'com.google.android.gms:play-services-9.4.0' caused this error.To avoid this error use necessary libraries.for example if you want to use Maps in your app.Then use compile 'com.google.android.gms:play-services-maps:9.4.0'.while adding google play services dependency specify the needed libraries only.by default it includes all the libraries.

How to set a Header field on POST a form?

If you are using JQuery with Form plugin, you can use:

$('#myForm').ajaxSubmit({
    headers: {
        "foo": "bar"
    }
});

Source: https://stackoverflow.com/a/31955515/9469069

iPad browser WIDTH & HEIGHT standard

The pixel width and height of your page will depend on orientation as well as the meta viewport tag, if specified. Here are the results of running jquery's $(window).width() and $(window).height() on iPad 1 browser.

When page has no meta viewport tag:

  • Portrait: 980x1208
  • Landscape: 980x661

When page has either of these two meta tags:

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1">

  • Portrait: 768x946
  • Landscape: 1024x690

With <meta name="viewport" content="width=device-width">:

  • Portrait: 768x946
  • Landscape: 768x518

With <meta name="viewport" content="height=device-height">:

  • Portrait: 980x1024
  • Landscape: 980x1024

With <meta name="viewport" content="height=device-height,width=device-width">:

  • Portrait: 768x1024
  • Landscape: 768x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width,height=device-height">

  • Portrait: 768x1024
  • Landscape: 1024x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,height=device-height">

  • Portrait: 831x1024
  • Landscape: 1520x1024

Why is using the JavaScript eval function a bad idea?

It's not always a bad idea. Take for example, code generation. I recently wrote a library called Hyperbars which bridges the gap between virtual-dom and handlebars. It does this by parsing a handlebars template and converting it to hyperscript which is subsequently used by virtual-dom. The hyperscript is generated as a string first and before returning it, eval() it to turn it into executable code. I have found eval() in this particular situation the exact opposite of evil.

Basically from

<div>
    {{#each names}}
        <span>{{this}}</span>
    {{/each}}
</div>

To this

(function (state) {
    var Runtime = Hyperbars.Runtime;
    var context = state;
    return h('div', {}, [Runtime.each(context['names'], context, function (context, parent, options) {
        return [h('span', {}, [options['@index'], context])]
    })])
}.bind({}))

The performance of eval() isn't an issue in a situation like this because you only need to interpret the generated string once and then reuse the executable output many times over.

You can see how the code generation was achieved if you're curious here.

How to call a method in another class in Java?

Try this :

public void addTeacherToClassRoom(classroom myClassRoom, String TeacherName)
{
    myClassRoom.setTeacherName(TeacherName);
}

The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

    * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

Best practices

  • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

  • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

  • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

  • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

  • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14/17/… References:

  • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

  • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

  • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

  • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

how to check if object already exists in a list

If you use EF core add

 .UseSerialColumn();

Example

modelBuilder.Entity<JobItem>(entity =>
        {
            entity.ToTable("jobs");

            entity.Property(e => e.Id)
                .HasColumnName("id")
                .UseSerialColumn();
});

Is __init__.py not required for packages in Python 3.3+

Overview

@Mike's answer is correct but too imprecise. It is true that Python 3.3+ supports Implicit Namespace Packages that allows it to create a package without an __init__.py file. This is called a namespace package in contrast to a regular package which does have an __init__.py file (empty or not empty).

However, creating a namespace package should ONLY be done if there is a need for it. For most use cases and developers out there, this doesn't apply so you should stick with EMPTY __init__.py files regardless.

Namespace package use case

To demonstrate the difference between the two types of python packages, lets look at the following example:

google_pubsub/              <- Package 1
    google/                 <- Namespace package (there is no __init__.py)
        cloud/              <- Namespace package (there is no __init__.py)
            pubsub/         <- Regular package (with __init__.py)
                __init__.py <- Required to make the package a regular package
                foo.py

google_storage/             <- Package 2
    google/                 <- Namespace package (there is no __init__.py)
        cloud/              <- Namespace package (there is no __init__.py)
            storage/        <- Regular package (with __init__.py)
                __init__.py <- Required to make the package a regular package
                bar.py

google_pubsub and google_storage are separate packages but they share the same namespace google/cloud. In order to share the same namespace, it is required to make each directory of the common path a namespace package, i.e. google/ and cloud/. This should be the only use case for creating namespace packages, otherwise, there is no need for it.

It's crucial that there are no __init__py files in the google and google/cloud directories so that both directories can be interpreted as namespace packages. In Python 3.3+ any directory on the sys.path with a name that matches the package name being looked for will be recognized as contributing modules and subpackages to that package. As a result, when you import both from google_pubsub and google_storage, the Python interpreter will be able to find them.

This is different from regular packages which are self-contained meaning all parts live in the same directory hierarchy. When importing a package and the Python interpreter encounters a subdirectory on the sys.path with an __init__.py file, then it will create a single directory package containing only modules from that directory, rather than finding all appropriately named subdirectories outside that directory. This is perfectly fine for packages that don't want to share a namespace. I highly recommend taking a look at Traps for the Unwary in Python’s Import System to get a better understanding of how Python importing behaves with regular and namespace package and what __init__.py traps to watch out for.

Summary

  • Only skip __init__.py files if you want to create namespace packages. Only create namespace packages if you have different libraries that reside in different locations and you want them each to contribute a subpackage to the parent package, i.e. the namespace package.
  • Keep on adding empty __init__py to your directories because 99% of the time you just want to create regular packages. Also, Python tools out there such as mypy and pytest require empty __init__.py files to interpret the code structure accordingly. This can lead to weird errors if not done with care.

Resources

My answer only touches the surface of how regular packages and namespace packages work so take a look at the following resources for further information:

How do you make websites with Java?

While a lot of others should be mentioned, Apache Wicket should be preferred.

Wicket doesn't just reduce lots of boilerplate code, it actually removes it entirely and you can work with excellent separation of business code and markup without mixing the two and a wide variety of other things you can read about from the website.

What's the difference between KeyDown and KeyPress in .NET?

Keydown is pressing the key without releasing it, Keypress is a complete press-and-release cycle.

Put another way, KeyDown + KeyUp = Keypress

What is the best Java email address validation method?

Using the official java email package is the easiest:

public static boolean isValidEmailAddress(String email) {
   boolean result = true;
   try {
      InternetAddress emailAddr = new InternetAddress(email);
      emailAddr.validate();
   } catch (AddressException ex) {
      result = false;
   }
   return result;
}

Android design support library for API 28 (P) not working

Google has introduced new AndroidX dependencies. You need to migrate to AndroidX, it's simple.

I replaced all dependencies to AndroidX dependencies

Old design dependency

implementation 'com.android.support:design:28.0.0'

New AndroidX design dependency

implementation 'com.google.android.material:material:1.0.0-rc01'

you can find AndroidX dependencies here https://developer.android.com/jetpack/androidx/migrate


Automatic AndroidX migration option (supported on android studio 3.3+)

Migrate an existing project to use AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.

How to solve PHP error 'Notice: Array to string conversion in...'

<?php
ob_start();
var_dump($_POST['C']);
$result = ob_get_clean();
?>

if you want to capture the result in a variable

How to raise a ValueError?

Here's a revised version of your code which still works plus it illustrates how to raise a ValueError the way you want. By-the-way, I think find_last(), find_last_index(), or something simlar would be a more descriptive name for this function. Adding to the possible confusion is the fact that Python already has a container object method named __contains__() that does something a little different, membership-testing-wise.

def contains(char_string, char):
    largest_index = -1
    for i, ch in enumerate(char_string):
        if ch == char:
            largest_index = i
    if largest_index > -1:  # any found?
        return largest_index  # return index of last one
    else:
        raise ValueError('could not find {!r} in {!r}'.format(char, char_string))

print(contains('mississippi', 's'))  # -> 6
print(contains('bababa', 'k'))  # ->
Traceback (most recent call last):
  File "how-to-raise-a-valueerror.py", line 15, in <module>
    print(contains('bababa', 'k'))
  File "how-to-raise-a-valueerror.py", line 12, in contains
    raise ValueError('could not find {} in {}'.format(char, char_string))
ValueError: could not find 'k' in 'bababa'

Update — A substantially simpler way

Wow! Here's a much more concise version—essentially a one-liner—that is also likely faster because it reverses (via [::-1]) the string before doing a forward search through it for the first matching character and it does so using the fast built-in string index() method. With respect to your actual question, a nice little bonus convenience that comes with using index() is that it already raises a ValueError when the character substring isn't found, so nothing additional is required to make that happen.

Here it is along with a quick unit test:

def contains(char_string, char):
    #  Ending - 1 adjusts returned index to account for searching in reverse.
    return len(char_string) - char_string[::-1].index(char) - 1

print(contains('mississippi', 's'))  # -> 6
print(contains('bababa', 'k'))  # ->
Traceback (most recent call last):
  File "better-way-to-raise-a-valueerror.py", line 9, in <module>
    print(contains('bababa', 'k'))
  File "better-way-to-raise-a-valueerror", line 6, in contains
    return len(char_string) - char_string[::-1].index(char) - 1
ValueError: substring not found

Coding Conventions - Naming Enums

enum MyEnum {VALUE_1,VALUE_2}

is (approximately) like saying

class MyEnum {

    public static final MyEnum VALUE_1 = new MyEnum("VALUE_1");
    public static final MyEnum VALUE_2 = new MyEnum("VALUE_2");

    private final name;

    private MyEnum(String name) {
        this.name = name;
    }

    public String name() { return this.name }
}

so I guess the all caps is strictly more correct, but still I use the class name convention since I hate all caps wherever

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

Use ubuntu on windows store

windows subsystem for linux

, your git push will work across different accounts.

Delaying a jquery script until everything else has loaded

It turns out that because of a peculiar mixture of javascript frameworks that I needed to initiate the script using an event listener provide by one of the other frameworks.

insert vertical divider line between two nested divs, not full height

Can't think of a only css solution, but couldn't you just had a div between those 2 and set in the css the properties to look like a line like shown in the image? If you are using divs as they were table cells this is a pretty simple solution to the problem

How to launch html using Chrome at "--allow-file-access-from-files" mode?

If you are using a mac you can use the following terminal command:

open -a Google\ Chrome --args --allow-file-access-from-files

How can get the text of a div tag using only javascript (no jQuery)

Because textContent is not supported in IE8 and older, here is a workaround:

var node = document.getElementById('test'),
var text  = node.textContent || node.innerText;
alert(text);

innerText does work in IE.

how to read a long multiline string line by line in python

What about using .splitlines()?

for line in textData.splitlines():
    print(line)
    lineResult = libLAPFF.parseLine(line)

Truncate (not round off) decimal numbers in javascript

Consider taking advantage of the double tilde: ~~.

Take in the number. Multiply by significant digits after the decimal so that you can truncate to zero places with ~~. Divide that multiplier back out. Profit.

function truncator(numToTruncate, intDecimalPlaces) {    
    var numPower = Math.pow(10, intDecimalPlaces); // "numPowerConverter" might be better
    return ~~(numToTruncate * numPower)/numPower;
}

I'm trying to resist wrapping the ~~ call in parens; order of operations should make that work correctly, I believe.

alert(truncator(5.1231231, 1)); // is 5.1

alert(truncator(-5.73, 1)); // is -5.7

alert(truncator(-5.73, 0)); // is -5

JSFiddle link.

EDIT: Looking back over, I've unintentionally also handled cases to round off left of the decimal as well.

alert(truncator(4343.123, -2)); // gives 4300.

The logic's a little wacky looking for that usage, and may benefit from a quick refactor. But it still works. Better lucky than good.

How do I convert from a money datatype in SQL server?

You can try like this:

SELECT PARSENAME('$'+ Convert(varchar,Convert(money,@MoneyValue),1),2)

Free Rest API to retrieve current datetime as string (timezone irrelevant)

This API gives you the current time and several formats in JSON - https://market.mashape.com/parsify/format#time. Here's a sample response:

{
  "time": {
    "daysInMonth": 31,
    "millisecond": 283,
    "second": 42,
    "minute": 55,
    "hour": 1,
    "date": 6,
    "day": 3,
    "week": 10,
    "month": 2,
    "year": 2013,
    "zone": "+0000"
  },
  "formatted": {
    "weekday": "Wednesday",
    "month": "March",
    "ago": "a few seconds",
    "calendar": "Today at 1:55 AM",
    "generic": "2013-03-06T01:55:42+00:00",
    "time": "1:55 AM",
    "short": "03/06/2013",
    "slim": "3/6/2013",
    "hand": "Mar 6 2013",
    "handTime": "Mar 6 2013 1:55 AM",
    "longhand": "March 6 2013",
    "longhandTime": "March 6 2013 1:55 AM",
    "full": "Wednesday, March 6 2013 1:55 AM",
    "fullSlim": "Wed, Mar 6 2013 1:55 AM"
  },
  "array": [
    2013,
    2,
    6,
    1,
    55,
    42,
    283
  ],
  "offset": 1362534942283,
  "unix": 1362534942,
  "utc": "2013-03-06T01:55:42.283Z",
  "valid": true,
  "integer": false,
  "zone": 0
}

Changing the space between each item in Bootstrap navbar

I would suggest you just evenly space them as shown in this answer here

.navbar ul {
  list-style-type: none;
  padding: 0;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  flex-wrap: nowrap; /* assumes you only want one row */
}

How to remove the character at a given index from a string in C?

int chartoremove = 1;

strncpy(word2, word, chartoremove);
strncpy(((char*)word2)+chartoremove, ((char*)word)+chartoremove+1,
    strlen(word)-1-chartoremove);

Ugly as hell

Object of class mysqli_result could not be converted to string in

The mysqli_query() method returns an object resource to your $result variable, not a string.

You need to loop it up and then access the records. You just can't directly use it as your $result variable.

while ($row = $result->fetch_assoc()) {
    echo $row['classtype']."<br>";
}

Is there a limit to the length of a GET request?

Not in the RFC, no, but there are practical limits.

The HTTP protocol does not place any a priori limit on the length of a URI. Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs. A server SHOULD return 414 (Request-URI Too Long) status if a URI is longer than the server can handle (see section 10.4.15).

Note: Servers should be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations may not properly support these lengths.

Multiple simultaneous downloads using Wget?

wget cant download in multiple connections, instead you can try to user other program like aria2.

'ssh-keygen' is not recognized as an internal or external command

Just go to heroku.bat and add:

@SET PATH="D:\Program Files (x86)\Git\bin";%PATH% after @SET PATH=%HEROKU_RUBY%;%PATH%

in my case it's in D:\Program Files (x86)\Git\bin, change it to the path you've installed Git to. (i just left it with my path so it will be clearer on how to write this)

How to schedule a periodic task in Java?

If your application is already using Spring framework, you have Scheduling built in

How to override the properties of a CSS class using another CSS class

LIFO is the way browser parses CSS properties..If you are using Sass declare a variable called as

"$header-background: red;"

use it instead of directly assigning values like red or blue. When you want to override just reassign the value to

"$header-background:blue"

then

background-color:$header-background;

it should smoothly override. Using "!important" is not always the right choice..Its just a hotfix

How to center buttons in Twitter Bootstrap 3?

<div class="row">
  <div class="col-sm-12">
    <div class="text-center">
      <button class="btn btn-primary" id="singlebutton"> Next Step!</button>
    </div>
  </div>
</div>

Django DateField default options

This should do the trick:

models.DateTimeField(_("Date"), auto_now_add = True)

Remove white space below image

I've set up a JSFiddle to test several different solutions to this problem. Based on the [vague] criteria of

1) Maximum flexibility

2) No weird behavior

The accepted answer here of

img { display: block; }

which is recommended by a lot of people (such as in this excellent article), actually ranks fourth.

1st, 2nd, and 3rd place are all a toss-up between these three solutions:

1) The solution given by @Dave Kok and @Hasan Gursoy:

img { vertical-align: top; } /* or bottom */

pros:

  • All display values work on both the parent and img.
  • No very strange behavior; any siblings of the img fall where you'd expect them to.
  • Very efficient.

cons:

  • In the [perfectly valid] case of both the parent and img having `display: inline`, the value of this property can determine the position of the img's parent (a bit strange).

2) Setting font-size: 0; on the parent element:

.parent {
    font-size: 0;
    vertical-align: top;
}
.parent > * {
    font-size: 16px;
    vertical-align: top;
}

Since this one [kind of] requires vertical-align: top on the img, this is basically an extension of the 1st solution.

pros:

  • All display values work on both the parent and img.
  • No very strange behavior; any siblings of the img fall where you'd expect them to.
  • Fixes the inline whitespace problem for any siblings of the img.
  • Although this still moves the position of the parent in the case of the parent and img both having `display: inline`, at least you can't see the parent anymore.

cons:

  • Less efficient code.
  • This assumes "correct" markup; if the img has text node siblings, they won't show up.

3) Setting line-height: 0 on the parent element:

.parent {
    line-height: 0;
    vertical-align: top;
}
.parent > * {
    line-height: 1.15;
    vertical-align: top;
}

Similar to the 2nd solution in that, to make it fully flexible, it basically becomes an extension of the 1st.

pros:

  • Behaves like the first two solutions on all display combinations except when the parent and img have `display: inline`.

cons:

  • Less efficient code.
  • In the case of both the parent and img having `display: inline`, we get all sorts of crazy. (Maybe playing with the `line-height` property isn't the best idea...)

So there you have it. I hope this helps some poor soul.

Convert String[] to comma separated string in java

Android developers are probably looking for TextUtils.join

Android docs: http://developer.android.com/reference/android/text/TextUtils.html

Code:

String[] name = {"amit", "rahul", "surya"};
TextUtils.join(",",name)

How do I convert a String to a BigInteger?

For a loop where you want to convert an array of strings to an array of bigIntegers do this:

String[] unsorted = new String[n]; //array of Strings
BigInteger[] series = new BigInteger[n]; //array of BigIntegers

for(int i=0; i<n; i++){
    series[i] = new BigInteger(unsorted[i]); //convert String to bigInteger
}

How to add an extra column to a NumPy array

Assuming M is a (100,3) ndarray and y is a (100,) ndarray append can be used as follows:

M=numpy.append(M,y[:,None],1)

The trick is to use

y[:, None]

This converts y to a (100, 1) 2D array.

M.shape

now gives

(100, 4)

Selenium 2.53 not working on Firefox 47

In case anyone is wondering how to use Marionette in C#.

FirefoxProfile profile = new FirefoxProfile(); // Your custom profile
var service = FirefoxDriverService.CreateDefaultService("DirectoryContainingTheDriver", "geckodriver.exe");
// Set the binary path if you want to launch the release version of Firefox.
service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe";
var option = new FirefoxProfileOptions(profile) { IsMarionette = true };
var driver = new FirefoxDriver(
    service,
    option,
    TimeSpan.FromSeconds(30));

Overriding FirefoxOptions to provide the function to add additional capability and set Firefox profile because selenium v53 doesn't provide that function yet.

public class FirefoxProfileOptions : FirefoxOptions
{
    private DesiredCapabilities _capabilities;

    public FirefoxProfileOptions()
        : base()
    {
        _capabilities = DesiredCapabilities.Firefox();
        _capabilities.SetCapability("marionette", this.IsMarionette);
    }

    public FirefoxProfileOptions(FirefoxProfile profile)
        : this()
    {
        _capabilities.SetCapability(FirefoxDriver.ProfileCapabilityName, profile.ToBase64String());
    }

    public override void AddAdditionalCapability(string capabilityName, object capabilityValue)
    {
        _capabilities.SetCapability(capabilityName, capabilityValue);
    }

    public override ICapabilities ToCapabilities()
    {
        return _capabilities;
    }
}

Note: Launching with profile doesn't work with FF 47, it works with FF 50 Nightly.

However, we tried to convert our test to use Marionette, and it's just not viable at the moment because the implementation of the driver is either not completed or buggy. I'd suggest people downgrade their Firefox at this moment.

Using IF ELSE statement based on Count to execute different Insert statements

There are many, many ways to code this, but here is one possible way. I'm assuming MS SQL

We'll start by getting row count (Another Quick Example) and then do if/else

-- Let's get our row count and assign it to a var that will be used
--    in our if stmt 
DECLARE @HasExistingRows int -- I'm assuming it can fit into an int
SELECT @HasExistingRows = Count(*) 
   ELSE 0 -- false
FROM
   INCIDENTS
WHERE {Your Criteria}
GROUP BY {Required Grouping}

Now we can do the If / Else Logic MSDN Docs

-- IF / Else / Begin / END Syntax
IF @HasExistingRows = 0 -- No Existing Rows
   BEGIN
      {Insert Logic for No Existing Rows}
   END
ELSE -- existing rows are found
   BEGIN
      {Insert logic for existing rows}
   END

Another faster way (inspired by Mahmoud Gamal's comment):

Forget the whole variable creation / assignment - look up "EXISTS" - MSDN Docs 2.

IF EXISTS ({SELECT Query})
   BEGIN
      {INSERT Version 1}
   END
ELSE
   BEGIN
      {INSERT version 2}
   END

Drop multiple tables in one shot in MySQL

SET foreign_key_checks = 0;
DROP TABLE IF EXISTS a,b,c;
SET foreign_key_checks = 1;

Then you do not have to worry about dropping them in the correct order, nor whether they actually exist.

N.B. this is for MySQL only (as in the question). Other databases likely have different methods for doing this.

openssl s_client using a proxy

Even with openssl v1.1.0 I had some problems passing our proxy, e.g. s_client: HTTP CONNECT failed: 400 Bad Request That forced me to write a minimal Java-class to show the SSL-Handshake

    public static void main(String[] args) throws IOException, URISyntaxException {
    HttpHost proxy = new HttpHost("proxy.my.company", 8080);
    DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
    CloseableHttpClient httpclient = HttpClients.custom()
            .setRoutePlanner(routePlanner)
            .build();
    URI uri = new URIBuilder()
            .setScheme("https")
            .setHost("www.myhost.com")
            .build();
    HttpGet httpget = new HttpGet(uri);
    httpclient.execute(httpget);
}

With following dependency:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
        <type>jar</type>
    </dependency>

you can run it with Java SSL Logging turned on

This should produce nice output like

trustStore provider is :
init truststore
adding as trusted cert:
  Subject: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
  Issuer:  CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
  Algorithm: RSA; Serial number: 0xc3517
  Valid from Mon Jun 21 06:00:00 CEST 1999 until Mon Jun 22 06:00:00 CEST 2020

adding as trusted cert:
  Subject: CN=SecureTrust CA, O=SecureTrust Corporation, C=US
  Issuer:  CN=SecureTrust CA, O=SecureTrust Corporation, C=US
(....)

"Debug only" code that should run only when "turned on"

You could try this if you only need the code to run when you have a debugger attached to the process.

if (Debugger.IsAttached)
{
     // do some stuff here
}

Waiting until two async blocks are executed before starting another block

I know you asked about GCD, but if you wanted, NSOperationQueue also handles this sort of stuff really gracefully, e.g.:

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"Starting 3");
}];

NSOperation *operation;

operation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"Starting 1");
    sleep(7);
    NSLog(@"Finishing 1");
}];

[completionOperation addDependency:operation];
[queue addOperation:operation];

operation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"Starting 2");
    sleep(5);
    NSLog(@"Finishing 2");
}];

[completionOperation addDependency:operation];
[queue addOperation:operation];

[queue addOperation:completionOperation];

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

This lovely detailed error is still present in 2019! I just want to add that if your web.config is valid and accessible it most likely is a dependency issue.

As mentioned by the OP it was a AJAX module, and as by others commonly the Rewrite module. Just keep your eyes open in your web.config what modules and libraries your tags are referencing to since the error code 0x8007000d can be about ANY dependency.

In my case I didn't realize the AspNetCore bundle was missing and had to be installed! So happy I found this post!!

Download & Install Xcode version without Premium Developer Account

Yes,
You can download Xcode with/without Paid (Premium) Apple Developer Account from below links.

Xcode 11

Xcode 10


For non-premium account/apple id: (Download Xcode 10 without Paid (Premium) Apple Developer Account from below link)

Apple Download Portal

Look at here: How to install & set command line tool


See here for older versions of Xcode (Which may need to authenticate your apple account):

Boolean operators ( &&, -a, ||, -o ) in Bash

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

How to remove trailing whitespace in code, using another script?

Save as fix_whitespace.py:

#!/usr/bin/env python
"""
Fix trailing whitespace and line endings (to Unix) in a file.
Usage: python fix_whitespace.py foo.py
"""

import os
import sys


def main():
    """ Parse arguments, then fix whitespace in the given file """
    if len(sys.argv) == 2:
        fname = sys.argv[1]
        if not os.path.exists(fname):
            print("Python file not found: %s" % sys.argv[1])
            sys.exit(1)
    else:
        print("Invalid arguments. Usage: python fix_whitespace.py foo.py")
        sys.exit(1)
    fix_whitespace(fname)


def fix_whitespace(fname):
    """ Fix whitespace in a file """
    with open(fname, "rb") as fo:
        original_contents = fo.read()
    # "rU" Universal line endings to Unix
    with open(fname, "rU") as fo:
        contents = fo.read()
    lines = contents.split("\n")
    fixed = 0
    for k, line in enumerate(lines):
        new_line = line.rstrip()
        if len(line) != len(new_line):
            lines[k] = new_line
            fixed += 1
    with open(fname, "wb") as fo:
        fo.write("\n".join(lines))
    if fixed or contents != original_contents:
        print("************* %s" % os.path.basename(fname))
    if fixed:
        slines = "lines" if fixed > 1 else "line"
        print("Fixed trailing whitespace on %d %s" \
              % (fixed, slines))
    if contents != original_contents:
        print("Fixed line endings to Unix (\\n)")


if __name__ == "__main__":
    main()

CSS root directory

This problem that the "../" means step up (parent folder) link "../images/img.png" will not work because when you are using ajax like data passing to the web site from the server.

What you have to do is point the image location to root with "./" then the second folder (in this case the second folder is "images")

url("./images/img.png")

if you have folders like this

root -> content -> images

then you use url("./content/images/img.png"), remember your image will not visible in the editor window but when it passed to the browser using ajax it will display.

Data at the root level is invalid

I found that the example I was using had an xml document specification on the first line. I was using a stylesheet I got at this blog entry and the first line was

<?xmlversion="1.0"encoding="utf-8"?>

which was causing the error. When I removed that line, so that the stylesheet started with the line

<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

my transform worked. By the way, that blog post was the first good, easy-to follow example I have found for trying to get information from the XML definition of an SSIS package, but I did have to modify the paths in the example for my SSIS 2008 packages, so you might too. I also created a version to extract the "flow" from the precedence constraints. My final one looks like this:

    <xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" encoding="utf-8" />
    <xsl:template match="/">
    <xsl:text>From,To~</xsl:text>
    <xsl:text>
</xsl:text>
    <xsl:for-each select="//DTS:PrecedenceConstraints/DTS:PrecedenceConstraint">
      <xsl:value-of select="@DTS:From"/>
      <xsl:text>,</xsl:text>
      <xsl:value-of select="@DTS:To"/>
       <xsl:text>~</xsl:text>
      <xsl:text>
</xsl:text>
    </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

and gave me a CSV with the tilde as my line delimiter. I replaced that with a line feed in my text editor then imported into excel to get a with look at the data flow in the package.

Compress files while reading data from STDIN

Yes, gzip will let you do this. If you simply run gzip > foo.gz, it will compress STDIN to the file foo.gz. You can also pipe data into it, like some_command | gzip > foo.gz.

Simulate limited bandwidth from within Chrome?

Note, do not use Chrome's built in Speed Tester (it will show you unthrottled speed). Instead use another site, like Fast.com. That will show you properly throttled speeds.

Also, the throttling settings might be hidden and can be accessed from the network bar by clicking the tiny down arrow.

Jackson how to transform JsonNode to ArrayNode without casting?

In Java 8 you can do it like this:

import java.util.*;
import java.util.stream.*;

List<JsonNode> datasets = StreamSupport
    .stream(datasets.get("datasets").spliterator(), false)
    .collect(Collectors.toList())

PHPExcel - set cell type before writing a value in it

try this

$currencyFormat = '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)';
$textFormat='@';//'General','0.00','@'
$excel->getActiveSheet()->getStyle('B1')->getNumberFormat()->setFormatCode($currencyFormat);
$excel->getActiveSheet()->getStyle('C1')->getNumberFormat()->setFormatCode($textFormat);`

.gitignore and "The following untracked working tree files would be overwritten by checkout"

that's easy to solve, git is saying that you have the same files in both branches, therefore you have to delete the specific files from master branch and then you will be able to merge:

git merge "your branch"

I hope it works for you, I just solved my error. my error was:

error: The following untracked working tree files would be overwritten by merge:
        .vs/slnx.sqlite
Please move or remove them before you merge.
Aborting

Now it is working! In my case .vs/slnx.sqlite was generated by visual studio, I needed to close it before delete it.

Convert json data to a html table

I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.

Demo

_x000D_
_x000D_
var _table_ = document.createElement('table'),_x000D_
  _tr_ = document.createElement('tr'),_x000D_
  _th_ = document.createElement('th'),_x000D_
  _td_ = document.createElement('td');_x000D_
_x000D_
// Builds the HTML Table out of myList json data from Ivy restful service._x000D_
function buildHtmlTable(arr) {_x000D_
  var table = _table_.cloneNode(false),_x000D_
    columns = addAllColumnHeaders(arr, table);_x000D_
  for (var i = 0, maxi = arr.length; i < maxi; ++i) {_x000D_
    var tr = _tr_.cloneNode(false);_x000D_
    for (var j = 0, maxj = columns.length; j < maxj; ++j) {_x000D_
      var td = _td_.cloneNode(false);_x000D_
      cellValue = arr[i][columns[j]];_x000D_
      td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));_x000D_
      tr.appendChild(td);_x000D_
    }_x000D_
    table.appendChild(tr);_x000D_
  }_x000D_
  return table;_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records_x000D_
function addAllColumnHeaders(arr, table) {_x000D_
  var columnSet = [],_x000D_
    tr = _tr_.cloneNode(false);_x000D_
  for (var i = 0, l = arr.length; i < l; i++) {_x000D_
    for (var key in arr[i]) {_x000D_
      if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {_x000D_
        columnSet.push(key);_x000D_
        var th = _th_.cloneNode(false);_x000D_
        th.appendChild(document.createTextNode(key));_x000D_
        tr.appendChild(th);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  table.appendChild(tr);_x000D_
  return columnSet;_x000D_
}_x000D_
_x000D_
document.body.appendChild(buildHtmlTable([{_x000D_
    "name": "abc",_x000D_
    "age": 50_x000D_
  },_x000D_
  {_x000D_
    "age": "25",_x000D_
    "hobby": "swimming"_x000D_
  },_x000D_
  {_x000D_
    "name": "xyz",_x000D_
    "hobby": "programming"_x000D_
  }_x000D_
]));
_x000D_
_x000D_
_x000D_

Random number c++ in some range

int random(int min, int max) //range : [min, max]
{
   static bool first = true;
   if (first) 
   {  
      srand( time(NULL) ); //seeding for the first time only!
      first = false;
   }
   return min + rand() % (( max + 1 ) - min);
}

Unable to connect with remote debugger

uninstall your application, then run react-native run-android. then click debugging end in chrome replace http://localhost:8081/debugger-ui/, end run react-native run-android. if you still haven't succeeded try again

ExecJS and could not find a JavaScript runtime

In your gem file Uncomment this line.

19 # gem 'therubyracer', platforms: :ruby

And run bundle install

You are ready to work. :)

Converting between datetime, Timestamp and datetime64

One option is to use str, and then to_datetime (or similar):

In [11]: str(dt64)
Out[11]: '2012-05-01T01:00:00.000000+0100'

In [12]: pd.to_datetime(str(dt64))
Out[12]: datetime.datetime(2012, 5, 1, 1, 0, tzinfo=tzoffset(None, 3600))

Note: it is not equal to dt because it's become "offset-aware":

In [13]: pd.to_datetime(str(dt64)).replace(tzinfo=None)
Out[13]: datetime.datetime(2012, 5, 1, 1, 0)

This seems inelegant.

.

Update: this can deal with the "nasty example":

In [21]: dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100')

In [22]: pd.to_datetime(str(dt64)).replace(tzinfo=None)
Out[22]: datetime.datetime(2002, 6, 28, 1, 0)

Python Pandas counting and summing specific conditions

I usually use numpy sum over the logical condition column:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'Age' : [20,24,18,5,78]})
>>> np.sum(df['Age'] > 20)
2

This seems to me slightly shorter than the solution presented above

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

The problem is that you're trying to print a unicode character, but your terminal doesn't support it.

You can try installing language-pack-en package to fix that:

sudo apt-get install language-pack-en

which provides English translation data updates for all supported packages (including Python). Install different language package if necessary (depending which characters you're trying to print).

On some Linux distributions it's required in order to make sure that the default English locales are set-up properly (so unicode characters can be handled by shell/terminal). Sometimes it's easier to install it, than configuring it manually.

Then when writing the code, make sure you use the right encoding in your code.

For example:

open(foo, encoding='utf-8')

If you've still a problem, double check your system configuration, such as:

  • Your locale file (/etc/default/locale), which should have e.g.

    LANG="en_US.UTF-8"
    LC_ALL="en_US.UTF-8"
    

    or:

    LC_ALL=C.UTF-8
    LANG=C.UTF-8
    
  • Value of LANG/LC_CTYPE in shell.

  • Check which locale your shell supports by:

    locale -a | grep "UTF-8"
    

Demonstrating the problem and solution in fresh VM.

  1. Initialize and provision the VM (e.g. using vagrant):

    vagrant init ubuntu/trusty64; vagrant up; vagrant ssh
    

    See: available Ubuntu boxes..

  2. Printing unicode characters (such as trade mark sign like ):

    $ python -c 'print(u"\u2122");'
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 0: ordinal not in range(128)
    
  3. Now installing language-pack-en:

    $ sudo apt-get -y install language-pack-en
    The following extra packages will be installed:
      language-pack-en-base
    Generating locales...
      en_GB.UTF-8... /usr/sbin/locale-gen: done
    Generation complete.
    
  4. Now problem should be solved:

    $ python -c 'print(u"\u2122");'
    ™
    
  5. Otherwise, try the following command:

    $ LC_ALL=C.UTF-8 python -c 'print(u"\u2122");'
    ™
    

Force HTML5 youtube video

Whether or not YouTube videos play in HTML5 format depends on the setting at https://www.youtube.com/html5, per browser. Chrome prefers HTML5 playback automatically, but even the latest Firefox and Internet Explorer still use Flash if it is installed on the machine.

The parameter html5=1 does not do anything (anymore) now. (Note it is not even listed at https://developers.google.com/youtube/player_parameters.)

Git fatal: protocol 'https' is not supported

I encountered the same problem after freshly installing git on Windows 10 and running it for the first time. Restarting the bash window solved the problem.

Downloading a Google font and setting up an offline site that uses it

Check out google webfonts helper

It lets you download every web font of Google and suggests css code for the implementation. This tool also allows you to simply download all formats at once without the hassle.

Ever wanted to know where Google hosts their webfonts? This service might be handy if you want to download all .eot, .woff, .woff2, .svg, .ttf files of a font variant directly from google (normally your User-Agent would determine the best format).

Also take a look at their Github page.

How to disable javax.swing.JButton in java?

The code is very long so I can't paste all the code.

There could be any number of reasons why your code doesn't work. Maybe you declared the button variables twice so you aren't actually changing enabling/disabling the button like you think you are. Maybe you are blocking the EDT.

You need to create a SSCCE to post on the forum.

So its up to you to isolate the problem. Start with a simple frame thas two buttons and see if your code works. Once you get that working, then try starting a Thread that simply sleeps for 10 seconds to see if it still works.

Learn how the basice work first before writing a 200 line program.

Learn how to do some basic debugging, we are not mind readers. We can't guess what silly mistake you are doing based on your verbal description of the problem.

How do I check if a number is positive or negative in C#?

This code takes advantage of SIMD instructions to improve performance.

public static bool IsPositive(int n)
{
  var v = new Vector<int>(n);
  var result = Vector.GreaterThanAll(v, Vector<int>.Zero);
  return result;
}

possibly undefined macro: AC_MSG_ERROR

For Debian. Required packages are: m4 automake pkg-config libtool

How to get the instance id from within an ec2 instance?

For powershell people:

(New-Object System.Net.WebClient).DownloadString("http://169.254.169.254/latest/meta-data/instance-id")

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

 jquery.ajax({
            url: `//your api url`
            type: "GET",
            dataType: "json",
            success: function(data) {
                jQuery.each(data, function(index, value) {
                        console.log(data);
                        `All you API data is here`
                    }
                }
            });     

PHP: Limit foreach() statement?

this is best solution for me :)

$i=0;
foreach() if ($i < yourlimitnumber) {

$i +=1;
}

Installation of SQL Server Business Intelligence Development Studio

I figured it out and posted the answer in Can't run Business Intelligence Development Studio, file is not found.

I had this same problem. I am running .NET framework 3.5, SQL Server 2005, and Visual Studio 2008. While I was trying to run SQL Server Business Intelligence Development Studio the icon was grayed out and the devenv.exe file was not found.

I hope this helps.

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

First uninstall your application from the emulator:

adb -e uninstall your.application.package.name

Then try to install the application again.

How to implement reCaptcha for ASP.NET MVC?

I've successfully implemented ReCaptcha in the following way.
note: this is in VB, but can easily be converted

1] First grab a copy of the reCaptcha library

2] Then build a custom ReCaptcha HTML Helper

    ''# fix SO code coloring issue.
    <Extension()>
    Public Function reCaptcha(ByVal htmlHelper As HtmlHelper) As MvcHtmlString
        Dim captchaControl = New Recaptcha.RecaptchaControl With {.ID = "recaptcha",
                                                                  .Theme = "clean",
                                                                  .PublicKey = "XXXXXX",
                                                                  .PrivateKey = "XXXXXX"}
        Dim htmlWriter = New HtmlTextWriter(New IO.StringWriter)
        captchaControl.RenderControl(htmlWriter)
        Return MvcHtmlString.Create(htmlWriter.InnerWriter.ToString)
    End Function

3] From here you need a re-usable server side validator

Public Class ValidateCaptchaAttribute : Inherits ActionFilterAttribute
    Private Const CHALLENGE_FIELD_KEY As String = "recaptcha_challenge_field"
    Private Const RESPONSE_FIELD_KEY As String = "recaptcha_response_field"

    Public Overrides Sub OnActionExecuting(ByVal filterContext As ActionExecutingContext)

        If IsNothing(filterContext.HttpContext.Request.Form(CHALLENGE_FIELD_KEY)) Then
            ''# this will push the result value into a parameter in our Action
            filterContext.ActionParameters("CaptchaIsValid") = True
            Return
        End If

        Dim captchaChallengeValue = filterContext.HttpContext.Request.Form(CHALLENGE_FIELD_KEY)
        Dim captchaResponseValue = filterContext.HttpContext.Request.Form(RESPONSE_FIELD_KEY)

        Dim captchaValidtor = New RecaptchaValidator() With {.PrivateKey = "xxxxx",
                                                                       .RemoteIP = filterContext.HttpContext.Request.UserHostAddress,
                                                                       .Challenge = captchaChallengeValue,
                                                                       .Response = captchaResponseValue}

        Dim recaptchaResponse = captchaValidtor.Validate()

        ''# this will push the result value into a parameter in our Action
        filterContext.ActionParameters("CaptchaIsValid") = recaptchaResponse.IsValid

        MyBase.OnActionExecuting(filterContext)
    End Sub

above this line is reusable **ONE TIME** code


below this line is how easy it is to implement reCaptcha over and over

Now that you have your re-usable code... all you need to do is add the captcha to your View.

<%: Html.reCaptcha %>

And when you post the form to your controller...

    ''# Fix SO code coloring issues
    <ValidateCaptcha()>
    <AcceptVerbs(HttpVerbs.Post)>
    Function Add(ByVal CaptchaIsValid As Boolean, ByVal [event] As Domain.Event) As ActionResult


        If Not CaptchaIsValid Then ModelState.AddModelError("recaptcha", "*")


        '#' Validate the ModelState and submit the data.
        If ModelState.IsValid Then
            ''# Post the form
        Else
            ''# Return View([event])
        End If
    End Function

Log4net does not write the log in the log file

For me I had to move Logger to a Nuget Package. Below code need to be added in NuGet package project.

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")]

See https://gurunadhduvvuru.wordpress.com/2020/04/30/log4net-issues-when-moved-it-to-a-nuget-package/ for more details.

New warnings in iOS 9: "all bitcode will be dropped"

To fix the issues with the canOpenURL failing. This is because of the new App Transport Security feature in iOS9

Read this post to fix that issue http://discoverpioneer.com/blog/2015/09/18/updating-facebook-integration-for-ios-9/

python multithreading wait till all threads finished

Put the threads in a list and then use the Join method

 threads = []

 t = Thread(...)
 threads.append(t)

 ...repeat as often as necessary...

 # Start all threads
 for x in threads:
     x.start()

 # Wait for all of them to finish
 for x in threads:
     x.join()

Limiting Python input strings to certain characters and lengths

if any( [ i>'z' or i<'a' for i in raw_input]):
    print "Error: Contains illegal characters"
elif len(raw_input)>15:
    print "Very long string"

Rebase array keys after unsetting elements

Use array_splice rather than unset:

$array = array(1,2,3,4,5);
foreach($array as $i => $info)
{
  if($info == 1 || $info == 2)
  {
    array_splice($array, $i, 1);
  }
}

print_r($array);

Working sample here.

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"
end

In Rails 3.x this is the way to specify the table name.

Import a custom class in Java

First off, avoid using the default package.

Second of all, you don't need to import the class; it's in the same package.

What's the best strategy for unit-testing database-driven applications?

I'm always running tests against an in-memory DB (HSQLDB or Derby) for these reasons:

  • It makes you think which data to keep in your test DB and why. Just hauling your production DB into a test system translates to "I have no idea what I'm doing or why and if something breaks, it wasn't me!!" ;)
  • It makes sure the database can be recreated with little effort in a new place (for example when we need to replicate a bug from production)
  • It helps enormously with the quality of the DDL files.

The in-memory DB is loaded with fresh data once the tests start and after most tests, I invoke ROLLBACK to keep it stable. ALWAYS keep the data in the test DB stable! If the data changes all the time, you can't test.

The data is loaded from SQL, a template DB or a dump/backup. I prefer dumps if they are in a readable format because I can put them in VCS. If that doesn't work, I use a CSV file or XML. If I have to load enormous amounts of data ... I don't. You never have to load enormous amounts of data :) Not for unit tests. Performance tests are another issue and different rules apply.

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

$data = array( 
    'name'      => $_POST['name'] , 
    'groupname' => $_POST['groupname'], 
    'age'       => $_POST['age']
);

$this->db->where('id', $_POST['id']);

$this->db->update('tbl_user', $data);

How to remove spaces from a string using JavaScript?

This?

str = str.replace(/\s/g, '');

Example

_x000D_
_x000D_
var str = '/var/www/site/Brand new document.docx';_x000D_
_x000D_
document.write( str.replace(/\s/g, '') );
_x000D_
_x000D_
_x000D_


Update: Based on this question, this:

str = str.replace(/\s+/g, '');

is a better solution. It produces the same result, but it does it faster.

The Regex

\s is the regex for "whitespace", and g is the "global" flag, meaning match ALL \s (whitespaces).

A great explanation for + can be found here.

As a side note, you could replace the content between the single quotes to anything you want, so you can replace whitespace with any other string.

Is it possible to get only the first character of a String?

Here I am taking Mobile No From EditText It may start from +91 or 0 but i am getting actual 10 digits. Hope this will help you.

              String mob=edit_mobile.getText().toString();
                    if (mob.length() >= 10) {
                        if (mob.contains("+91")) {
                            mob= mob.substring(3, 13);
                        }
                        if (mob.substring(0, 1).contains("0")) {
                            mob= mob.substring(1, 11);
                        }
                        if (mob.contains("+")) {
                            mob= mob.replace("+", "");
                        }
                        mob= mob.substring(0, 10);
                        Log.i("mob", mob);

                    }

Unexpected character encountered while parsing value

In my case, I was getting an error on JsonConvert.PopulateObject(). My request was returning JSON that was wrapped in an extra pair of '[ ]' brackets, making my result an array of one object rather than just an object. Here's what I did to get inside these brackets (only for that type of model):

           T jsonResponse = new T();
                var settings = new JsonSerializerSettings
                {
                    DateParseHandling = DateParseHandling.DateTimeOffset,
                    NullValueHandling = NullValueHandling.Ignore,
                };
                var jRslt = response.Content.ReadAsStringAsync().Result;
                if (jsonResponse.GetType() == typeof(myProject.Models.myModel))
                {
                    var dobj = JsonConvert.DeserializeObject<myModel[]>(jRslt);
                    var y = dobj.First();
                    var szObj = JsonConvert.SerializeObject(y);
                    JsonConvert.PopulateObject(szObj, jsonResponse, settings);
                }
                else
                {
                    JsonConvert.PopulateObject(jRslt, jsonResponse);
                }

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Try this query -

SELECT 
  t2.company_name,
  t2.expose_new,
  t2.expose_used,
  t1.title,
  t1.seller,
  t1.status,
  CASE status
      WHEN 'New' THEN t2.expose_new
      WHEN 'Used' THEN t2.expose_used
      ELSE NULL
  END as 'expose'
FROM
  `products` t1
JOIN manufacturers t2
  ON
    t2.id = t1.seller
WHERE
  t1.seller = 4238

How to pretty-print a numpy.array without scientific notation and with given precision?

Years later, another one is below. But for everyday use I just

np.set_printoptions( threshold=20, edgeitems=10, linewidth=140,
    formatter = dict( float = lambda x: "%.3g" % x ))  # float arrays %.3g

''' printf( "... %.3g ... %.1f  ...", arg, arg ... ) for numpy arrays too

Example:
    printf( """ x: %.3g   A: %.1f   s: %s   B: %s """,
                   x,        A,        "str",  B )

If `x` and `A` are numbers, this is like `"format" % (x, A, "str", B)` in python.
If they're numpy arrays, each element is printed in its own format:
    `x`: e.g. [ 1.23 1.23e-6 ... ]  3 digits
    `A`: [ [ 1 digit after the decimal point ... ] ... ]
with the current `np.set_printoptions()`. For example, with
    np.set_printoptions( threshold=100, edgeitems=3, suppress=True )
only the edges of big `x` and `A` are printed.
`B` is printed as `str(B)`, for any `B` -- a number, a list, a numpy object ...

`printf()` tries to handle too few or too many arguments sensibly,
but this is iffy and subject to change.

How it works:
numpy has a function `np.array2string( A, "%.3g" )` (simplifying a bit).
`printf()` splits the format string, and for format / arg pairs
    format: % d e f g
    arg: try `np.asanyarray()`
-->  %s  np.array2string( arg, format )
Other formats and non-ndarray args are left alone, formatted as usual.

Notes:

`printf( ... end= file= )` are passed on to the python `print()` function.

Only formats `% [optional width . precision] d e f g` are implemented,
not `%(varname)format` .

%d truncates floats, e.g. 0.9 and -0.9 to 0; %.0f rounds, 0.9 to 1 .
%g is the same as %.6g, 6 digits.
%% is a single "%" character.

The function `sprintf()` returns a long string. For example,
    title = sprintf( "%s  m %g  n %g  X %.3g",
                    __file__, m, n, X )
    print( title )
    ...
    pl.title( title )

Module globals:
_fmt = "%.3g"  # default for extra args
_squeeze = np.squeeze  # (n,1) (1,n) -> (n,) print in 1 line not n

See also:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html
http://docs.python.org/2.7/library/stdtypes.html#string-formatting

'''
# http://stackoverflow.com/questions/2891790/pretty-printing-of-numpy-array


#...............................................................................
from __future__ import division, print_function
import re
import numpy as np

__version__ = "2014-02-03 feb denis"

_splitformat = re.compile( r'''(
    %
    (?<! %% )  # not %%
    -? [ \d . ]*  # optional width.precision
    \w
    )''', re.X )
    # ... %3.0f  ... %g  ... %-10s ...
    # -> ['...' '%3.0f' '...' '%g' '...' '%-10s' '...']
    # odd len, first or last may be ""

_fmt = "%.3g"  # default for extra args
_squeeze = np.squeeze  # (n,1) (1,n) -> (n,) print in 1 line not n

#...............................................................................
def printf( format, *args, **kwargs ):
    print( sprintf( format, *args ), **kwargs )  # end= file=

printf.__doc__ = __doc__


def sprintf( format, *args ):
    """ sprintf( "text %.3g text %4.1f ... %s ... ", numpy arrays or ... )
        %[defg] array -> np.array2string( formatter= )
    """
    args = list(args)
    if not isinstance( format, basestring ):
        args = [format] + args
        format = ""

    tf = _splitformat.split( format )  # [ text %e text %f ... ]
    nfmt = len(tf) // 2
    nargs = len(args)
    if nargs < nfmt:
        args += (nfmt - nargs) * ["?arg?"]
    elif nargs > nfmt:
        tf += (nargs - nfmt) * [_fmt, " "]  # default _fmt

    for j, arg in enumerate( args ):
        fmt = tf[ 2*j + 1 ]
        if arg is None \
        or isinstance( arg, basestring ) \
        or (hasattr( arg, "__iter__" ) and len(arg) == 0):
            tf[ 2*j + 1 ] = "%s"  # %f -> %s, not error
            continue
        args[j], isarray = _tonumpyarray(arg)
        if isarray  and fmt[-1] in "defgEFG":
            tf[ 2*j + 1 ] = "%s"
            fmtfunc = (lambda x: fmt % x)
            formatter = dict( float_kind=fmtfunc, int=fmtfunc )
            args[j] = np.array2string( args[j], formatter=formatter )
    try:
        return "".join(tf) % tuple(args)
    except TypeError:  # shouldn't happen
        print( "error: tf %s  types %s" % (tf, map( type, args )))
        raise


def _tonumpyarray( a ):
    """ a, isarray = _tonumpyarray( a )
        ->  scalar, False
            np.asanyarray(a), float or int
            a, False
    """
    a = getattr( a, "value", a )  # cvxpy
    if np.isscalar(a):
        return a, False
    if hasattr( a, "__iter__" )  and len(a) == 0:
        return a, False
    try:
        # map .value ?
        a = np.asanyarray( a )
    except ValueError:
        return a, False
    if hasattr( a, "dtype" )  and a.dtype.kind in "fi":  # complex ?
        if callable( _squeeze ):
            a = _squeeze( a )  # np.squeeze
        return a, True
    else:
        return a, False


#...............................................................................
if __name__ == "__main__":
    import sys

    n = 5
    seed = 0
        # run this.py n= ...  in sh or ipython
    for arg in sys.argv[1:]:
        exec( arg )
    np.set_printoptions( 1, threshold=4, edgeitems=2, linewidth=80, suppress=True )
    np.random.seed(seed)

    A = np.random.exponential( size=(n,n) ) ** 10
    x = A[0]

    printf( "x: %.3g  \nA: %.1f  \ns: %s  \nB: %s ",
                x,         A,         "str",   A )
    printf( "x %%d: %d", x )
    printf( "x %%.0f: %.0f", x )
    printf( "x %%.1e: %.1e", x )
    printf( "x %%g: %g", x )
    printf( "x %%s uses np printoptions: %s", x )

    printf( "x with default _fmt: ", x )
    printf( "no args" )
    printf( "too few args: %g %g", x )
    printf( x )
    printf( x, x )
    printf( None )
    printf( "[]:", [] )
    printf( "[3]:", [3] )
    printf( np.array( [] ))
    printf( [[]] )  # squeeze

How To Set Text In An EditText

If you want to set text at design time in xml file just simple android:text="username" add this property.

<EditText
    android:id="@+id/edtUsername"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="username"/>

If you want to set text programmatically in Java

EditText edtUsername = findViewById(R.id.edtUsername);
edtUsername.setText("username");

and in kotlin same like java using getter/setter

edtUsername.setText("username")

But if you want to use .text from principle then

edtUsername.text = Editable.Factory.getInstance().newEditable("username")

because of EditText.text requires an editable at firstplace not String

Run a php app using tomcat?

  1. Make sure you have php installed on your server
  2. Find the latest release of php-java-bridge off of sourceforge
  3. From the exploded directory on Sourceforge, download php-servlet.jar and JavaBridge.jar
  4. Place those jar files into webapp/WEB-INF/lib folder of your project
  5. Edit webapp/WEB-INF/web.xml to look like:

ok

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
   <filter>
      <filter-name>PhpCGIFilter</filter-name>
      <filter-class>php.java.servlet.PhpCGIFilter</filter-class>
   </filter>
   <filter-mapping>
      <filter-name>PhpCGIFilter</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
   <!-- the following adds the JSR223 listener. Remove it if you don't want to use the JSR223 API -->
   <listener>
      <listener-class>php.java.servlet.ContextLoaderListener</listener-class>
   </listener>
   <!-- the back end for external (console, Apache/IIS-) PHP scripts; remove it if you don't need this -->
   <servlet>
      <servlet-name>PhpJavaServlet</servlet-name>
      <servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
   </servlet>
   <!-- runs PHP scripts in this web app; remove it if you don't need this -->
   <servlet>
      <servlet-name>PhpCGIServlet</servlet-name>
      <servlet-class>php.java.servlet.fastcgi.FastCGIServlet</servlet-class>
      <load-on-startup>0</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>PhpJavaServlet</servlet-name>
      <url-pattern>*.phpjavabridge</url-pattern>
   </servlet-mapping>
   <servlet-mapping>
      <servlet-name>PhpCGIServlet</servlet-name>
      <url-pattern>*.php</url-pattern>
   </servlet-mapping>
</web-app>

You may have other content inside this file, just make sure you have added everything between the web-app tag.

  1. Add your php files to the webapp directory

You can do other special things with this as well. You cal learn more about it here: http://php-java-bridge.sourceforge.net/pjb/how_it_works.php

mysql extract year from date format

This should work:

SELECT YEAR(STR_TO_DATE(subdateshow, '%m/%d/%Y')) FROM table;

eg:

SELECT YEAR(STR_TO_DATE('01/17/2009', '%m/%d/%Y'));  /* shows "2009" */

Repeat String - Javascript

Concatenating strings based on an number.

function concatStr(str, num) {
   var arr = [];

   //Construct an array
   for (var i = 0; i < num; i++)
      arr[i] = str;

   //Join all elements
   str = arr.join('');

   return str;
}

console.log(concatStr("abc", 3));

Hope that helps!

Read remote file with node.js (http.get)

I'd use request for this:

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:

var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var csv = body;
        // Continue with your processing here.
    }
});

etc.

Specify multiple attribute selectors in CSS

[class*="test"],[class="second"] {
background: #ffff00;
}

Instantiating a generic class in Java

I could do this in a JUnit Test Setup.

I wanted to test a Hibernate facade so I was looking for a generic way to do it. Note that the facade also implements a generic interface. Here T is the database class and U the primary key. Ifacade<T,U> is a facade to access the database object T with the primary key U.

public abstract class GenericJPAController<T, U, C extends IFacade<T,U>>

{
    protected static EntityManagerFactory emf;

    /* The properties definition is straightforward*/
    protected T testObject;
    protected C facadeManager;

    @BeforeClass
    public static void setUpClass() {


        try {
            emf = Persistence.createEntityManagerFactory("my entity manager factory");

        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }

    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    /* Get the class name*/
        String className = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[2].getTypeName();

        /* Create the instance */
        try {
            facadeManager = (C) Class.forName(className).newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
            Logger.getLogger(GenericJPAController.class.getName()).log(Level.SEVERE, null, ex);
        }
        createTestObject();
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of testFindTEntities_0args method, of class
     * GenericJPAController<T, U, C extends IFacade<T,U>>.
     * @throws java.lang.ClassNotFoundException
     * @throws java.lang.NoSuchMethodException
     * @throws java.lang.InstantiationException
     * @throws java.lang.IllegalAccessException
     */
    @Test
    public void  testFindTEntities_0args() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException {

        /* Example of instance usage. Even intellisense (NetBeans) works here!*/
        try {
            List<T> lista = (List<T>) facadeManager.findAllEntities();
            lista.stream().forEach((ct) -> {
                System.out.println("Find all: " + stringReport());
            });
        } catch (Throwable ex) {
            System.err.println("Failed to access object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }


    /**
     *
     * @return
     */
    public abstract String stringReport();

    protected abstract T createTestObject();
    protected abstract T editTestObject();
    protected abstract U getTextObjectIndex();
}

Laravel migration default value

Might be a little too late to the party, but hope this helps someone with similar issue.

The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.

Let me illustrate with an example.

This line means Laravel is generating a new Book instance, as specified in your model. The new Book object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.

$book = new Book();

Now the following lines are setting up the values of each property of the Book object. Same still, nothing is written on the database yet.

$book->author = 'Test'
$book->title = 'Test'

This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).

$book->save();

And thus, the default value will not pop up before you save it to the database.

But, that is not enough. If you try to access $book->price, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.

So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the

Book::find($book->id);

Or, a more sophisticated way by refreshing the instance

$book->refresh();

And then, the next time you try to access the object, it will be filled with the default values.

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

mysql->SHOW PROCESSLIST;
kill xxxx; 

and then kill which one in sleep. In my case it is 2456.

enter image description here

curl -GET and -X GET

The use of -X [WHATEVER] merely changes the request's method string used in the HTTP request. This is easier to understand with two examples — one with -X [WHATEVER] and one without — and the associated HTTP request headers for each:

# curl -XPANTS -o nul -v http://neverssl.com/
* Connected to neverssl.com (13.224.86.126) port 80 (#0)
> PANTS / HTTP/1.1
> Host: neverssl.com
> User-Agent: curl/7.42.0
> Accept: */*

# curl -o nul -v http://neverssl.com/
* Connected to neverssl.com (13.33.50.167) port 80 (#0)
> GET / HTTP/1.1
> Host: neverssl.com
> User-Agent: curl/7.42.0
> Accept: */*

Show git diff on file in staging area

You can show changes that have been staged with the --cached flag:

$ git diff --cached

In more recent versions of git, you can also use the --staged flag (--staged is a synonym for --cached):

$ git diff --staged

Unknown column in 'field list' error on MySQL Update query

Just sharing my experience on this. I was having this same issue. My query was like:

select table1.column2 from table1

However, table1 did not have column2 column.

Change size of text in text input tag?

The Javascript to change font size for an input control is:

input.style.fontSize = "16px";

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

Not with pure HTML as far as I know.

But with JS or PHP or another scripting language such as JSP, you can do it very easily with a for loop.

Example in PHP:

<select>
<?php
    for ($i=1; $i<=100; $i++)
    {
        ?>
            <option value="<?php echo $i;?>"><?php echo $i;?></option>
        <?php
    }
?>
</select>

How can I open a URL in Android's web browser from my application?

If you want to do this with XML not programmatically you can use on your TextView:

android:autoLink="web"
android:linksClickable="true"

keytool error Keystore was tampered with, or password was incorrect

Check your home folder ~/.gradle/gradle.properties. Sometimes if you have gradle.properties in home directory it takes details from the there. Either you can change that or delete the files. Then it will take required details from your local folder.

How to convert dataframe into time series?

Input. We will start with the text of the input shown in the question since the question did not provide the csv input:

Lines <- "Dates   Bajaj_close Hero_close
3/14/2013   1854.8  1669.1
3/15/2013   1850.3  1684.45
3/18/2013   1812.1  1690.5
3/19/2013   1835.9  1645.6
3/20/2013   1840    1651.15
3/21/2013   1755.3  1623.3
3/22/2013   1820.65 1659.6
3/25/2013   1802.5  1617.7
3/26/2013   1801.25 1571.85
3/28/2013   1799.55 1542"

zoo. "ts" class series normally do not represent date indexes but we can create a zoo series that does (see zoo package):

library(zoo)
z <- read.zoo(text = Lines, header = TRUE, format = "%m/%d/%Y")

Alternately, if you have already read this into a data frame DF then it could be converted to zoo as shown on the second line below:

DF <- read.table(text = Lines, header = TRUE)
z <- read.zoo(DF, format = "%m/%d/%Y")

In either case above z ia a zoo series with a "Date" class time index. One could also create the zoo series, zz, which uses 1, 2, 3, ... as the time index:

zz <- z
time(zz) <- seq_along(time(zz))

ts. Either of these could be converted to a "ts" class series:

as.ts(z)
as.ts(zz)

The first has a time index which is the number of days since the Epoch (January 1, 1970) and will have NAs for missing days and the second will have 1, 2, 3, ... as the time index and no NAs.

Monthly series. Typically "ts" series are used for monthly, quarterly or yearly series. Thus if we were to aggregate the input into months we could reasonably represent it as a "ts" series:

z.m <- as.zooreg(aggregate(z, as.yearmon, mean), freq = 12)
as.ts(z.m)

How do I include a file over 2 directories back?

. = current directory
.. = parent directory

So ../ gets you one directory back not two.

Chain ../ as many times as necessary to go up 2 or more levels.

How to vertically align text in input type="text"?

I found this question while looking for a solution to my own problem. The previous answers rely on padding to make the text appear at the top or bottom of the input or use a combination of height and line-height to align the text to the vertical middle.

Here is an alternative solution to making the text appear in the middle using a div and positioning. Check out the jsfiddle.

<style type="text/css">
    div {
        display: inline-block;
        height: 300px;
        position: relative;
        width: 500px;
    }

    input {
        height: 100%;
        position: absolute;
        text-align: center; /* Optional */
        width: 100%;
    }
</style>

<div>
    <input type="text" value="Hello world!" />
</div>

Write HTML string in JSON

You can, once you escape the HTML correctly. This page shows what needs to be done.

If using PHP, you could use json_encode()

Hope this helps :)

How to open new browser window on button click event?

It can be done all on the client-side using the OnClientClick[MSDN] event handler and window.open[MDN]:

<asp:Button 
     runat="server" 
     OnClientClick="window.open('http://www.stackoverflow.com'); return false;">
     Open a new window!
</asp:Button>

Convert command line arguments into an array in Bash

Easier Yet, you can operate directly on $@ ;)

Here is how to do pass a a list of args directly from the prompt:

function echoarg { for stuff in "$@" ; do echo $stuff ; done ; } 
    echoarg Hey Ho Lets Go
    Hey
    Ho
    Lets
    Go

How to Decode Json object in laravel and apply foreach loop on that in laravel

your string is NOT a valid json to start with.

a valid json will be,

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

if you do a json_decode, it will yield,

stdClass Object
(
    [area] => Array
        (
            [0] => stdClass Object
                (
                    [area] => kothrud
                )

            [1] => stdClass Object
                (
                    [area] => katraj
                )

        )

)

Update: to use

$string = '

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

';
            $area = json_decode($string, true);

            foreach($area['area'] as $i => $v)
            {
                echo $v['area'].'<br/>';
            }

Output:

kothrud
katraj

Update #2:

for that true:

When TRUE, returned objects will be converted into associative arrays. for more information, click here

How to stop/terminate a python script from running?

To stop your program, just press Control + C.

What is the difference between a 'closure' and a 'lambda'?

A lambda is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.

A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list. Examples:

def func(): return h
def anotherfunc(h):
   return func()

This will cause an error, because func does not close over the environment in anotherfunc - h is undefined. func only closes over the global environment. This will work:

def anotherfunc(h):
    def func(): return h
    return func()

Because here, func is defined in anotherfunc, and in python 2.3 and greater (or some number like this) when they almost got closures correct (mutation still doesn't work), this means that it closes over anotherfunc's environment and can access variables inside of it. In Python 3.1+, mutation works too when using the nonlocal keyword.

Another important point - func will continue to close over anotherfunc's environment even when it's no longer being evaluated in anotherfunc. This code will also work:

def anotherfunc(h):
    def func(): return h
    return func

print anotherfunc(10)()

This will print 10.

This, as you notice, has nothing to do with lambdas - they are two different (although related) concepts.

How do I exclude Weekend days in a SQL Server query?

Try the DATENAME() function:

select [date_created]
from table
where DATENAME(WEEKDAY, [date_created]) <> 'Saturday'
  and DATENAME(WEEKDAY, [date_created]) <> 'Sunday'

JavaScript naming conventions

One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. eg:

define(['Lightbox'],function(Lightbox) {
  var myLightbox = new Lightbox() // not sure whether this is a constructor (non-static) or not
  myLightbox.show('hello')
})

I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? Would look like this:

define(['theLightbox'],function(theLightbox) {
  theLightbox.show('hello') // since I recognize the 'the' convention, I know it's static
})

Convert NSDate to NSString

It's swift format :

func dateFormatterWithCalendar(calndarIdentifier: Calendar.Identifier, dateFormat: String) -> DateFormatter {

    let formatter = DateFormatter()
    formatter.calendar = Calendar(identifier: calndarIdentifier)
    formatter.dateFormat = dateFormat

    return formatter
}


//Usage
let date = Date()
let fotmatter = dateFormatterWithCalendar(calndarIdentifier: .gregorian, dateFormat: "yyyy")
let dateString = fotmatter.string(from: date)
print(dateString) //2018

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

Typically you add a class selector to the :not() pseudo-class like so:

:not(.printable) {
    /* Styles */
}

:not([attribute]) {
    /* Styles */
}

But if you need better browser support (IE8 and older don't support :not()), you're probably better off creating style rules for elements that do have the "printable" class. If even that isn't feasible despite what you say about your actual markup, you may have to work your markup around that limitation.

Keep in mind that, depending on the properties you're setting in this rule, some of them may either be inherited by descendants that are .printable, or otherwise affect them one way or another. For example, although display is not inherited, setting display: none on a :not(.printable) will prevent it and all of its descendants from displaying, since it removes the element and its subtree from layout completely. You can often get around this by using visibility: hidden instead which will allow visible descendants to show, but the hidden elements will still affect layout as they originally did. In short, just be careful.

sed whole word search and replace

On Mac OS X, neither of these regex syntaxes work inside sed for matching whole words

  • \bmyWord\b
  • \<myWord\>

Hear me now and believe me later, this ugly syntax is what you need to use:

  • /[[:<:]]myWord[[:>:]]/

So, for example, to replace mint with minty for whole words only:

  • sed "s/[[:<:]]mint[[:>:]]/minty/g"

Source: re_format man page

How to open child forms positioned within MDI parent in VB.NET?

Try adding a button on mdi parent and add this code' to set your mdi child inside the mdi parent. change the yourchildformname to your MDI Child's form name and see if this works.

    Dim NewMDIChild As New yourchildformname()
    'Set the Parent Form of the Child window.
    NewMDIChild.MdiParent = Me
    'Display the new form.
    NewMDIChild.Show()

How to get the parent dir location

Use the following to jump to previous folder:

os.chdir(os.pardir)

If you need multiple jumps a good and easy solution will be to use a simple decorator in this case.

How to draw a standard normal distribution in R

By the way, instead of generating the x and y coordinates yourself, you can also use the curve() function, which is intended to draw curves corresponding to a function (such as the density of a standard normal function).

see

help(curve)

and its examples.

And if you want to add som text to properly label the mean and standard deviations, you can use the text() function (see also plotmath, for annotations with mathematical symbols) .

see

help(text)
help(plotmath)

Store multiple values in single key in json

{
  "number" : ["1","2","3"],
  "alphabet" : ["a", "b", "c"]
}

?: ?? Operators Instead Of IF|ELSE

Refering to ?: Operator (C# Reference)

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.

Refering to ?? Operator (C# Reference)

The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

That means:

[Part 1]

return source ?? String.Empty;

[Part 2] is not applicable ...

error C2039: 'string' : is not a member of 'std', header file problem

You need to have

#include <string>

in the header file too.The forward declaration on it's own doesn't do enough.

Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:

#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H

/* header goes in here */

#endif

This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.

How to filter files when using scp to copy dir recursively?

I'd probably recommend using something like rsync for this due to its include and exclude flags, e.g:-

rsync -rav -e ssh --include '*/' --include='*.class' --exclude='*' \
server:/usr/some/unknown/number/of/sub/folders/ \ 
/usr/project/backup/some/unknown/number/of/sub/folders/

Some other useful flags:

  • -r for recursive
  • -a for archive (mostly all files)
  • -v for verbose output
  • -e to specify ssh instead of the default (which should be ssh, actually)

Entity Framework rollback and remove bad migration

For EF 6 here's a one-liner if you're re-scaffolding a lot in development. Just update the vars and then keep using the up arrow in package manager console to rinse and repeat.

$lastGoodTarget = "OldTargetName"; $newTarget = "NewTargetName"; Update-Database -TargetMigration "$lastGoodTarget" -Verbose; Add-Migration "$newTarget" -Verbose -Force

Why is this necessary you ask? Not sure which versions of EF6 this applies but if your new migration target has already been applied then using '-Force' to re-scaffold in Add-Migration will not actually re-scaffold, but instead make a new file (this is a good thing though because you wouldn't want to lose your 'Down'). The above snippet does the 'Down' first if necessary then -Force works properly to re-scaffold.

How do I make a new line in swift

You can use the following code;

var example: String = "Hello World \r\n This is a new line"

Cannot bulk load. Operating system error code 5 (Access is denied.)

1) Open SQL 2) In Task Manager, you can check which account is running the SQL - it is probably not Michael-PC\Michael as Jan wrote.

The account that runs SQL need access to the shared folder.

Rolling back local and remote git repository by 1 commit

If you have direct access to the remote repo, you could always use:

git reset --soft HEAD^

This works since there is no attempt to modify the non-existent working directory. For more details please see the original answer:

How can I uncommit the last commit in a git bare repository?

converting CSV/XLS to JSON?

Since Powershell 3.0 (shipped with Windows 8, available for Windows 7 and windows Server 2008 but not Windows Vista ) you can use the built-in convertto-json commandlet:

PS E:> $topicsjson = import-csv .\itinerary-all.csv | ConvertTo-Json 

PS E:\> $topicsjson.Length
11909

PS E:\> $topicsjson.getType()

IsPublic IsSerial Name                                     BaseType                  
-------- -------- ----                                     --------                  
True     True     Object[]                                 System.Array              

Online Help Page on Technet

How do I disable Git Credential Manager for Windows?

OK, I discovered that you need to either avoid checking the "Git Credential Manager" checkbox during the Git for Windows installer, or (after installation) run the Bash shell as Administrator and use git config --edit --system to remove the helper = manager line so that it is no longer registered as a credential helper.

For bonus points, use git config --edit --global and insert:

[core]
    askpass =

To disable the OpenSSH credentials popup too.

ORA-28040: No matching authentication protocol exception

Except for adding the following to sqlnet.ora

SQLNET.ALLOWED_LOGON_VERSION_CLIENT = 8
SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8

I also added the following to both the Client and Server, which resolved my issue

SQLNET.AUTHENTICATION_SERVICES = (NONE)

Also see post ORA-28040: No matching authentication protocol

Angular 2 Cannot find control with unspecified name attribute on formArrays

For me, I was trying to add [formGroupName]="i" and/or formControlName and forgetting to specify the parent formArrayName. Pay attention to your form group tree.

How to start MySQL server on windows xp

Type

C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld" --console

to start the sql server and then test the client connection.

What is a good practice to check if an environmental variable exists or not?

My comment might not be relevant to the tags given. However, I was lead to this page from my search. I was looking for similar check in R and I came up the following with the help of @hugovdbeg post. I hope it would be helpful for someone who is looking for similar solution in R

'USERNAME' %in% names(Sys.getenv())

How to remove files from git staging area?

If unwanted files were added to the staging area but not yet committed, then a simple reset will do the job:

$ git reset HEAD file
# Or everything
$ git reset HEAD .

To only remove unstaged changes in the current working directory, use:

git checkout -- .

How to get a value from a cell of a dataframe?

Most answers are using iloc which is good for selection by position.

If you need selection-by-label loc would be more convenient.

For getting a value explicitly (equiv to deprecated df.get_value('a','A'))

# this is also equivalent to df1.at['a','A']
In [55]: df1.loc['a', 'A'] 
Out[55]: 0.13200317033032932

__init__() missing 1 required positional argument

The problem is with, you

def __init__(self, data):

when you create object from DHT class you should pass parameter the data should be dict type, like

data={'one':1,'two':2,'three':3}
dhtObj=DHT(data)

But in your code youshould to change is

data={'one':1,'two':2,'three':3}
if __name__ == '__main__': DHT(data).showData()

Or

if __name__ == '__main__': DHT({'one':1,'two':2,'three':3}).showData()

Using Java generics for JPA findAll() query with WHERE clause

you can also use a namedQuery named findAll for all your entities and call it in your generic FindAll with

entityManager.createNamedQuery(persistentClass.getSimpleName()+"findAll").getResultList();

Some projects cannot be imported because they already exist in the workspace error in Eclipse

I built the eclipse dependencies in the project terminal and then tried to import the project and it worked.

IntelliJ Organize Imports

Shortcut for the Mac: (ctrl + opt + o)

How to specify maven's distributionManagement organisation wide?

The best solution for this is to create a simple parent pom file project (with packaging 'pom') generically for all projects from your organization.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>your.company</groupId>
    <artifactId>company-parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <distributionManagement>
        <repository>
            <id>nexus-site</id>
            <url>http://central_nexus/server</url>
        </repository>
    </distributionManagement>

</project>

This can be built, released, and deployed to your local nexus so everyone has access to its artifact.

Now for all projects which you wish to use it, simply include this section:

<parent>
  <groupId>your.company</groupId>
  <artifactId>company-parent</artifactId>
  <version>1.0.0</version>
</parent>

This solution will allow you to easily add other common things to all your company's projects. For instance if you wanted to standardize your JUnit usage to a specific version, this would be the perfect place for that.

If you have projects that use multi-module structures that have their own parent, Maven also supports chaining inheritance so it is perfectly acceptable to make your project's parent pom file refer to your company's parent pom and have the project's child modules not even aware of your company's parent.

I see from your example project structure that you are attempting to put your parent project at the same level as your aggregator pom. If your project needs its own parent, the best approach I have found is to include the parent at the same level as the rest of the modules and have your aggregator pom.xml file at the root of where all your modules' directories exist.

- pom.xml (aggregator)
    - project-parent
    - project-module1
    - project-module2

What you do with this structure is include your parent module in the aggregator and build everything with a mvn install from the root directory.

We use this exact solution at my organization and it has stood the test of time and worked quite well for us.

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

Here is my one liner. Here 'c' is the name of the column

df.select('c').withColumn('isNull_c',F.col('c').isNull()).where('isNull_c = True').count()

Django ChoiceField

First I recommend you as @ChrisHuang-Leaver suggested to define a new file with all the choices you need it there, like choices.py:

STATUS_CHOICES = (
    (1, _("Not relevant")),
    (2, _("Review")),
    (3, _("Maybe relevant")),
    (4, _("Relevant")),
    (5, _("Leading candidate"))
)
RELEVANCE_CHOICES = (
    (1, _("Unread")),
    (2, _("Read"))
)

Now you need to import them on the models, so the code is easy to understand like this(models.py):

from myApp.choices import * 

class Profile(models.Model):
    user = models.OneToOneField(User)    
    status = models.IntegerField(choices=STATUS_CHOICES, default=1)   
    relevance = models.IntegerField(choices=RELEVANCE_CHOICES, default=1)

And you have to import the choices in the forms.py too:

forms.py:

from myApp.choices import * 

class CViewerForm(forms.Form):

    status = forms.ChoiceField(choices = STATUS_CHOICES, label="", initial='', widget=forms.Select(), required=True)
    relevance = forms.ChoiceField(choices = RELEVANCE_CHOICES, required=True)

Anyway you have an issue with your template, because you're not using any {{form.field}}, you generate a table but there is no inputs only hidden_fields.

When the user is staff you should generate as many input fields as users you can manage. I think django form is not the best solution for your situation.

I think it will be better for you to use html form, so you can generate as many inputs using the boucle: {% for user in users_list %} and you generate input with an ID related to the user, and you can manage all of them in the view.

Enable & Disable a Div and its elements in Javascript

The following selects all descendant elements and disables them:

$("#dcacl").find("*").prop("disabled", true);

But it only really makes sense to disable certain element types: inputs, buttons, etc., so you want a more specific selector:

$("#dcac1").find(":input").prop("disabled",true);
// noting that ":input" gives you the equivalent of
$("#dcac1").find("input,select,textarea,button").prop("disabled",true);

To re-enable you just set "disabled" to false.

I want to Disable them at loading the page and then by a click i can enable them

OK, so put the above code in a document ready handler, and setup an appropriate click handler:

$(document).ready(function() {
    var $dcac1kids = $("#dcac1").find(":input");
    $dcac1kids.prop("disabled",true);

    // not sure what you want to click on to re-enable
    $("selector for whatever you want to click").one("click",function() {
       $dcac1kids.prop("disabled",false);
    }
}

I've cached the results of the selector on the assumption that you're not adding more elements to the div between the page load and the click. And I've attached the click handler with .one() since you haven't specified a requirement to re-disable the elements so presumably the event only needs to be handled once. Of course you can change the .one() to .click() if appropriate.

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Here's how to fix this error when launching Eclipse:

Version 1.6.0_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.

  1. Go and install latest JDK

  2. Make sure you have installed 64 bit Eclipse

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

One difference is that:

  • :map does nvo == normal + (visual + select) + operator pending
  • :map! does ic == insert + command-line mode

as stated on help map-modes tables.

So: map does not map to all modes.

To map to all modes you need both :map and :map!.

Revert to Eclipse default settings

The settings of plugins, including the core ones, are saved in the [workspace_dir]/.metadata/.plugins directories ([workspace_dir] refers to the workspace directory you use).

So if you remove the [workspace_dir]/.metadata, you will reset all the properties defined (which will include all the properties, not only the font ones). Another idea is to create and use a new workspace. Be careful, as your code source may be located in your [workspace_dir]/ directory.

But why don't you just use Use System Font button in the Eclipse Properties dialog?

How to convert PDF files to images

Apache PDFBox also works great for me.

Usage with the command line tool:

javar -jar pdfbox-app-2.0.19.jar PDFToImage -quality 1.0  -dpi 150 -prefix out_dir/page -format png

How to make Sonar ignore some classes for codeCoverage metric?

I had to struggle for a little bit but I found a solution, I added

-Dsonar.coverage.exclusions=**/*.* 

and the coverage metric was cancelled from the dashboard at all, so I realized that the problem was the path I was passing, not the property. In my case the path to exclude was java/org/acme/exceptions, so I used :

`-Dsonar.coverage.exclusions=**/exceptions/**/*.*` 

and it worked, but since I don't have sub-folders it also works with

-Dsonar.coverage.exclusions=**/exceptions/*.*

How to insert date values into table

insert into run(id,name,dob)values(&id,'&name',[what should I write here?]);

insert into run(id,name,dob)values(&id,'&name',TO_DATE('&dob','YYYY-MM-DD'));

python selenium click on button

Remove space between classes in css selector:

driver.find_element_by_css_selector('.button .c_button .s_button').click()
#                                           ^         ^

=>

driver.find_element_by_css_selector('.button.c_button.s_button').click()

How do I check if PHP is connected to a database already?

before... (I mean somewhere in some other file you're not sure you've included)

$db = mysql_connect()

later...

if (is_resource($db)) {
// connected
} else {
$db = mysql_connect();
}

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

How to post data to specific URL using WebClient in C#

//Making a POST request using WebClient.
Function()
{    
  WebClient wc = new WebClient();

  var URI = new Uri("http://your_uri_goes_here");

  //If any encoding is needed.
  wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
  //Or any other encoding type.

  //If any key needed

  wc.Headers["KEY"] = "Your_Key_Goes_Here";

  wc.UploadStringCompleted += 
      new UploadStringCompletedEventHandler(wc_UploadStringCompleted);

  wc.UploadStringAsync(URI,"POST","Data_To_Be_sent");    
}

void wc__UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)    
{  
  try            
  {          
     MessageBox.Show(e.Result); 
     //e.result fetches you the response against your POST request.         
  }
  catch(Exception exc)         
  {             
     MessageBox.Show(exc.ToString());            
  }
}

How do I get an animated gif to work in WPF?

Thanks for your post Joel, it helped me solve WPF's absence of support for animated GIFs. Just adding a little code since I had a heck of a time with setting the pictureBoxLoading.Image property due to the Winforms api.

I had to set my animated gif image's Build Action as "Content" and the Copy to output directory to "Copy if newer" or "always". Then in the MainWindow() I called this method. Only issue is that when I tried to dispose of the stream, it gave me a red envelope graphic instead of my image. I'll have to solve that problem. This removed the pain of loading a BitmapImage and changing it into a Bitmap (which obviously killed my animation because it is no longer a gif).

private void SetupProgressIcon()
{
   Uri uri = new Uri("pack://application:,,,/WPFTest;component/Images/animated_progress_apple.gif");
   if (uri != null)
   {
      Stream stream = Application.GetContentStream(uri).Stream;   
      imgProgressBox.Image = new System.Drawing.Bitmap(stream);
   }
}

Kill some processes by .exe file name

Quick Answer:

foreach (var process in Process.GetProcessesByName("whatever"))
{
    process.Kill();
}

(leave off .exe from process name)

Merging dictionaries in C#

Merging using an EqualityComparer that maps items for comparison to a different value/type. Here we will map from KeyValuePair (item type when enumerating a dictionary) to Key.

public class MappedEqualityComparer<T,U> : EqualityComparer<T>
{
    Func<T,U> _map;

    public MappedEqualityComparer(Func<T,U> map)
    {
        _map = map;
    }

    public override bool Equals(T x, T y)
    {
        return EqualityComparer<U>.Default.Equals(_map(x), _map(y));
    }

    public override int GetHashCode(T obj)
    {
        return _map(obj).GetHashCode();
    }
}

Usage:

// if dictA and dictB are of type Dictionary<int,string>
var dict = dictA.Concat(dictB)
                .Distinct(new MappedEqualityComparer<KeyValuePair<int,string>,int>(item => item.Key))
                .ToDictionary(item => item.Key, item=> item.Value);

Change <select>'s option and trigger events with JavaScript

These questions may be relevant to what you're asking for:

Here are my thoughts: You can stack up more than one call in your onclick event like this:

<select id="sel" onchange='alert("changed")'>
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>
<input type="button" onclick='document.getElementById("sel").options[1].selected = true; alert("changed");' value="Change option to 2" />

You could also call a function to do this.

If you really want to call one function and have both behave the same way, I think something like this should work. It doesn't really follow the best practice of "Functions should do one thing and do it well", but it does allow you to call one function to handle both ways of changing the dropdown. Basically I pass (value) on the onchange event and (null, index of option) on the onclick event.

Here is the codepen: http://codepen.io/mmaynar1/pen/ZYJaaj

<select id="sel" onchange='doThisOnChange(this.value)'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" onclick='doThisOnChange(null,1);' value="Change option to 2"/>

<script>
doThisOnChange = function( value, optionIndex)
{
    if ( optionIndex != null )
    {
       var option = document.getElementById( "sel" ).options[optionIndex];
       option.selected = true;
       value = option.value;
    }
    alert( "Do something with the value: " + value );
}
</script>

How to add a form load event (currently not working)

Three ways you can do this - from the form designer, select the form, and where you normally see the list of properties, just above it there should be a little lightning symbol - this shows you all the events of the form. Find the form load event in the list, and you should be able to pick ProgramViwer_Load from the dropdown.

A second way to do it is programmatically - somewhere (constructor maybe) you'd need to add it, something like: ProgramViwer.Load += new EventHandler(ProgramViwer_Load);

A third way using the designer (probably the quickest) - when you create a new form, double click on the middle of it on it in design mode. It'll create a Form load event for you, hook it in, and take you to the event handler code. Then you can just add your two lines and you're good to go!

jQuery disable a link

Here is an alternate css/jQuery solution that I prefer for its terseness and minimized scripting:

css:

a.disabled {
  opacity: 0.5;
  pointer-events: none;
  cursor: default;
}

jQuery:

$('.disableAfterClick').click(function (e) {
   $(this).addClass('disabled');
});

Regarding C++ Include another class

The thing with compiling two .cpp files at the same time, it doesnt't mean they "know" about eachother. You will have to create a file, the "tells" your File1.cpp, there actually are functions and classes like ClassTwo. This file is called header-file and often doesn't include any executable code. (There are exception, e.g. for inline functions, but forget them at first) They serve a declarative need, just for telling, which functions are available.

When you have your File2.cpp and include it into your File1.cpp, you see a small problem: There is the same code twice: One in the File1.cpp and one in it's origin, File2.cpp.

Therefore you should create a header file, like File1.hpp or File1.h (other names are possible, but this is simply standard). It works like the following:

//File1.cpp

void SomeFunc(char c) //Definition aka Implementation
{
//do some stuff
}

//File1.hpp

void SomeFunc(char c); //Declaration aka Prototype

And for a matter of clean code you might add the following to the top of File1.cpp:

#include "File1.hpp"

And the following, surrounding File1.hpp's code:

#ifndef FILE1.HPP_INCLUDED
#define FILE1.HPP_INCLUDED
//
//All your declarative code
//
#endif

This makes your header-file cleaner, regarding to duplicate code.

What is a constant reference? (not a reference to a constant)

By "constant reference" I am guessing you really mean "reference to constant data". Pointers on the other hand, can be a constant pointer (the pointer itself is constant, not the data it points to), a pointer to constant data, or both.

Append value to empty vector in R?

> vec <- c(letters[1:3]) # vec <- c("a","b","c") ; or just empty vector: vec <- c()

> values<- c(1,2,3)

> for (i in 1:length(values)){
      print(paste("length of vec", length(vec))); 
      vec[length(vec)+1] <- values[i]  #Appends value at the end of vector
  }

[1] "length of vec 3"
[1] "length of vec 4"
[1] "length of vec 5"

> vec
[1] "a" "b" "c" "1" "2" "3"

Method to Add new or update existing item in Dictionary

Could there be any problem if i replace Method-1 by Method-2?

No, just use map[key] = value. The two options are equivalent.


Regarding Dictionary<> vs. Hashtable: When you start Reflector, you see that the indexer setters of both classes call this.Insert(key, value, add: false); and the add parameter is responsible for throwing an exception, when inserting a duplicate key. So the behavior is the same for both classes.

How to use GROUP BY to concatenate strings in SQL Server?

You can improve performance significant the following way if group by contains mostly one item:

SELECT 
  [ID],

CASE WHEN MAX( [Name]) = MIN( [Name]) THEN 
MAX( [Name]) NameValues
ELSE

  STUFF((
    SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) 
    FROM #YourTable 
    WHERE (ID = Results.ID) 
    FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
  ,1,2,'') AS NameValues

END

FROM #YourTable Results
GROUP BY ID

How to remove list elements in a for loop in Python?

Probably a bit late to answer this but I just found this thread and I had created my own code for it previously...

    list = [1,2,3,4,5]
    deleteList = []
    processNo = 0
    for item in list:
        if condition:
            print item
            deleteList.insert(0, processNo)
        processNo += 1

    if len(deleteList) > 0:
        for item in deleteList:
            del list[item]

It may be a long way of doing it but seems to work well. I create a second list that only holds numbers that relate to the list item to delete. Note the "insert" inserts the list item number at position 0 and pushes the remainder along so when deleting the items, the list is deleted from the highest number back to the lowest number so the list stays in sequence.

How to use new PasswordEncoder from Spring Security

Having just gone round the internet to read up on this and the options in Spring I'd second Luke's answer, use BCrypt (it's mentioned in the source code at Spring).

The best resource I found to explain why to hash/salt and why use BCrypt is a good choice is here: Salted Password Hashing - Doing it Right.

add to array if it isn't there already

if (!in_array(...))  
  array_push(..)

How do I execute a *.dll file

The following series of steps might be helpful:

  1. Open Windows Explorer
  2. In the top-left corner, click "Organize"
  3. select "Folder and Search Options"
  4. Switch to the "View" tab
  5. Scroll down and uncheck "Hide file extensions for known file types"
  6. Click OK
  7. Now find the dll file
  8. Right-click on it and select "Rename"
  9. Change the extension(what comes after the last .) and change it to .exe

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Ternary operator ?: vs if...else

It is not faster. There is one difference when you can initialize a constant variable depending on some expression:

const int x = (a<b) ? b : a;

You can't do the same with if-else.

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

I had the same issue. This Microsoft support article fixed it for me.
https://support.microsoft.com/en-us/help/2023146/mvc-2-and-asp.net-4-web-forms-applications-that-use-url-routing-might-return-http-404-errors-when-they-attempt-to-process-extensionless-urls-on-iis-7-and-iis-7.5

In the "Turn Windows Features On or Off" dialog box of the Windows Control Panel "Programs and Features" application, perform the following steps:

  1. Navigate to the following node: Internet Information Services --> World Wide Web Services --> Common HTTP Features
  2. Make sure that the "HTTP Error Redirection" option is selected.

-or-

  1. Navigate to the following node: Internet Information Services --> World Wide Web Services --> Performance Features
  2. Make sure that the "Static Content Compression" option is selected. After either option has been selected, click "OK" to save changes.

Re-enabling either the HTTP Error Redirection module or the Static Content Compression module ensures that ASP.NET and IIS correctly synchronize HTTP pipeline events. This enables the URL routing module to process extensionsless URLs.

'git status' shows changed files, but 'git diff' doesn't

There are a few reasons why git status might show a difference but git diff might not.

  • The mode (permission bits) of the file changed-- for example, from 777 to 700.

  • The line feed style changed from CRLF (DOS) to LF (UNIX)

The easiest way to find out what happened is to run git format-patch HEAD^ and see what the generated patch says.

How to change JDK version for an Eclipse project

Click on the Window tab in Eclipse, go to Preferences and when that window comes up, go to Java ? Installed JREs ? Execution Environment and choose JavaSE-1.5. You then have to go to Compiler and set the Compiler compliance level.

Changing JRE

Enter image description here

Input mask for numeric and decimal

Now that I understand better what you need, here's what I propose. Add a keyup handler for your textbox that checks the textbox contents with this regex ^[0-9]{1,14}\.[0-9]{2}$ and if it doesn't match, make the background red or show a text or whatever you like. Here's the code to put in document.ready

$(document).ready(function() {
    $('selectorForTextbox').bind('keyup', function(e) {
        if (e.srcElement.value.match(/^[0-9]{1,14}\.[0-9]{2}$/) === null) {
            $(this).addClass('invalid');
        } else {
            $(this).removeClass('invalid');
        }
    });
});

Here's a JSFiddle of this in action. Also, do the same regex server side and if it doesn't match, the requirements have not been met. You can also do this check the onsubmit event and not let the user submit the page if the regex didn't match.

The reason for not enforcing the mask upon text inserting is that it complicates things a lot, e.g. as I mentioned in the comment, the user cannot begin entering the valid input since the beggining of it is not valid. It is possible though, but I suggest this instead.

Determine path of the executing script

#!/usr/bin/env Rscript
print("Hello")

# sad workaround but works :(
programDir <- dirname(sys.frame(1)$ofile)
source(paste(programDir,"other.R",sep='/'))
source(paste(programDir,"other-than-other.R",sep='/'))

Android device does not show up in adb list

adb was not detecting connected nexus 5 device. Switched on the phone, enabled developer options, Enabled USB debugging mode, Now visible with adb. Also, USB configuration is still MTP. Hope this helps.

Add custom headers to WebView resource requests - android

You will need to intercept each request using WebViewClient.shouldInterceptRequest

With each interception, you will need to take the url, make this request yourself, and return the content stream:

WebViewClient wvc = new WebViewClient() {
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

        try {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("MY-CUSTOM-HEADER", "header value");
            httpGet.setHeader(HttpHeaders.USER_AGENT, "custom user-agent");
            HttpResponse httpReponse = client.execute(httpGet);

            Header contentType = httpReponse.getEntity().getContentType();
            Header encoding = httpReponse.getEntity().getContentEncoding();
            InputStream responseInputStream = httpReponse.getEntity().getContent();

            String contentTypeValue = null;
            String encodingValue = null;
            if (contentType != null) {
                contentTypeValue = contentType.getValue();
            }
            if (encoding != null) {
                encodingValue = encoding.getValue();
            }
            return new WebResourceResponse(contentTypeValue, encodingValue, responseInputStream);
        } catch (ClientProtocolException e) {
            //return null to tell WebView we failed to fetch it WebView should try again.
            return null;
        } catch (IOException e) {
             //return null to tell WebView we failed to fetch it WebView should try again.
            return null;
        }
    }
}

Webview wv = new WebView(this);
wv.setWebViewClient(wvc);

If your minimum API target is level 21, you can use the new shouldInterceptRequest which gives you additional request information (such as headers) instead of just the URL.

How to use the 'replace' feature for custom AngularJS directives?

When you have replace: true you get the following piece of DOM:

<div ng-controller="Ctrl" class="ng-scope">
    <div class="ng-binding">hello</div>
</div>

whereas, with replace: false you get this:

<div ng-controller="Ctrl" class="ng-scope">
    <my-dir>
        <div class="ng-binding">hello</div>
    </my-dir>
</div>

So the replace property in directives refer to whether the element to which the directive is being applied (<my-dir> in that case) should remain (replace: false) and the directive's template should be appended as its child,

OR

the element to which the directive is being applied should be replaced (replace: true) by the directive's template.

In both cases the element's (to which the directive is being applied) children will be lost. If you wanted to perserve the element's original content/children you would have to translude it. The following directive would do it:

.directive('myDir', function() {
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<div>{{title}}<div ng-transclude></div></div>'
    };
});

In that case if in the directive's template you have an element (or elements) with attribute ng-transclude, its content will be replaced by the element's (to which the directive is being applied) original content.

See example of translusion http://plnkr.co/edit/2DJQydBjgwj9vExLn3Ik?p=preview

See this to read more about translusion.

Filter values only if not null using lambda in Java8

You just need to filter the cars that have a null name:

requiredCars = cars.stream()
                   .filter(c -> c.getName() != null)
                   .filter(c -> c.getName().startsWith("M"));

Making Maven run all tests, even when some fail

A quick answer:

mvn -fn test

Works with nested project builds.

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

Mac SQLite editor

Try a versiontracker search instead. SqliteManager from SQLabs ($49, Mac & Windows) is the one I prefer, but I haven't really evaluated the other alternatives.

How do you parse and process HTML/XML in PHP?

With FluidXML you can query and iterate XML using XPath and CSS Selectors.

$doc = fluidxml('<html>...</html>');

$title = $doc->query('//head/title')[0]->nodeValue;

$doc->query('//body/p', 'div.active', '#bgId')
        ->each(function($i, $node) {
            // $node is a DOMNode.
            $tag   = $node->nodeName;
            $text  = $node->nodeValue;
            $class = $node->getAttribute('class');
        });

https://github.com/servo-php/fluidxml

Max length for client ip address

Take it from someone who has tried it all three ways... just use a varchar(39)

The slightly less efficient storage far outweighs any benefit of having to convert it on insert/update and format it when showing it anywhere.

Manually Set Value for FormBuilder Control

Aangular 2 final has updated APIs. They have added many methods for this.

To update the form control from controller do this:

this.form.controls['dept'].setValue(selected.id);

this.form.controls['dept'].patchValue(selected.id);

No need to reset the errors

References

https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

https://toddmotto.com/angular-2-form-controls-patch-value-set-value

How can I get the index from a JSON object with value?

Traverse through the array and find the index of the element which contains a key name and has the value as the passed param.

_x000D_
_x000D_
var data = [{_x000D_
  "name": "placeHolder",_x000D_
  "section": "right"_x000D_
}, {_x000D_
  "name": "Overview",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "ByFunction",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "Time",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "allFit",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "allbMatches",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "allOffers",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "allInterests",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "allResponses",_x000D_
  "section": "left"_x000D_
}, {_x000D_
  "name": "divChanged",_x000D_
  "section": "right"_x000D_
}];_x000D_
_x000D_
Array.prototype.getIndexOf = function(el) {_x000D_
_x000D_
  var arr = this;_x000D_
_x000D_
  for (var i=0; i<arr.length; i++){_x000D_
     console.log(arr[i].name);_x000D_
     if(arr[i].name==el){_x000D_
       return i;_x000D_
     }_x000D_
     _x000D_
  }_x000D_
  _x000D_
  return -1;_x000D_
_x000D_
}_x000D_
_x000D_
alert(data.getIndexOf("allResponses"));
_x000D_
_x000D_
_x000D_

JavaScript: How to find out if the user browser is Chrome?

If you want to detect Chrome's rendering engine (so not specific features in Google Chrome or Chromium), a simple option is:

var isChrome = !!window.chrome;

NOTE: this also returns true for many versions of Edge, Opera, etc that are based on Chrome (thanks @Carrm for pointing this out). Avoiding that is an ongoing battle (see window.opr below) so you should ask yourself if you're trying to detect the rendering engine (used by almost all major modern browsers in 2020) or some other Chrome (or Chromium?) -specific feature.

And you can probably skip !!

Is there an onSelect event or equivalent for HTML <select>?

I had faced a similar need and ended up writing a angularjs directive for the same -

guthub link - angular select

Used element[0].blur(); to remove the focus off the select tag. Logic is to trigger this blur on second click of the dropdown.

as-select gets triggered even when user selects the same value in the dropdown.

DEMO - link