Programs & Examples On #Edmx

An .edmx file is an XML file in the .Net Entity Framework that defines a conceptual model, a storage model, and the mapping between these models.

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:

  1. You should never send your model to the view => This is correct
  2. If you create a ViewModel, and include the Model as member in the ViewModel, then you effectively sent your model to the View => this is BAD
  3. Using dictionaries to send the options to the view => this not good style

So how can you create a better coupling?

I would use a tool like AutoMapper or ValueInjecter to map between ViewModel and Model. AutoMapper does seem to have the better syntax and feel to it, but the current version lacks a very severe topic: It is not able to perform the mapping from ViewModel to Model (under certain circumstances like flattening, etc., but this is off topic) So at present I prefer to use ValueInjecter.

So you create a ViewModel with the fields you need in the view. You add the SelectList items you need as lookups. And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist: You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList from the view to the controller.

  // StaffTypes is an IEnumerable<StaffType> from dbContext
  // viewModel is the viewModel initialized to copy content of Model Employee  
  // viewModel.StaffTypes is of type SelectList

  viewModel.StaffTypes =
    new SelectList(
        StaffTypes.OrderBy( item => item.Name )
        "StaffTypeID",
        "Type",
        viewModel.StaffTypeID
    );

In the view you just have to call

@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )

Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel. You then check for validation. If the validation fails, you have to remember to re-populate the viewModel.StaffTypes SelectList, because this item will be null on entering the post function. So I tend to have those population things separated into a function. You just call back return new View(viewModel) if anything is wrong. Validation errors found by MVC3 will automatically be shown in the view.

If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState to get info on that.

If the viewModel is valid you have to perform the next step:

If it is a create of a new item, you have to populate a model from the viewModel (best suited is ValueInjecter). Then you can add it to the EF collection of that type and commit changes.

If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel back to the model (again using ValueInjecter gets you do that very quick). After that you can SaveChanges and are done.

Feel free to ask if anything is unclear.

Circular dependency in Spring

Say A depends on B, then Spring will first instantiate A, then B, then set properties for B, then set B into A.

But what if B also depends on A?

My understanding is: Spring just found that A has been constructed (constructor executed), but not fully initialized (not all injections done), well, it thought, it's OK, it's tolerable that A is not fully initialized, just set this not-fully-initialized A instances into B for now. After B is fully initialized, it was set into A, and finally, A was fully initiated now.

In other words, it just expose A to B in advance.

For dependencies via constructor, Sprint just throw BeanCurrentlyInCreationException, to resolve this exception, set lazy-init to true for the bean which depends on others via constructor-arg way.

change Oracle user account status from EXPIRE(GRACE) to OPEN

Step-1 Need to find user details by using below query

SQL> select username, account_status from dba_users where username='BOB';

USERNAME                       ACCOUNT_STATUS
------------------------------ --------------------------------
BOB                            EXPIRED

Step-2 Get users password by using below query.

SQL>SELECT 'ALTER USER '|| name ||' IDENTIFIED BY VALUES '''|| spare4 ||';'|| password ||''';' FROM sys.user$ WHERE name='BOB';

ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';

Step -3 Run Above alter query

SQL> ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';
User altered.

Step-4 :Check users account status

SQL> select username, account_status from dba_users where username='BOB';
USERNAME                       ACCOUNT_STATUS
------------------------------ --------------------------------
BOB                            OPEN

The character encoding of the HTML document was not declared

You have to change the file from .html to .php.

and add this following line

header('Content-Type: text/html; charset=utf-8');

Custom checkbox image android

If you use androidx.appcompat:appcompat and want a custom drawable (of type selector with android:state_checked) to work on old platform versions in addition to new platform versions, you need to use

    <CheckBox
        app:buttonCompat="@drawable/..."

instead of

    <CheckBox
        android:button="@drawable/..."

How to erase the file contents of text file in Python?

You have to overwrite the file. In C++:

#include <fstream>

std::ofstream("test.txt", std::ios::out).close();

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

Sending JSON to PHP using ajax

That's because $_POST is pre-populated with form data.

To get JSON data (or any raw input), use php://input.

$json = json_decode(file_get_contents("php://input"));

Normalizing a list of numbers in Python

How long is the list you're going to normalize?

def psum(it):
    "This function makes explicit how many calls to sum() are done."
    print "Another call!"
    return sum(it)

raw = [0.07,0.14,0.07]
print "How many calls to sum()?"
print [ r/psum(raw) for r in raw]

print "\nAnd now?"
s = psum(raw)
print [ r/s for r in raw]

# if one doesn't want auxiliary variables, it can be done inside
# a list comprehension, but in my opinion it's quite Baroque    
print "\nAnd now?"
print [ r/s  for s in [psum(raw)] for r in raw]

Output

# How many calls to sum()?
# Another call!
# Another call!
# Another call!
# [0.25, 0.5, 0.25]
# 
# And now?
# Another call!
# [0.25, 0.5, 0.25]
# 
# And now?
# Another call!
# [0.25, 0.5, 0.25]

Reading in from System.in - Java

In Java, console input is accomplished by reading from System.in. To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object. BufferedReader supports a buffered input stream. Its most commonly used constructor is shown here:

BufferedReader(Reader inputReader)

Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters.

To obtain an InputStreamReader object that is linked to System.in, use the following constructor:

InputStreamReader(InputStream inputStream)

Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

After this statement executes, br is a character-based stream that is linked to the console through System.in.

This is taken from the book Java- The Complete Reference by Herbert Schildt

Android - java.lang.SecurityException: Permission Denial: starting Intent

You need to set android:exported="true" in your AndroidManifest.xml file where you declare this Activity:

<activity
    android:name="com.example.lib.MainActivity"
    android:label="LibMain" 
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" >
        </action>
    </intent-filter>
</activity>

How to read/write files in .Net Core?

For writing any Text to a file.

public static void WriteToFile(string DirectoryPath,string FileName,string Text)
    {
        //Check Whether directory exist or not if not then create it
        if(!Directory.Exists(DirectoryPath))
        {
            Directory.CreateDirectory(DirectoryPath);
        }

        string FilePath = DirectoryPath + "\\" + FileName;
        //Check Whether file exist or not if not then create it new else append on same file
        if (!File.Exists(FilePath))
        {
            File.WriteAllText(FilePath, Text);
        }
        else
        {
            Text = $"{Environment.NewLine}{Text}";
            File.AppendAllText(FilePath, Text);
        }
    }

For reading a Text from file

public static string ReadFromFile(string DirectoryPath,string FileName)
    {
        if (Directory.Exists(DirectoryPath))
        {
            string FilePath = DirectoryPath + "\\" + FileName;
            if (File.Exists(FilePath))
            {
                return File.ReadAllText(FilePath);
            }
        }
        return "";
    }

For Reference here this is the official microsoft document link.

how to configure hibernate config file for sql server

The connection URL should look like this for SQL Server:

jdbc:sqlserver://serverName[\instanceName][:port][;databaseName=your_db_name]

Examples:

jdbc:sqlserver://localhost
jdbc:sqlserver://127.0.0.1\INGESQL:1433;databaseName=datatest
...

MySQL, Check if a column exists in a table with SQL

I am using this simple script:

mysql_query("select $column from $table") or mysql_query("alter table $table add $column varchar (20)");

It works if you are already connected to the database.

Execute SQL script from command line

If you want to run the script file then use below in cmd

sqlcmd -U user -P pass  -S servername -d databasename -i "G:\Hiren\Lab_Prodution.sql"

How to Disable landscape mode in Android?

How to change orientation in some of the view

Instead of locking orientation of entire activity you can use this class to dynamically lock orientation from any of your view pragmatically:-

Make your view Landscape

OrientationUtils.lockOrientationLandscape(mActivity);

Make your view Portrait

OrientationUtils.lockOrientationPortrait(mActivity);

Unlock Orientation

OrientationUtils.unlockOrientation(mActivity);

Orientation Util Class

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.view.Surface;
import android.view.WindowManager;

/*  * This class is used to lock orientation of android app in nay android devices 
 */

public class OrientationUtils {
    private OrientationUtils() {
    }

    /** Locks the device window in landscape mode. */
    public static void lockOrientationLandscape(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
    }

    /** Locks the device window in portrait mode. */
    public static void lockOrientationPortrait(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /** Locks the device window in actual screen mode. */
    public static void lockOrientation(Activity activity) {
        final int orientation = activity.getResources().getConfiguration().orientation;
        final int rotation = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getRotation();

        // Copied from Android docs, since we don't have these values in Froyo
        // 2.2
        int SCREEN_ORIENTATION_REVERSE_LANDSCAPE = 8;
        int SCREEN_ORIENTATION_REVERSE_PORTRAIT = 9;

        // Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO
        if (!(Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO)) {
            SCREEN_ORIENTATION_REVERSE_LANDSCAPE = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            SCREEN_ORIENTATION_REVERSE_PORTRAIT = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        }

        if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) {
            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        } else if (rotation == Surface.ROTATION_180 || rotation == Surface.ROTATION_270) {
            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_PORTRAIT);
            } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                activity.setRequestedOrientation(SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
            }
        }
    }

    /** Unlocks the device window in user defined screen mode. */
    public static void unlockOrientation(Activity activity) {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
    }

}

Powershell script does not run via Scheduled Tasks

Change your Action to:

powershell -noprofile -executionpolicy bypass -file C:\path\event4740.ps1

On a Windows 2008 server R2: In Task Scheduler under the General Tab - Make sure the 'Run As' user is set to an account with the right permissions it takes to execute the script.

Also, I believe you have the "Run only when user is logged on" Option checked off. Change that to "Run whether user is logged on or not". Leave the Do Not Store password option unchecked, and you'll probably need the "Run with Highest Privileges" option marked.

PHP check if date between two dates

Edit: use <= or >= to count today's date.

This is the right answer for your code. Just use the strtotime() php function.

$paymentDate = date('Y-m-d');
$paymentDate=date('Y-m-d', strtotime($paymentDate));
//echo $paymentDate; // echos today! 
$contractDateBegin = date('Y-m-d', strtotime("01/01/2001"));
$contractDateEnd = date('Y-m-d', strtotime("01/01/2012"));
    
if (($paymentDate >= $contractDateBegin) && ($paymentDate <= $contractDateEnd)){
    echo "is between";
}else{
    echo "NO GO!";  
}

Center Oversized Image in Div

Try something like this. This should center any huge element in the middle vertically and horizontally with respect to its parent no matter both of their sizes.

.parent {
    position: relative;
    overflow: hidden;
    //optionally set height and width, it will depend on the rest of the styling used
}

.child {
    position: absolute;
    top: -9999px;
    bottom: -9999px;
    left: -9999px;
    right: -9999px;
    margin: auto;

}

How to Configure SSL for Amazon S3 bucket

Custom domain SSL certs were just added today for $600/cert/month. Sign up for your invite below: http://aws.amazon.com/cloudfront/custom-ssl-domains/

Update: SNI customer provided certs are now available for no additional charge. Much cheaper than $600/mo, and with XP nearly killed off, it should work well for most use cases.

@skalee AWS has a mechanism for achieving what the poster asks for, "implement SSL for an Amazon s3 bucket", it's called CloudFront. I'm reading "implement" as "use my SSL certs," not "just put an S on the HTTP URL which I'm sure the OP could have surmised.

Since CloudFront costs exactly the same as S3 ($0.12/GB), but has a ton of additional features around SSL AND allows you to add your own SNI cert at no additional cost, it's the obvious fix for "implementing SSL" on your domain.

How to access html form input from asp.net code behind

Edit: thought of something else.

You say you're creating a form dynamically - do you really mean a <form> and its contents 'cause asp.net takes issue with multiple forms on a page and it's already creating one uberform for you.

How to access cookies in AngularJS?

Angular deprecated $cookieStore in version 1.4.x, so use $cookies instead if you are using latest version of angular. Syntax remain same for $cookieStore & $cookies:

$cookies.put("key", "value"); 
var value = $cookies.get("key");

See the Docs for an API overview. Mind also that the cookie service has been enhanced with some new important features like setting expiration (see this answer) and domain (see CookiesProvider Docs).

Note that, in version 1.3.x or below, $cookies has a different syntax than above:

$cookies.key = "value";
var value = $cookies.value; 

Also if you are using bower, make sure to type your package name correctly:

bower install [email protected] 

where X.Y.Z is the AngularJS version you are running. There's another package in bower "angular-cookie"(without the 's') which is not the official angular package.

How to join two sets in one line without using "|"

You could use or_ alias:

>>> from operator import or_
>>> from functools import reduce # python3 required
>>> reduce(or_, [{1, 2, 3, 4}, {3, 4, 5, 6}])
set([1, 2, 3, 4, 5, 6])

Merge two json/javascript arrays in to one array

Since you are using jQuery. How about the jQuery.extend() method?

http://api.jquery.com/jQuery.extend/

Description: Merge the contents of two or more objects together into the first object.

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The min sdk version is the earliest release of the Android SDK that your application can run on. Usually this is because of a problem with the earlier APIs, lacking functionality, or some other behavioural issue.

The target sdk version is the version your application was targeted to run on. Ideally, this is because of some sort of optimal run conditions. If you were to "make your app for version 19", this is where that would be specified. It may run on earlier or later releases, but this is what you were aiming for. This is mostly to indicate how current your application is for use in the marketplace, etc.

The compile sdk version is the version of android your IDE (or other means of compiling I suppose) uses to make your app when you publish a .apk file. This is useful for testing your application as it is a common need to compile your app as you develop it. As this will be the version to compile to an APK, it will naturally be the version of your release. Likewise, it is advisable to have this match your target sdk version.

How can javascript upload a blob?

Try this

var fd = new FormData();
fd.append('fname', 'test.wav');
fd.append('data', soundBlob);
$.ajax({
    type: 'POST',
    url: '/upload.php',
    data: fd,
    processData: false,
    contentType: false
}).done(function(data) {
       console.log(data);
});

You need to use the FormData API and set the jQuery.ajax's processData and contentType to false.

What's wrong with overridable method calls in constructors?

In the specific case of Wicket: This is the very reason why I asked the Wicket devs to add support for an explicit two phase component initialization process in the framework's lifecycle of constructing a component i.e.

  1. Construction - via constructor
  2. Initialization - via onInitilize (after construction when virtual methods work!)

There was quite an active debate about whether it was necessary or not (it fully is necessary IMHO) as this link demonstrates http://apache-wicket.1842946.n4.nabble.com/VOTE-WICKET-3218-Component-onInitialize-is-broken-for-Pages-td3341090i20.html)

The good news is that the excellent devs at Wicket did end up introducing two phase initialization (to make the most aweseome Java UI framework even more awesome!) so with Wicket you can do all your post construction initialization in the onInitialize method that is called by the framework automatically if you override it - at this point in the lifecycle of your component its constructor has completed its work so virtual methods work as expected.

Implementing SearchView in action bar

It took a while to put together a solution for this, but have found this is the easiest way to get it to work in the way that you describe. There could be better ways to do this, but since you haven't posted your activity code I will have to improvise and assume you have a list like this at the start of your activity:

private List<String> items = db.getItems();

ExampleActivity.java

private List<String> items;

private Menu menu;

@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.example, menu);

    this.menu = menu;

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

        SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();

        search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));

        search.setOnQueryTextListener(new OnQueryTextListener() { 

            @Override 
            public boolean onQueryTextChange(String query) {

                loadHistory(query);

                return true; 

            } 

        });

    }

    return true;

}

// History
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void loadHistory(String query) {

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

        // Cursor
        String[] columns = new String[] { "_id", "text" };
        Object[] temp = new Object[] { 0, "default" };

        MatrixCursor cursor = new MatrixCursor(columns);

        for(int i = 0; i < items.size(); i++) {

            temp[0] = i;
            temp[1] = items.get(i);

            cursor.addRow(temp);

        }

        // SearchView
        SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        final SearchView search = (SearchView) menu.findItem(R.id.search).getActionView();

        search.setSuggestionsAdapter(new ExampleAdapter(this, cursor, items));

    }

}

Now you need to create an adapter extended from CursorAdapter:

ExampleAdapter.java

public class ExampleAdapter extends CursorAdapter {

    private List<String> items;

    private TextView text;

    public ExampleAdapter(Context context, Cursor cursor, List<String> items) {

        super(context, cursor, false);

        this.items = items;

    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

        text.setText(items.get(cursor.getPosition()));

    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = inflater.inflate(R.layout.item, parent, false);

        text = (TextView) view.findViewById(R.id.text);

        return view;

    }

}

A better way to do this is if your list data is from a database, you can pass the Cursor returned by database functions directly to ExampleAdapter and use the relevant column selector to display the column text in the TextView referenced in the adapter.

Please note: when you import CursorAdapter don't import the Android support version, import the standard android.widget.CursorAdapter instead.

The adapter will also require a custom layout:

res/layout/item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

You can now customize list items by adding additional text or image views to the layout and populating them with data in the adapter.

This should be all, but if you haven't done this already you need a SearchView menu item:

res/menu/example.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/search"
        android:title="@string/search"
        android:showAsAction="ifRoom"
        android:actionViewClass="android.widget.SearchView" />

</menu>

Then create a searchable configuration:

res/xml/searchable.xml

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/search"
    android:hint="@string/search" >
</searchable>

Finally add this inside the relevant activity tag in the manifest file:

AndroidManifest.xml

<intent-filter>
    <action android:name="android.intent.action.SEARCH" />
</intent-filter>

<meta-data
    android:name="android.app.default_searchable"
    android:value="com.example.ExampleActivity" />
<meta-data
    android:name="android.app.searchable"
    android:resource="@xml/searchable" />

Please note: The @string/search string used in the examples should be defined in values/strings.xml, also don't forget to update the reference to com.example for your project.

How to get evaluated attributes inside a custom directive

var myApp = angular.module('myApp',[]);

myApp .directive('myDirective', function ($timeout) {
    return function (scope, element, attr) {
        $timeout(function(){
            element.val("value = "+attr.value);
        });

    }
});

function MyCtrl($scope) {

}

Use $timeout because directive call after dom load so your changes doesn`'t apply

References with text in LaTeX

Using the hyperref package, you could also declare a new command by using \newcommand{\secref}[1]{\autoref{#1}. \nameref{#1}} in the pre-amble. Placing \secref{section:my} in the text generates: 1. My section.

PHP Sort a multidimensional array by element containing date

I came across to this post but I wanted to sort by time when returning the items inside my class and I got an error.

So I research the php.net website and end up doing this:

class MyClass {
   public function getItems(){
      usort( $this->items, array("MyClass", "sortByTime") );
      return $this->items;
   }
   public function sortByTime($a, $b){
      return $b["time"] - $a["time"];
   }
}

You can find very useful examples in the PHP.net website

My array looked like this:

  'recent' => 
    array
      92 => 
        array
          'id' => string '92' (length=2)
          'quantity' => string '1' (length=1)
          'time' => string '1396514041' (length=10)
      52 => 
        array
          'id' => string '52' (length=2)
          'quantity' => string '8' (length=1)
          'time' => string '1396514838' (length=10)
      22 => 
        array
          'id' => string '22' (length=2)
          'quantity' => string '1' (length=1)
          'time' => string '1396514871' (length=10)
      81 => 
        array
          'id' => string '81' (length=2)
          'quantity' => string '2' (length=1)
          'time' => string '1396514988' (length=10)

List all virtualenv

Run workon with no argument to list available environments.

How to convert a selection to lowercase or uppercase in Sublime Text

From the Sublime Text docs for Windows/Linux:

Keypress            Command
Ctrl + K, Ctrl + U  Transform to Uppercase
Ctrl + K, Ctrl + L  Transform to Lowercase

and for Mac:

Keypress    Command
cmd + KU    Transform to Uppercase
cmd + KL    Transform to Lowercase

Also note that Ctrl + Shift + p in Windows (? + Shift + p in a Mac) brings up the Command Palette where you can search for these and other commands. It looks like this:

enter image description here

AngularJS routing without the hash '#'

You could also use the below code to redirect to the main page (home):

{ path: '', redirectTo: 'home', pathMatch: 'full'}

After specifying your redirect as above, you can redirect the other pages, for example:

{ path: 'add-new-registration', component: AddNewRegistrationComponent},
{ path: 'view-registration', component: ViewRegistrationComponent},
{ path: 'home', component: HomeComponent}

How do I merge dictionaries together in Python?

Starting in Python 3.9, the operator | creates a new dictionary with the merged keys and values from two dictionaries:

# d1 = { 'a': 1, 'b': 2 }
# d2 = { 'b': 1, 'c': 3 }
d3 = d2 | d1
# d3: {'b': 2, 'c': 3, 'a': 1}

This:

Creates a new dictionary d3 with the merged keys and values of d2 and d1. The values of d1 take priority when d2 and d1 share keys.


Also note the |= operator which modifies d2 by merging d1 in, with priority on d1 values:

# d1 = { 'a': 1, 'b': 2 }
# d2 = { 'b': 1, 'c': 3 }
d2 |= d1
# d2: {'b': 2, 'c': 3, 'a': 1}

?

How do I work with dynamic multi-dimensional arrays in C?

Basics

Arrays in c are declared and accessed using the [] operator. So that

int ary1[5];

declares an array of 5 integers. Elements are numbered from zero so ary1[0] is the first element, and ary1[4] is the last element. Note1: There is no default initialization, so the memory occupied by the array may initially contain anything. Note2: ary1[5] accesses memory in an undefined state (which may not even be accessible to you), so don't do it!

Multi-dimensional arrays are implemented as an array of arrays (of arrays (of ... ) ). So

float ary2[3][5];

declares an array of 3 one-dimensional arrays of 5 floating point numbers each. Now ary2[0][0] is the first element of the first array, ary2[0][4] is the last element of the first array, and ary2[2][4] is the last element of the last array. The '89 standard requires this data to be contiguous (sec. A8.6.2 on page 216 of my K&R 2nd. ed.) but seems to be agnostic on padding.

Trying to go dynamic in more than one dimension

If you don't know the size of the array at compile time, you'll want to dynamically allocate the array. It is tempting to try

double *buf3;
buf3 = malloc(3*5*sizeof(double));
/* error checking goes here */

which should work if the compiler does not pad the allocation (stick extra space between the one-dimensional arrays). It might be safer to go with:

double *buf4;
buf4 = malloc(sizeof(double[3][5]));
/* error checking */

but either way the trick comes at dereferencing time. You can't write buf[i][j] because buf has the wrong type. Nor can you use

double **hdl4 = (double**)buf;
hdl4[2][3] = 0; /* Wrong! */

because the compiler expects hdl4 to be the address of an address of a double. Nor can you use double incomplete_ary4[][]; because this is an error;

So what can you do?

  • Do the row and column arithmetic yourself
  • Allocate and do the work in a function
  • Use an array of pointers (the mechanism qrdl is talking about)

Do the math yourself

Simply compute memory offset to each element like this:

  for (i=0; i<3; ++i){
     for(j=0; j<3; ++j){
        buf3[i * 5 + j] = someValue(i,j); /* Don't need to worry about 
                                             padding in this case */
     }
  }

Allocate and do the work in a function

Define a function that takes the needed size as an argument and proceed as normal

void dary(int x, int y){
  double ary4[x][y];
  ary4[2][3] = 5;
}

Of course, in this case ary4 is a local variable and you can not return it: all the work with the array must be done in the function you call of in functions that it calls.

An array of pointers

Consider this:

double **hdl5 = malloc(3*sizeof(double*));
/* Error checking */
for (i=0; i<3; ++i){
   hdl5[i] = malloc(5*sizeof(double))
   /* Error checking */
}

Now hdl5 points to an array of pointers each of which points to an array of doubles. The cool bit is that you can use the two-dimensional array notation to access this structure---hdl5[0][2] gets the middle element of the first row---but this is none-the-less a different kind of object than a two-dimensional array declared by double ary[3][5];.

This structure is more flexible then a two dimensional array (because the rows need not be the same length), but accessing it will generally be slower and it requires more memory (you need a place to hold the intermediate pointers).

Note that since I haven't setup any guards you'll have to keep track of the size of all the arrays yourself.

Arithmetic

c provides no support for vector, matrix or tensor math, you'll have to implement it yourself, or bring in a library.

Multiplication by a scaler and addition and subtraction of arrays of the same rank are easy: just loop over the elements and perform the operation as you go. Inner products are similarly straight forward.

Outer products mean more loops.

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.

So you have either closed the socket before calling write() or you have corrupted the value of 'sockfd' somewhere in your code.

It would be useful to trace all calls to close(), and the value of 'sockfd' prior to the write() calls.

Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror() is invalid, as it may disturb the value of errno. Indeed it may have done so in this case, and the real underlying error may be different.

Moment Js UTC to Local Time

I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!

Full Example on Codesandbox (DEMO):

https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js

Jenkins - how to build a specific branch

I don't think you can both within the same jenkins job, what you need to do is to configure a new jenkins job which will have access to your github to retrieve branches and then you can choose which one to manually build.

Just mark it as a parameterized build, specify a name, and a parameter configured as git parameter

enter image description here

and now you can configure git options:

enter image description here

Meaning of ${project.basedir} in pom.xml

${project.basedir} is the root directory of your project.

${project.build.directory} is equivalent to ${project.basedir}/target

as it is defined here: https://github.com/apache/maven/blob/trunk/maven-model-builder/src/main/resources/org/apache/maven/model/pom-4.0.0.xml#L53

Move SQL Server 2008 database files to a new folder location

To add the privileges needed to the files add and grant right to the following local user: SQLServerMSSQLUser$COMPUTERNAME$INSTANCENAME, where COMPUTERNAME and INSTANCENAME has to be replaced with name of computer and MSSQL instance respectively.

How to format a numeric column as phone number in SQL

You Can Use FORMAT if you column is a number Syntax like FORMAT ( value, format [, culture ] ) In use like FORMAT ( @d, 'D', 'en-US' ) or FORMAT(123456789,'###-##-####') (But This works for only SQL SERVER 2012 And After)

In Use Like UPDATE TABLE_NAME SET COLUMN_NAME = FORMAT(COLUMN_NAME ,'###-##-####')

And

if your column is Varchar Or Nvarchar use do like this CONCAT(SUBSTRING(CELLPHONE,0,4),' ',SUBSTRING(CELLPHONE,4,3),' ',SUBSTRING(CELLPHONE,7,2) ,' ',SUBSTRING(CELLPHONE,9,2) )

You can always get help from

https://msdn.microsoft.com/en-us/library/hh213505.aspx

How can I convert string date to NSDate?

import Foundation

let now : String = "2014-07-16 03:03:34 PDT"
var date : NSDate
var dateFormatter : NSDateFormatter

date = dateFormatter.dateFromString(now)

date // $R6: __NSDate = 2014-07-16 03:03:34 PDT

https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/index.html#//apple_ref/doc/uid/20000447-SW32

Need to remove href values when printing in Chrome

If you use the following CSS

<link href="~/Content/common/bootstrap.css" rel="stylesheet" type="text/css"    />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" type="text/css" />

just change it into the following style by adding media="screen"

<link href="~/Content/common/bootstrap.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/bootstrap.min.css" rel="stylesheet" **media="screen"** type="text/css" />
<link href="~/Content/common/site.css" rel="stylesheet" **media="screen"** type="text/css" />

I think it will work.

the former answers like

    @media print {
  a[href]:after {
    content: none !important;
  }
}

were not worked well in the chrome browse.

Netbeans 8.0.2 The module has not been deployed

In my case I had to run Netbeans as administrator, that solved the problem for me. I'm using Apache Netbeans IDE 11.0

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

in my case just

const myReducers = combineReducers({
  user: UserReducer
});

const store: any = createStore(
  myReducers,
  applyMiddleware(thunk)
);

shallow(<Login />, { context: { store } });

Correct way to push into state array

Never recommended to mutate the state directly.

The recommended approach in later React versions is to use an updater function when modifying states to prevent race conditions:

Push string to end of the array

this.setState(prevState => ({
  myArray: [...prevState.myArray, "new value"]
}))

Push string to beginning of the array

this.setState(prevState => ({
  myArray: ["new value", ...prevState.myArray]
}))

Push object to end of the array

this.setState(prevState => ({
  myArray: [...prevState.myArray, {"name": "object"}]
}))

Push object to beginning of the array

this.setState(prevState => ({
  myArray: [ {"name": "object"}, ...prevState.myArray]
}))

Entity Framework and Connection Pooling

Below code helped my object to be refreshed with fresh database values. The Entry(object).Reload() command forces the object to recall database values

GM_MEMBERS member = DatabaseObjectContext.GM_MEMBERS.FirstOrDefault(p => p.Username == username && p.ApplicationName == this.ApplicationName);
DatabaseObjectContext.Entry(member).Reload();

How to remove default mouse-over effect on WPF buttons?

An extension on dodgy_coder's answer which adds support for..

  • Maintaining WPF button style
  • Adds support for IsSelected and hover, i.e. a toggled button

        <Style x:Key="Button.Hoverless" TargetType="{x:Type ButtonBase}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ButtonBase}">
                        <Border Name="border"
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Padding="{TemplateBinding Padding}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                        </Border>
                        <ControlTemplate.Triggers>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsMouseOver" Value="True" />
                                    <Condition Property="Selector.IsSelected" Value="False" />
                                </MultiTrigger.Conditions>
                                <Setter Property="Background" Value="#FFBEE6FD" />
                            </MultiTrigger>
    
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsMouseOver" Value="True" />
                                    <Condition Property="Selector.IsSelected" Value="True" />
                                </MultiTrigger.Conditions>
                                <Setter Property="Background" Value="#BB90EE90" />
                            </MultiTrigger>
    
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsMouseOver" Value="False" />
                                    <Condition Property="Selector.IsSelected" Value="True" />
                                </MultiTrigger.Conditions>
                                <Setter Property="Background" Value="LightGreen" />
                            </MultiTrigger>
    
                            <Trigger Property="IsPressed" Value="True">
                                <Setter TargetName="border" Property="Opacity" Value="0.95" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    

examples..

<Button Content="Wipe On" Selector.IsSelected="True" /> <Button Content="Wipe Off" Selector.IsSelected="False" />

how to draw directed graphs using networkx in python?

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_node("D")
G.add_node("E")
G.add_node("F")
G.add_node("G")
G.add_edge("A","B")
G.add_edge("B","C")
G.add_edge("C","E")
G.add_edge("C","F")
G.add_edge("D","E")
G.add_edge("F","G")

print(G.nodes())
print(G.edges())

pos = nx.spring_layout(G)

nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edge_color='r', arrows = True)

plt.show()

How to get last inserted row ID from WordPress database?

just like this :

global $wpdb;
$table_name='lorem_ipsum';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY ID DESC LIMIT 1");
print_r($results[0]->id);

simply your selecting all the rows then order them DESC by id , and displaying only the first

Why is there no SortedList in Java?

Another point is the time complexity of insert operations. For a list insert, one expects a complexity of O(1). But this could not be guaranteed with a sorted list.

And the most important point is that lists assume nothing about their elements. For example, you can make lists of things that do not implement equals or compare.

What is Shelving in TFS?

@JaredPar: Yes you can use Shelvesets for reviews but keep in mind that shelvesets can be overwritten by yourself/others and therefore are not long term stable. Therefore for regulatory relevant reviews you should never use a Shelveset as base but rather a checkin (Changeset). For an informal review it is ok but not for a formal (E.g. FTA relevant) review!

Get Value From Select Option in Angular 4

This is very simple actually.

Please notice that I'm

I. adding name="selectedCorp" to your select opening tag, and

II. changing your [value]="corporationObj" to [value]="corporation", which is consistent with the corporation in your *ngFor="let corporation of corporations" statement:

 <form class="form-inline" (ngSubmit)="HelloCorp(f)" #f="ngForm">
   <div class="select">
     <select class="form-control col-lg-8" #corporation name="selectedCorp" required>
       <option *ngFor="let corporation of corporations" [value]="corporation">{{corporation.corp_name}}</option>
     </select>
     <button type="submit" class="btn btn-primary manage">Submit</button>
   </div>
 </form>

And then in your .ts file, you just do the following:

HelloCorp(form: NgForm) {
   const corporationObj = form.value.selectedCorp;
}

and the const corporationObj now is the selected corporation object, which will include all the properties of the corporation class you have defined.

NOTE:

In the html code, by the statement [value]="corporation", the corporation (from *ngFor="let corporation of corporations") is bound to [value], and the name property will get the value.

Since the name is "selectedCorp", you can get the actual value by getting "form.value.selectedCorp" in your .ts file.

By the way, actually you don't need the "#corporation" in your "select" opening tag.

Command line for looking at specific port

As noted elsewhere: use netstat, with appropriate switches, and then filter the results with find[str]

Most basic:

netstat -an | find ":N"

or

netstat -a -n | find ":N"

To find a foreign port you could use:

netstat -an | findstr ":N[^:]*$"

To find a local port you might use:

netstat -an | findstr ":N.*:[^:]*$"

Where N is the port number you are interested in.

-n ensures all ports will be numerical, i.e. not returned as translated to service names.

-a will ensure you search all connections (TCP, UDP, listening...)

In the find string you must include the colon, as the port qualifier, otherwise the number may match either local or foreign addresses.

You can further narrow narrow the search using other netstat switches as necessary...

Further reading (^0^)

netstat /?

find /?

findstr /?

Subset a dataframe by multiple factor levels

Try this:

> data[match(as.character(data$Code), selected, nomatch = FALSE), ]
    Code Value
1      A     1
2      B     2
1.1    A     1
1.2    A     1

How to convert Nvarchar column to INT

I know its Too late But I hope it will work new comers Try This Its Working ... :D

select 
  case 
      when isnumeric(my_NvarcharColumn) = 1 then 
              cast(my_NvarcharColumn AS int)
      else
              NULL
 end

AS 'my_NvarcharColumnmitter'
from A

iPad browser WIDTH & HEIGHT standard

You can try this:

    /*iPad landscape oriented styles */

    @media only screen and (device-width:768px)and (orientation:landscape){
        .yourstyle{

        }

    }

    /*iPad Portrait oriented styles */

    @media only screen and (device-width:768px)and (orientation:portrait){
        .yourstyle{

        }
    }

Converting string to Date and DateTime

You need to be careful with m/d/Y and m-d-Y formats. PHP considers / to mean m/d/Y and - to mean d-m-Y. I would explicitly describe the input format in this case:

$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');

That way you are not at the whims of a certain interpretation.

SQL Order By Count

Try using below Query:

SELECT
    GROUP,
    COUNT(*) AS Total_Count
FROM
    TABLE
GROUP BY
    GROUP
ORDER BY
    Total_Count DESC

How to display a PDF via Android web browser without "downloading" first

  Try this, worked for me.

    WebView view = (WebView) findViewById(R.id.yourWebView);

    view.getSettings().setJavaScriptEnabled(true);
    view.getSettings().setPluginState(WebSettings.PluginState.ON);
    view.loadUrl("http://docs.google.com/gview?embedded=true&url="
                  +"your document link(pdf,doc,docx...etc)");

How can I generate UUID in C#

I have a GitHub Gist with a Java like UUID implementation in C#: https://gist.github.com/rickbeerendonk/13655dd24ec574954366

The UUID can be created from the least and most significant bits, just like in Java. It also exposes them. The implementation has an explicit conversion to a GUID and an implicit conversion from a GUID.

SQL query to get most recent row for each instance of a given key

Nice elegant solution with ROW_NUMBER window function (supported by PostgreSQL - see in SQL Fiddle):

SELECT username, ip, time_stamp FROM (
 SELECT username, ip, time_stamp, 
  ROW_NUMBER() OVER (PARTITION BY username ORDER BY time_stamp DESC) rn
 FROM Users
) tmp WHERE rn = 1;

How to convert FileInputStream to InputStream?

You would typically first read from the input stream and then close it. You can wrap the FileInputStream in another InputStream (or Reader). It will be automatically closed when you close the wrapping stream/reader.

If this is a method returning an InputStream to the caller, then it is the caller's responsibility to close the stream when finished with it. If you close it in your method, the caller will not be able to use it.

To answer some of your comments...

To send the contents InputStream to a remote consumer, you would write the content of the InputStream to an OutputStream, and then close both streams.

The remote consumer does not know anything about the stream objects you have created. He just receives the content, in an InputStream which he will create, read from and close.

Create a sample login page using servlet and JSP?

As I can see, you are comparing the message with the empty string using ==.

Its very hard to write the full code, but I can tell the flow of code - first, create db class & method inide that which will return the connection. second, create a servelet(ex-login.java) & import that db class onto that servlet. third, create instance of imported db class with the help of new operator & call the connection method of that db class. fourth, creaet prepared statement & execute statement & put this code in try catch block for exception handling.Use if-else condition in the try block to navigate your login page based on success or failure.

I hope, it will help you. If any problem, then please revert.

Nikhil Pahariya

Laravel redirect back to original destination after login

I have been using this for a while on my language selector code. As long as you only need to go back by just 1 page it works fine:

return Redirect::to(URL::previous());

It ain't the most powerful solution out there but it is super-easy and can help solve a few puzzles. :)

How to declare a global variable in C++

In addition to other answers here, if the value is an integral constant, a public enum in a class or struct will work. A variable - constant or otherwise - at the root of a namespace is another option, or a static public member of a class or struct is a third option.

MyClass::eSomeConst (enum)
MyNamespace::nSomeValue 
MyStruct::nSomeValue (static) 

Python: How to get stdout after running os.system?

import subprocess
string="echo Hello world"
result=subprocess.getoutput(string)
print("result::: ",result)

How to add onload event to a div element

You cannot add event onload on div, but you can add onkeydown and trigger onkeydown event on document load

_x000D_
_x000D_
$(function ()_x000D_
{_x000D_
  $(".ccsdvCotentPS").trigger("onkeydown");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
_x000D_
<div  onkeydown="setCss( );"> </div>`
_x000D_
_x000D_
_x000D_

Looping through JSON with node.js

My most preferred way is,

var objectKeysArray = Object.keys(yourJsonObj)
objectKeysArray.forEach(function(objKey) {
    var objValue = yourJsonObj[objKey]
})

Find the least number of coins required that can make any change from 1 to 99 cents

You can very quickly find an upper bound.

Say, you take three quarters. Then you would only have to fill in the 'gaps' 1-24, 26-49, 51-74, 76-99 with other coins.

Trivially, that would work with 2 dimes, 1 nickel, and 4 pennies.

So, 3 + 4 + 2 + 1 should be an upper bound for your number of coins, Whenever your brute-force algorithm goes above thta, you can instantly stop searching any deeper.

The rest of the search should perform fast enough for any purpose with dynamic programming.

(edit: fixed answer as per Gabe's observation)

"google is not defined" when using Google Maps V3 in Firefox remotely

instead of this

var defaultLocation = new google.maps.LatLng(lat, lng);

use this

var defaultLocation = new window.google.maps.LatLng(lat, lng);

and this worked for me.

Stylesheet not updating

First, try to Force reload or Clear cache and Empty chase and hard reload. You can do it by pressing F12 and then by right-clicking on it.

2nd Solution: Check your HTML base tag. You can learn more about it from here.

joining two select statements

This will do what you want:

select * 
  from orders_products 
       INNER JOIN orders 
          ON orders_products.orders_id = orders.orders_id
 where products_id in (180, 181);

Concatenating variables and strings in React

you can simply do this..

 <img src={"http://img.example.com/test/" + this.props.url +"/1.jpg"}/>

Convert array values from string to int?

If you have a multi-dimensional array, none of the previously mentioned solutions will work. Here is my solution:

public function arrayValuesToInt(&$array){
  if(is_array($array)){
    foreach($array as &$arrayPiece){
      arrayValuesToInt($arrayPiece);
    }
  }else{
    $array = intval($array);
  }
}

Then, just do this:

arrayValuesToInt($multiDimentionalArray);

This will make an array like this:

[["1","2"]["3","4"]]

look like this:

[[1,2][3,4]]

This will work with any level of depth.

Alternatively, you can use array_walk_recursive() for a shorter answer:

array_walk_recursive($array, function(&$value){
    $value = intval($value);
});

How to merge remote master to local branch

Switch to your local branch

> git checkout configUpdate

Merge remote master to your branch

> git rebase master configUpdate

In case you have any conflicts, correct them and for each conflicted file do the command

> git add [path_to_file/conflicted_file] (e.g. git add app/assets/javascripts/test.js)

Continue rebase

> git rebase --continue

android TextView: setting the background color dynamically doesn't work

Well I had situation when web service returned a color in hex format like "#CC2233" and I wanted to put this color on textView by using setBackGroundColor(), so I used android Color class to get int value of hex string and passed it to mentioned function. Everything worked. This is example:

String myHexColor = "#CC2233";
TextView myView = (TextView) findViewById(R.id.myTextView);
myView.setBackGroundColor(Color.pasrsehexString(myHexColor));

P.S. posted this answer because other solutions didn't work for me. I hope this will help someone:)

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

Invalid JSON from the server should always be an expected use case. A million things can go wrong during transmission. Gson is a bit tricky, because its error output will give you one problem, and the actual exception you catch will be of a different type.

With all that in mind, the proper fix on the client side is

try
{
  gson.fromJSON(ad, Ad.class);
  //...
}
catch (IllegalStateException | JsonSyntaxException exception)
{
  //...

If you want to know why the JSON you received from the server is wrong, you can look inside your catch block at the exception. But even if it is your problem, it's not the client's responsibility to fix JSON it is receiving from the internet.

Either way, it is the client's responsibility to decide what to do when it gets bad JSON. Two possibilities are rejecting the JSON and doing nothing, and trying again.

If you are going to try again, I highly recommend setting a flag inside the try / catch block and then responding to that flag outside the try / catch block. Nested try / catch is likely how Gson got us into this mess with our stack trace and exceptions not matching up.

In other words, even though I'll admit it doesn't look very elegant, I would recommend

boolean failed = false;

try
{
  gson.fromJSON(ad, Ad.class);
  //...
}
catch (IllegalStateException | JsonSyntaxException exception)
{
  failed = true;
  //...
}

if (failed)
{
  //...

Set Culture in an ASP.Net MVC app

protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            if(Context.Session!= null)
            Thread.CurrentThread.CurrentCulture =
                    Thread.CurrentThread.CurrentUICulture = (Context.Session["culture"] ?? (Context.Session["culture"] = new CultureInfo("pt-BR"))) as CultureInfo;
        }

Blur effect on a div element

I think this is what you are looking for? If you are looking to add a blur effect to a div element, you can do this directly through CSS Filters-- See fiddle: http://jsfiddle.net/ayhj9vb0/

 div {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
  width: 100px;
  height: 100px;
  background-color: #ccc;

}

How to use 'hover' in CSS

a.hover:hover {
    text-decoration:underline;
}

How can I declare and use Boolean variables in a shell script?

POSIX (Portable Operating System Interface)

I miss here the key point, which is portability. That's why my header has POSIX in itself.

Essentially, all of the voted answers are correct, with the exception they are Bash-specific too much.

Basically, I only wish to add more information about portability.


  1. [ and ] brackets like in [ "$var" = true ] are not necessary, and you can omit them and use the test command directly:

    test "$var" = true && yourCodeIfTrue || yourCodeIfFalse
    

    Important note: I no longer recommend this as it's being slowly deprecated and more difficult to combine multiple statements.

  2. Imagine what those words true and false mean to the shell, test it yourself:

    echo $(( true ))
    
    0
    
    echo $(( false ))
    
    1
    

    But using quotes:

    echo $(( "true" ))
    
    bash: "true": syntax error: operand expected (error token is ""true"")
    sh (dash): sh: 1: arithmetic expression: expecting primary: ""true""
    

    The same goes for:

    echo $(( "false" ))
    

    The shell can't interpret it other than a string. I hope you are getting the idea of how good it is using proper keyword without quotes.

    But no one said it in previous answers.

  3. What does this mean? Well, several things.

    • You should get used to the Boolean keywords are actually treated like numbers, that is true = 0 and false = 1, remember all non-zero values are treated like false.

    • Since they are treated as numbers, you should treat them like that too, i.e. if you define variable say:

      var_bool=true
      echo "$var_bool"
      
       true
      

      you can create an opposite value of it with:

      var_bool=$(( 1 - $var_bool ))  # same as $(( ! $var_bool ))
      echo "$var_bool"
      
      1
      

    As you can see for yourself, the shell does print true string for the first time you use it, but since then, it all works via number 0 representing trueor 1 representing false, respectively.


Finally, what you should do with all that information

  • First, one good habit would be assigning 0 instead of true; 1 instead of false.

  • Second good habit would be to test if the variable is / isn't equal to zero:

    if [ "$var_bool" -eq 0 ]; then
         yourCodeIfTrue
    else
         yourCodeIfFalse
    fi
    

Where is Developer Command Prompt for VS2013?

From VS2013 Menu Select "Tools", then Select "External Tools". Enter as below:

  • Title: "VS2013 Native Tools-Command Prompt" would be good
  • Command: C:\Windows\System32\cmd.exe
  • Arguments: /k "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat"
  • Initial Directory: Select as suits your needs.

Click OK. Now you have command prompt access under the Tools Menu.

What is a StackOverflowError?

The most common cause of stack overflows is excessively deep or infinite recursion. If this is your problem, this tutorial about Java Recursion could help understand the problem.

Address already in use: JVM_Bind

My answer does 100% fit to this problem, but I want to document my solution and the trap behind it, since the Exception is the same.

My port was always in use testing a Jetty in a Junit testcase. Problem was Google's code pro on Eclipse, which, I guess, was testing in the background and thus starting jetty before me all the time. Workaround: let Eclipse open *.java files always w/ the Java editor instead of Google's Junit editor. That seems to help.

How can I add an item to a IEnumerable<T> collection?

Easyest way to do that is simply

IEnumerable<T> items = new T[]{new T("msg")};
List<string> itemsList = new List<string>();
itemsList.AddRange(items.Select(y => y.ToString()));
itemsList.Add("msg2");

Then you can return list as IEnumerable also because it implements IEnumerable interface

Does PHP have threading?

Ever heard about appserver from techdivision?

It is written in php and works as a appserver managing multithreads for high traffic php applications. Is still in beta but very promesing.

Bash scripting missing ']'

If you created your script on windows and want to run it on linux machine, and you're sure there is no mistake in your code, install dos2unix on linux machine and run dos2unix yourscript.sh. Then, run the script.

How to remove class from all elements jquery

The best to remove a class in jquery from all the elements is to target via element tag. e.g.,

$("div").removeClass("highlight");

password-check directive in angularjs

As of angular 1.3.0-beta12, invalid inputs don't write to ngModel, so you can't watch AND THEN validate as you can see here: http://plnkr.co/edit/W6AFHF308nyKVMQ9vomw?p=preview. A new validators pipeline was introduced and you can attach to this to achieve the same thing.

Actually, on that note I've created a bower component for common extra validators: https://github.com/intellix/angular-validators which includes this.

angular.module('validators').directive('equals', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attrs, ngModel)
        {
            if (!ngModel) return;

            attrs.$observe('equals', function() {
                ngModel.$validate();
            });

            ngModel.$validators.equals = function(value) {
                return value === attrs.equals;
            };
        }
    };
});

angular.module('validators').directive('notEquals', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attrs, ngModel)
        {
            if (!ngModel) return;

            attrs.$observe('notEquals', function() {
                ngModel.$validate();
            });

            ngModel.$validators.notEquals = function(value) {
                return value === attrs.notEquals;
            };
        }
    };
});

SQL search multiple values in same field

This will works perfectly in both cases, one or multiple fields searching multiple words.

Hope this will help someone. Thanks

declare @searchTrm varchar(MAX)='one two three four'; 
--select value from STRING_SPLIT(@searchTrm, ' ') where trim(value)<>''
select * from Bols 
WHERE EXISTS (SELECT value  
    FROM STRING_SPLIT(@searchTrm, ' ')  
    WHERE 
        trim(value)<>''
        and(    
        BolNumber like '%'+ value+'%'
        or UserComment like '%'+ value+'%'
        or RequesterId like '%'+ value+'%' )
        )

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123

Python 3 Building an array of bytes

what about simply constructing your frame from a standard list ?

frame = bytes([0xA2,0x01,0x02,0x03,0x04])

the bytes() constructor can build a byte frame from an iterable containing int values. an iterable is anything which implements the iterator protocol: an list, an iterator, an iterable object like what is returned by range()...

Read file content from S3 bucket with boto3

Using the client instead of resource:

s3 = boto3.client('s3')
bucket='bucket_name'
result = s3.list_objects(Bucket = bucket, Prefix='/something/')
for o in result.get('Contents'):
    data = s3.get_object(Bucket=bucket, Key=o.get('Key'))
    contents = data['Body'].read()
    print(contents)

Encapsulation vs Abstraction?

Answering my own question after 5 years as i feel it still need more details

Abstraction:

Technical Definition :- Abstraction is a concept to hide unnecessary details(complex or simple) and only show the essential features of the object. There is no implementaion here its just an concept

What it means practically:- When i say my company needs some medium/device so that employees can connect to customer . This is the purest form of abstaction(like interface in java) as that device/medium can be phone or internet or skype or in person or email etc. I am not going into nitty gritty of device/medium

Even when i say my company needs some medium/device so that employees can connect to customer through voice call. Then also i am talking abstract but at bit lower level as device/medium can be phone or skype or something else etc

Now when i say my company needs some phone so that employees can connect to customer through voice call. Then also i am talking abstract but at bit lower level as phone can be of any company like iphone or samsung or nokia etc

Encapsulation:- Its basically about hiding the state(information) of object with the help of modifiers like private,public,protected etc. we expose the state thru public methods only if require.

What it means practically:- Now when i say my company needs some iphone so that employees can connect to customer through voice call.Now i am talking about some concrete object(like iphone). Even though i am not going into nitty gritty of iphone here too but iphone has some state/concrecrete info/implementation associated with it where device/medium does not have. When i say concrete object, actually it means any object which has some(not complete like java abstract class) implementation/info associated with it.

So iphone actually used here encapsulation as strategy to hide its state/information and expose only the ones which it think should be exposed. So both abstraction and encapsulation hides some unnecessary details but abstraction at the concept level and encapsulation actually at implementation level

This is the gist based on answers in this post and below ones

  1. difference between abstraction and encapsulation?
  2. encapsulation vs abstraction real world example

Using logging in multiple modules

You could also come up with something like this!

def get_logger(name=None):
    default = "__app__"
    formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s',
                              datefmt='%Y-%m-%d %H:%M:%S')
    log_map = {"__app__": "app.log", "__basic_log__": "file1.log", "__advance_log__": "file2.log"}
    if name:
        logger = logging.getLogger(name)
    else:
        logger = logging.getLogger(default)
    fh = logging.FileHandler(log_map[name])
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    logger.setLevel(logging.DEBUG)
    return logger

Now you could use multiple loggers in same module and across whole project if the above is defined in a separate module and imported in other modules were logging is required.

a=get_logger("__app___")
b=get_logger("__basic_log__")
a.info("Starting logging!")
b.debug("Debug Mode")

How to delete a cookie?

Try this:

function delete_cookie( name, path, domain ) {
  if( get_cookie( name ) ) {
    document.cookie = name + "=" +
      ((path) ? ";path="+path:"")+
      ((domain)?";domain="+domain:"") +
      ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
  }
}

You can define get_cookie() like this:

function get_cookie(name){
    return document.cookie.split(';').some(c => {
        return c.trim().startsWith(name + '=');
    });
}

Automatically deleting related rows in Laravel (Eloquent ORM)

Relation in User model:

public function photos()
{
    return $this->hasMany('Photo');
}

Delete record and related:

$user = User::find($id);

// delete related   
$user->photos()->delete();

$user->delete();

Representing null in JSON

I would use null to show that there is no value for that particular key. For example, use null to represent that "number of devices in your household connects to internet" is unknown.

On the other hand, use {} if that particular key is not applicable. For example, you should not show a count, even if null, to the question "number of cars that has active internet connection" is asked to someone who does not own any cars.

I would avoid defaulting any value unless that default makes sense. While you may decide to use null to represent no value, certainly never use "null" to do so.

CRON command to run URL address every 5 minutes

The other advantage of using curl is that you also can keep the HTTP way of sending parameters to your script if you need to, by using $_GET, $_POST etc like this:

*/5 * * * * curl --request GET 'http://exemple.com/path/check.php?param1=1&param2=2'

Status bar and navigation bar appear over my view's bounds in iOS 7

If you want the view to have the translucent nav bar (which is kind of nice) you have to setup a contentInset or similar.

Here is how I do it:

// Check if we are running on ios7
if([[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."][0] intValue] >= 7) {
      CGRect statusBarViewRect = [[UIApplication sharedApplication] statusBarFrame];
      float heightPadding = statusBarViewRect.size.height+self.navigationController.navigationBar.frame.size.height;

      myContentView.contentInset = UIEdgeInsetsMake(heightPadding, 0.0, 0.0, 0.0);
}

Java HTTP Client Request with defined timeout

If you are using Http Client version 4.3 and above you should be using this:

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30 * 1000).build();
HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();

Xampp localhost/dashboard

Here's what's actually happening localhost means that you want to open htdocs. First it will search for any file named index.php or index.html. If one of those exist it will open the file. If neither of those exist then it will open all folder/file inside htdocs directory which is what you want.

So, the simplest solution is to rename index.php or index.html to index2.php etc.

"java.lang.OutOfMemoryError : unable to create new native Thread"

I would recommend to also look at the Thread Stack Size and see if you get more threads created. The default Thread Stack Size for JRockit 1.5/1.6 is 1 MB for 64-bit VM on Linux OS. 32K threads will require a significant amount of physical and virtual memory to honor this requirement.

Try to reduce the Stack Size to 512 KB as a starting point and see if it helps creating more threads for your application. I also recommend to explore horizontal scaling e.g. splitting your application processing across more physical or virtual machines.

When using a 64-bit VM, the true limit will depend on the OS physical and virtual memory availability and OS tuning parameters such as ulimitc. I also recommend the following article as a reference:

OutOfMemoryError: unable to create new native thread – Problem Demystified

SQL Current month/ year question

How about:

Select *
from some_table st
where st.month = to_char(sysdate,'MM') and
    st.year = to_char(sysdate,'YYYY');

should work in Oracle. What database are you using? I ask because not all databases have the same date functions.

Foreign key constraints: When to use ON UPDATE and ON DELETE

Do not hesitate to put constraints on the database. You'll be sure to have a consistent database, and that's one of the good reasons to use a database. Especially if you have several applications requesting it (or just one application but with a direct mode and a batch mode using different sources).

With MySQL you do not have advanced constraints like you would have in postgreSQL but at least the foreign key constraints are quite advanced.

We'll take an example, a company table with a user table containing people from theses company

CREATE TABLE COMPANY (
     company_id INT NOT NULL,
     company_name VARCHAR(50),
     PRIMARY KEY (company_id)
) ENGINE=INNODB;

CREATE TABLE USER (
     user_id INT, 
     user_name VARCHAR(50), 
     company_id INT,
     INDEX company_id_idx (company_id),
     FOREIGN KEY (company_id) REFERENCES COMPANY (company_id) ON...
) ENGINE=INNODB;

Let's look at the ON UPDATE clause:

  • ON UPDATE RESTRICT : the default : if you try to update a company_id in table COMPANY the engine will reject the operation if one USER at least links on this company.
  • ON UPDATE NO ACTION : same as RESTRICT.
  • ON UPDATE CASCADE : the best one usually : if you update a company_id in a row of table COMPANY the engine will update it accordingly on all USER rows referencing this COMPANY (but no triggers activated on USER table, warning). The engine will track the changes for you, it's good.
  • ON UPDATE SET NULL : if you update a company_id in a row of table COMPANY the engine will set related USERs company_id to NULL (should be available in USER company_id field). I cannot see any interesting thing to do with that on an update, but I may be wrong.

And now on the ON DELETE side:

  • ON DELETE RESTRICT : the default : if you try to delete a company_id Id in table COMPANY the engine will reject the operation if one USER at least links on this company, can save your life.
  • ON DELETE NO ACTION : same as RESTRICT
  • ON DELETE CASCADE : dangerous : if you delete a company row in table COMPANY the engine will delete as well the related USERs. This is dangerous but can be used to make automatic cleanups on secondary tables (so it can be something you want, but quite certainly not for a COMPANY<->USER example)
  • ON DELETE SET NULL : handful : if you delete a COMPANY row the related USERs will automatically have the relationship to NULL. If Null is your value for users with no company this can be a good behavior, for example maybe you need to keep the users in your application, as authors of some content, but removing the company is not a problem for you.

usually my default is: ON DELETE RESTRICT ON UPDATE CASCADE. with some ON DELETE CASCADE for track tables (logs--not all logs--, things like that) and ON DELETE SET NULL when the master table is a 'simple attribute' for the table containing the foreign key, like a JOB table for the USER table.

Edit

It's been a long time since I wrote that. Now I think I should add one important warning. MySQL has one big documented limitation with cascades. Cascades are not firing triggers. So if you were over confident enough in that engine to use triggers you should avoid cascades constraints.

MySQL triggers activate only for changes made to tables by SQL statements. They do not activate for changes in views, nor by changes to tables made by APIs that do not transmit SQL statements to the MySQL Server

==> See below the last edit, things are moving on this domain

Triggers are not activated by foreign key actions.

And I do not think this will get fixed one day. Foreign key constraints are managed by the InnoDb storage and Triggers are managed by the MySQL SQL engine. Both are separated. Innodb is the only storage with constraint management, maybe they'll add triggers directly in the storage engine one day, maybe not.

But I have my own opinion on which element you should choose between the poor trigger implementation and the very useful foreign keys constraints support. And once you'll get used to database consistency you'll love PostgreSQL.

12/2017-Updating this Edit about MySQL:

as stated by @IstiaqueAhmed in the comments, the situation has changed on this subject. So follow the link and check the real up-to-date situation (which may change again in the future).

How to change the background-color of jumbrotron?

.jumbotron {
background-color:black !important; 

}

Add this one line code in .css file, worked for me!

Powershell send-mailmessage - email to multiple recipients

You must first convert the string to a string array, like this:

$recipients = "Marcel <[email protected]>,Marcelt <[email protected]>"
[string[]]$To = $recipients.Split(',')

Then use Send-MailMessage like this:

Send-MailMessage -From "[email protected]" -To $To -subject "New files" -body "$teloadmin" -BodyAsHtml -priority High -dno onSuccess, onFailure -smtpServer 192.168.170.61

How can you flush a write using a file descriptor?

If you want to go the other way round (associate FILE* with existing file descriptor), use fdopen() :

                                                          FDOPEN(P)

NAME

       fdopen - associate a stream with a file descriptor

SYNOPSIS

       #include <stdio.h>

       FILE *fdopen(int fildes, const char *mode);

Case statement with multiple values in each 'when' block

In a case statement, a , is the equivalent of || in an if statement.

case car
   when 'toyota', 'lexus'
      # code
end

Some other things you can do with a Ruby case statement

Concat strings by & and + in VB.Net

From a former string concatenater (sp?) you should really consider using String.Format instead of concatenation.

    Dim s1 As String
    Dim i As Integer
    s1 = "Hello"
    i = 1
    String.Format("{0} {1}", s1, i)

It makes things a lot easier to read and maintain and I believe makes your code look more professional. See: code better – use string.format. Although not everyone agrees When is it better to use String.Format vs string concatenation?

Run an Ansible task only when the variable contains a specific string

I used

failed_when: not(promtool_version.stdout.find('1.5.2') != -1)

means - failed only when the previously registered variable "promtool_version" doesn't contains string '1.5.2'.

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '127.0.0.1' (61) Mac Macintosh

Ran into a similar issue and my problem was that MySQL installed itself configured to run on non-default port. I do not know the reason for that, but to find out which port MySQL is running on, run the following in MySql client:

SHOW GLOBAL VARIABLES LIKE 'PORT';

Calling a rest api with username and password - how to

If the API says to use HTTP Basic authentication, then you need to add an Authorization header to your request. I'd alter your code to look like this:

    WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value&param2=value");
    req.Method = "GET";
    req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
    //req.Credentials = new NetworkCredential("username", "password");
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

Replacing "username" and "password" with the correct values, of course.

Randomize numbers with jQuery?

Coding in Perl, I used the rand() function that generates the number at random and wanted only 1, 2, or 3 to be randomly selected. Due to Perl printing out the number one when doing "1 + " ... so I also did a if else statement that if the number generated zero, run the function again, and it works like a charm.

printing out the results will always give a random number of either 1, 2, or 3.

That is just another idea and sure people will say that is newbie stuff but at the same time, I am a newbie but it works. My issue was when printing out my stuff, it kept spitting out that 1 being used to start at 1 and not zero for indexing.

Find and replace words/lines in a file

Any decent text editor has a search&replace facility that supports regular expressions.

If however, you have reason to reinvent the wheel in Java, you can do:

Path path = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;

String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("foo", "bar");
Files.write(path, content.getBytes(charset));

This only works for Java 7 or newer. If you are stuck on an older Java, you can do:

String content = IOUtils.toString(new FileInputStream(myfile), myencoding);
content = content.replaceAll(myPattern, myReplacement);
IOUtils.write(content, new FileOutputStream(myfile), myencoding);

In this case, you'll need to add error handling and close the streams after you are done with them.

IOUtils is documented at http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html

Using NULL in C++?

From crtdbg.h (and many other headers):

#ifndef NULL
#ifdef __cplusplus
#define NULL    0
#else
#define NULL    ((void *)0)
#endif
#endif

Therefore NULL is 0, at least on the Windows platform. So no, not that I know of.

How npm start runs a server on port 8000

If you will look at package.json file.

you will see something like this

 "start": "http-server -a localhost -p 8000"

This tells start a http-server at address of localhost on port 8000

http-server is a node-module.

Update:- Including comment by @Usman, ideally it should be present in your package.json but if it's not present you can include it in scripts section.

Radio button validation in javascript

document.forms[ 'forms1' ].onsubmit = function() {
    return [].some.call( this.elements, function( el ) {
        return el.type === 'radio' ? el.checked : false
    } )
}

Just something out of my head. Not sure the code is working.

Change WPF controls from a non-main thread using Dispatcher.Invoke

The first thing is to understand that, the Dispatcher is not designed to run long blocking operation (such as retrieving data from a WebServer...). You can use the Dispatcher when you want to run an operation that will be executed on the UI thread (such as updating the value of a progress bar).

What you can do is to retrieve your data in a background worker and use the ReportProgress method to propagate changes in the UI thread.

If you really need to use the Dispatcher directly, it's pretty simple:

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() => this.progressBar.Value = 50));

How to check certificate name and alias in keystore files?

You can run the following command to list the content of your keystore file (and alias name):

keytool -v -list -keystore .keystore

If you are looking for a specific alias, you can also specify it in the command:

keytool -list -keystore .keystore -alias foo

If the alias is not found, it will display an exception:

keytool error: java.lang.Exception: Alias does not exist

SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN'

That is invalid syntax. You are mixing relational expressions with scalar operators (OR). Specifically you cannot combine expr IN (select ...) OR (select ...). You probably want expr IN (select ...) OR expr IN (select ...). Using union would also work: expr IN (select... UNION select...)

How to write URLs in Latex?

Here is all the information you need in order to format clickable hyperlinks in LaTeX:

http://en.wikibooks.org/wiki/LaTeX/Hyperlinks

Essentially, you use the hyperref package and use the \url or \href tag depending on what you're trying to achieve.

How to convert a string to utf-8 in Python

In Python 2

>>> plain_string = "Hi!"
>>> unicode_string = u"Hi!"
>>> type(plain_string), type(unicode_string)
(<type 'str'>, <type 'unicode'>)

^ This is the difference between a byte string (plain_string) and a unicode string.

>>> s = "Hello!"
>>> u = unicode(s, "utf-8")

^ Converting to unicode and specifying the encoding.

In Python 3

All strings are unicode. The unicode function does not exist anymore. See answer from @Noumenon

Restricting input to textbox: allowing only numbers and decimal point

Are you looking for something like this?

   <HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
   </BODY>
  </HTML>

Javascript - User input through HTML input tag to set a Javascript variable?

This is bad style, but I'll assume you have a good reason for doing something similar.

<html>
<body>
    <input type="text" id="userInput">give me input</input>
    <button id="submitter">Submit</button>
    <div id="output"></div>
    <script>
        var didClickIt = false;
        document.getElementById("submitter").addEventListener("click",function(){
            // same as onclick, keeps the JS and HTML separate
            didClickIt = true;
        });

        setInterval(function(){
            // this is the closest you get to an infinite loop in JavaScript
            if( didClickIt ) {
                didClickIt = false;
                // document.write causes silly problems, do this instead (or better yet, use a library like jQuery to do this stuff for you)
                var o=document.getElementById("output"),v=document.getElementById("userInput").value;
                if(o.textContent!==undefined){
                    o.textContent=v;
                }else{
                    o.innerText=v;
                }
            }
        },500);
    </script>
</body>
</html>

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

How does strtok() split the string into tokens in C?

This is how i implemented strtok, Not that great but after working 2 hr on it finally got it worked. It does support multiple delimiters.

#include "stdafx.h"
#include <iostream>
using namespace std;

char* mystrtok(char str[],char filter[]) 
{
    if(filter == NULL) {
        return str;
    }
    static char *ptr = str;
    static int flag = 0;
    if(flag == 1) {
        return NULL;
    }
    char* ptrReturn = ptr;
    for(int j = 0; ptr != '\0'; j++) {
        for(int i=0 ; filter[i] != '\0' ; i++) {
            if(ptr[j] == '\0') {
                flag = 1;
                return ptrReturn;
            }
            if( ptr[j] == filter[i]) {
                ptr[j] = '\0';
                ptr+=j+1;
                return ptrReturn;
            }
        }
    }
    return NULL;
}

int _tmain(int argc, _TCHAR* argv[])
{
    char str[200] = "This,is my,string.test";
    char *ppt = mystrtok(str,", .");
    while(ppt != NULL ) {
        cout<< ppt << endl;
        ppt = mystrtok(NULL,", ."); 
    }
    return 0;
}

How to store .pdf files into MySQL as BLOBs using PHP?

EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.


Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:

$result = mysql_query 'INSERT INTO table (
    data
) VALUES (
    \'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';

A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.

Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.

UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it

Here's how to do it with mysqli in procedural mode:

$result = mysqli_query ($db, 'INSERT INTO table (
    data
) VALUES (
    \'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');

The ideal way of doing it is with MySQLI/PDO prepared statements.

Checking Bash exit status of several commands efficiently

An alternative is simply to join the commands together with && so that the first one to fail prevents the remainder from executing:

command1 &&
  command2 &&
  command3

This isn't the syntax you asked for in the question, but it's a common pattern for the use case you describe. In general the commands should be responsible for printing failures so that you don't have to do so manually (maybe with a -q flag to silence errors when you don't want them). If you have the ability to modify these commands, I'd edit them to yell on failure, rather than wrap them in something else that does so.


Notice also that you don't need to do:

command1
if [ $? -ne 0 ]; then

You can simply say:

if ! command1; then

And when you do need to check return codes use an arithmetic context instead of [ ... -ne:

ret=$?
# do something
if (( ret != 0 )); then

onchange equivalent in angular2

@Mark Rajcok gave a great solution for ion projects that include a range type input.

In any other case of non ion projects I will suggest this:

HTML:

<input type="text" name="points" #points maxlength="8" [(ngModel)]="range" (ngModelChange)="range=saverange($event, points)">

Component:

    onChangeAchievement(eventStr: string, eRef): string {

      //Do something (some manipulations) on input and than return it to be saved:

       //In case you need to force of modifing the Element-Reference value on-focus of input:
       var eventStrToReplace = eventStr.replace(/[^0-9,eE\.\+]+/g, "");
       if (eventStr != eventStrToReplace) {
           eRef.value = eventStrToReplace;
       }

      return this.getNumberOnChange(eventStr);

    }

The idea here:

  1. Letting the (ngModelChange) method to do the Setter job:

    (ngModelChange)="range=saverange($event, points)

  2. Enabling direct access to the native Dom element using this call:

    eRef.value = eventStrToReplace;

CSS3 gradient background set on body doesn't stretch but instead repeats?

Dirty; maybe could you just add a min-height: 100%; to the html, and body tags? That or at least set a default background color that is the end gradient color as well.

How to find whether or not a variable is empty in Bash?

To check if variable v is not set

if [ "$v" == "" ]; then
   echo "v not set"
fi

Cannot perform runtime binding on a null reference, But it is NOT a null reference

This exception is also thrown when a non-existent property is being updated dynamically, using reflection.

If one is using reflection to dynamically update property values, it's worth checking to make sure the passed PropertyName is identical to the actual property.

In my case, I was attempting to update Employee.firstName, but the property was actually Employee.FirstName.

Worth keeping in mind. :)

How to add a vertical Separator?

Here is how I did it:

<TextBlock Margin="0,-2,0,0">|</TextBlock>

How to send email to multiple address using System.Net.Mail

I'm used "for" operator.

try
{
    string s = textBox2.Text;
    string[] f = s.Split(',');

    for (int i = 0; i < f.Length; i++)
    {
        MailMessage message = new MailMessage(); // Create instance of message
        message.To.Add(f[i]); // Add receiver
        message.From = new System.Net.Mail.MailAddress(c);// Set sender .In this case the same as the username
        message.Subject = label3.Text; // Set subject
        message.Body = richTextBox1.Text; // Set body of message
        client.Send(message); // Send the message
        message = null; // Clean up
    }

}

catch (Exception ex)
{

    MessageBox.Show(ex.Message);
}

plain count up timer in javascript

Check this:

_x000D_
_x000D_
var minutesLabel = document.getElementById("minutes");_x000D_
var secondsLabel = document.getElementById("seconds");_x000D_
var totalSeconds = 0;_x000D_
setInterval(setTime, 1000);_x000D_
_x000D_
function setTime() {_x000D_
  ++totalSeconds;_x000D_
  secondsLabel.innerHTML = pad(totalSeconds % 60);_x000D_
  minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));_x000D_
}_x000D_
_x000D_
function pad(val) {_x000D_
  var valString = val + "";_x000D_
  if (valString.length < 2) {_x000D_
    return "0" + valString;_x000D_
  } else {_x000D_
    return valString;_x000D_
  }_x000D_
}
_x000D_
<label id="minutes">00</label>:<label id="seconds">00</label>
_x000D_
_x000D_
_x000D_

Return multiple values from a SQL Server function

Example of using a stored procedure with multiple out parameters

As User Mr. Brownstone suggested you can use a stored procedure; to make it easy for all i created a minimalist example. First create a stored procedure:

Create PROCEDURE MultipleOutParameter
    @Input int,
    @Out1 int OUTPUT, 
    @Out2 int OUTPUT 
AS
BEGIN
    Select @Out1 = @Input + 1
    Select @Out2 = @Input + 2   
    Select 'this returns your normal Select-Statement' as Foo
          , 'amazing is it not?' as Bar

    -- Return can be used to get even more (afaik only int) values 
    Return(@Out1+@Out2+@Input)
END 

Calling the stored procedure

To execute the stored procedure a few local variables are needed to receive the value:

DECLARE @GetReturnResult int, @GetOut1 int, @GetOut2 int 
EXEC @GetReturnResult = MultipleOutParameter  
    @Input = 1,
    @Out1 = @GetOut1 OUTPUT,
    @Out2 = @GetOut2 OUTPUT

To see the values content you can do the following

Select @GetReturnResult as ReturnResult, @GetOut1 as Out_1, @GetOut2 as Out_2 

This will be the result:

Result of Stored Procedure Call with multiple out parameters

Time comparison

I am using this class for time in this format "hh:mm:ss" u can use it with "hh:mm:00" (zero seconds) for your example. Here is the complete code. It has compare and between function and also checks the time format (in case of invalid time and throws TimeException). Hope you can use it or modify it for your needs.

Time class:

package es.utility.time;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author adrian
 */
public class Time {

    private int hours; //Hours of the day
    private int minutes; //Minutes of the day
    private int seconds; //Seconds of the day
    private String time; //Time of the day

    /**
     * Constructor of Time class
     *
     * @param time
     * @throws TimeException if time parameter is not valid
     */
    public Time(String time) throws TimeException {
        //Check if valid time
        if (!validTime(time)) {
            throw new TimeException();
        }
        //Init class parametars
        String[] params = time.split(":");
        this.time = time;
        this.hours = Integer.parseInt(params[0]);
        this.minutes = Integer.parseInt(params[1]);
        this.seconds = Integer.parseInt(params[2]);
    }

    /**
     * Constructor of Time class
     *
     * @param hours
     * @param minutes
     * @param seconds
     * @throws TimeException if time parameter is not valid
     */
    public Time(int hours, int minutes, int seconds) throws TimeException {
        //Check if valid time
        if (!validTime(hours, minutes, seconds)) {
            throw new TimeException();
        }
        this.time = timeToString(hours, minutes, seconds);
        this.hours = hours;
        this.minutes = minutes;
        this.seconds = seconds;

    }

    /**
     * Checks if the sting can be parsed as time
     *
     * @param time (correct from hh:mm:ss)
     * @return true if ok <br/> false if not ok
     */
    private boolean validTime(String time) {
        String regex = "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(time);
        return m.matches();
    }

    /**
     * Checks if the sting can be parsed as time
     *
     * @param hours hours
     * @param minutes minutes
     * @param seconds seconds
     * @return true if ok <br/> false if not ok
     */
    private boolean validTime(int hours, int minutes, int seconds) {
        return hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59 && seconds >= 0 && seconds <= 59;
    }

    /**
     * From Integer values to String time
     *
     * @param hours
     * @param minutes
     * @param seconds
     * @return String generated from int values for hours minutes and seconds
     */
    private String timeToString(int hours, int minutes, int seconds) {
        StringBuilder timeBuilder = new StringBuilder("");
        if (hours < 10) {
            timeBuilder.append("0").append(hours);
        } else {
            timeBuilder.append(hours);
        }
        timeBuilder.append(":");
        if (minutes < 10) {
            timeBuilder.append("0").append(minutes);
        } else {
            timeBuilder.append(minutes);
        }
        timeBuilder.append(":");
        if (seconds < 10) {
            timeBuilder.append("0").append(seconds);
        } else {
            timeBuilder.append(seconds);
        }
        return timeBuilder.toString();
    }

    /**
     * Compare this time to other
     *
     * @param compare
     * @return -1 time is before <br/> 0 time is equal <br/> time is after
     */
    public int compareTime(Time compare) {
        //Check hours
        if (this.getHours() < compare.getHours()) { //If hours are before return -1
            return -1;
        }
        if (this.getHours() > compare.getHours()) { //If hours are after return 1
            return 1;
        }
        //If no return hours are equeal
        //Check minutes
        if (this.getMinutes() < compare.getMinutes()) { //If minutes are before return -1
            return -1;
        }
        if (this.getMinutes() > compare.getMinutes()) { //If minutes are after return 1
            return 1;
        }
        //If no return minutes are equeal
        //Check seconds
        if (this.getSeconds() < compare.getSeconds()) { //If minutes are before return -1
            return -1;
        }
        if (this.getSeconds() > compare.getSeconds()) { //If minutes are after return 1
            return 1;
        }
        //If no return seconds are equeal and return 0
        return 0;
    }

    public boolean isBetween(Time before, Time after) throws TimeException{
        if(before.compareTime(after)== 1){
            throw new TimeException("Time 'before' is after 'after' time");
        }
        //Compare with before and after
        if (this.compareTime(before) == -1 || this.compareTime(after) == 1) { //If time is before before time return false or time is after after time
            return false;
        } else {
            return true;
        }
    }

    public int getHours() {
        return hours;
    }

    public void setHours(int hours) {
        this.hours = hours;
    }

    public int getMinutes() {
        return minutes;
    }

    public void setMinutes(int minutes) {
        this.minutes = minutes;
    }

    public int getSeconds() {
        return seconds;
    }

    public void setSeconds(int seconds) {
        this.seconds = seconds;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    /**
     * Override the toString method and return all of the class private
     * parameters
     *
     * @return String Time{" + "hours=" + hours + ", minutes=" + minutes + ",
     * seconds=" + seconds + ", time=" + time + '}'
     */
    @Override
    public String toString() {
        return "Time{" + "hours=" + hours + ", minutes=" + minutes + ", seconds=" + seconds + ", time=" + time + '}';
    }

}

TimeException class:

package es.utility.time;

/**
 *
 * @author adrian
 */
public class TimeException extends Exception {

    public TimeException() {
        super("Cannot create time with this params");
    }

    public TimeException(String message) {
        super(message);
    }

}

How to parse Excel (XLS) file in Javascript/HTML5

include the xslx.js , xlsx.full.min.js , jszip.js

add a onchange event handler to the file input

function showDataExcel(event)
{
            var file = event.target.files[0];
            var reader = new FileReader();
            var excelData = [];
            reader.onload = function (event) {
                var data = event.target.result;
                var workbook = XLSX.read(data, {
                    type: 'binary'
                });

                workbook.SheetNames.forEach(function (sheetName) {
                    // Here is your object
                    var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);

                    for (var i = 0; i < XL_row_object.length; i++)
                    {
                        excelData.push(XL_row_object[i]["your column name"]);

                    }

                    var json_object = JSON.stringify(XL_row_object);
                    console.log(json_object);
                    alert(excelData);
                })

            };

            reader.onerror = function (ex) {
                console.log(ex);
            };

            reader.readAsBinaryString(file);

}

gcc error: wrong ELF class: ELFCLASS64

It looks like the object file was compiled on a 64-bit toolchain, and you're using a 32-bit toolchain. Have you tried recompiling the object file in 32-bit mode?

JavaScript blob filename without link

Late, but since I had the same problem I add my solution:

function newFile(data, fileName) {
    var json = JSON.stringify(data);
    //IE11 support
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        let blob = new Blob([json], {type: "application/json"});
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {// other browsers
        let file = new File([json], fileName, {type: "application/json"});
        let exportUrl = URL.createObjectURL(file);
        window.location.assign(exportUrl);
        URL.revokeObjectURL(exportUrl);
    }
}

File Upload in WebView

In 5.0 Lollipop, Google added an official method, WebChromeClient.onShowFileChooser. They even provide a way to automatically generate the file chooser intent so that it uses the input accept mime types.

public class MyWebChromeClient extends WebChromeClient {
        // reference to activity instance. May be unnecessary if your web chrome client is member class.
    private MyActivity activity;

    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
        // make sure there is no existing message
        if (myActivity.uploadMessage != null) {
            myActivity.uploadMessage.onReceiveValue(null);
            myActivity.uploadMessage = null;
        }

        myActivity.uploadMessage = filePathCallback;

        Intent intent = fileChooserParams.createIntent();
        try {
            myActivity.startActivityForResult(intent, MyActivity.REQUEST_SELECT_FILE);
        } catch (ActivityNotFoundException e) {
            myActivity.uploadMessage = null;
            Toast.makeText(myActivity, "Cannot open file chooser", Toast.LENGTH_LONG).show();
            return false;
        }

        return true;
    }
}


public class MyActivity extends ... {
    public static final int REQUEST_SELECT_FILE = 100;
    public ValueCallback<Uri[]> uploadMessage;

    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if (requestCode == REQUEST_SELECT_FILE) {
                if (uploadMessage == null) return;
                uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
                uploadMessage = null;
            }
        }
    }
}

For Android versions before KitKat, the private methods mentioned in the other answers work. I have not found a good workaround for KitKat (4.4).

How can I stop the browser back button using JavaScript?

<html>
<head>
    <title>Disable Back Button in Browser - Online Demo</title>
    <style type="text/css">
        body, input {
            font-family: Calibri, Arial;
        }
    </style>
    <script type="text/javascript">
        window.history.forward();
        function noBack() {
            window.history.forward();
        }
    </script>
</head>
<body onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">
    <H2>Demo</H2>
    <p>This page contains the code to avoid Back button.</p>
    <p>Click here to Goto <a href="noback.html">NoBack Page</a></p>
</body>
</html>

How to utilize date add function in Google spreadsheet?

Using pretty much the same approach as used by Burnash, for the final result you can use ...

=regexextract(A1,"[0-9]+")+A2

where A1 houses the string with text and number and A2 houses the date of interest

SQL Server Profiler - How to filter trace to only display events from one database?

In SQL 2005, you first need to show the Database Name column in your trace. The easiest thing to do is to pick the Tuning template, which has that column added already.

Assuming you have the Tuning template selected, to filter:

  • Click the "Events Selection" tab
  • Click the "Column Filters" button
  • Check Show all Columns (Right Side Down)
  • Select "DatabaseName", click the plus next to Like in the right-hand pane, and type your database name.

I always save the trace to a table too so I can do LIKE queries on the trace data after the fact.

How to uninstall downloaded Xcode simulator?

NOTE: This will only remove a device configuration from the Xcode devices list. To remove the simulator files from your hard drive see the previous answer.

For Xcode 7 just use Window \ Devices menu in Xcode:

Devices menu

Then select emulator to delete in the list on the left side and right click on it. Here is Delete option: enter image description here

That's all.

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

The only way I could get it to work is if my Mac and my iPhone were on different networks. I have a main DSL modem call it network1 and a second network2 setup us an access point. They have SSIDs network1 and network2. If the phone was on network1 and the mac on network2 it would work, or vice versa. But if both were on network1 or both were on network2, it would NOT work.

How do I capture all of my compiler's output to a file?

In C shell - The ampersand is after the greater-than symbol

make >& filename

How to use the gecko executable with Selenium

You need to specify the system property with the path the .exe when starting the Selenium server node. See also the accepted anwser to Selenium grid with Chrome driver (WebDriverException: The path to the driver executable must be set by the webdriver.chrome.driver system property)

How to Git stash pop specific stash in 1.8.3?

You need to escape the braces:

git stash pop stash@\{1\}

How do I set the version information for an existing .exe, .dll?

rcedit is relative new and works well from the command line: https://github.com/atom/rcedit

$ rcedit "path-to-exe-or-dll" --set-version-string "Comments" "This is an exe"
$ rcedit "path-to-exe-or-dll" --set-file-version "10.7"
$ rcedit "path-to-exe-or-dll" --set-product-version "10.7"

There's also an NPM module which wraps it from JavaScript and a Grunt task in case you're using Grunt.

Regex for Mobile Number Validation

Try this regex:

^(\+?\d{1,4}[\s-])?(?!0+\s+,?$)\d{10}\s*,?$

Explanation of the regex using Perl's YAPE is as below:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  ^                        the beginning of the string
----------------------------------------------------------------------
  (                        group and capture to \1 (optional
                           (matching the most amount possible)):
----------------------------------------------------------------------
    \+?                      '+' (optional (matching the most amount
                             possible))
----------------------------------------------------------------------
    \d{1,4}                  digits (0-9) (between 1 and 4 times
                             (matching the most amount possible))
----------------------------------------------------------------------
    [\s-]                    any character of: whitespace (\n, \r,
                             \t, \f, and " "), '-'
----------------------------------------------------------------------
  )?                       end of \1 (NOTE: because you are using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in \1)
----------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
----------------------------------------------------------------------
    0+                       '0' (1 or more times (matching the most
                             amount possible))
----------------------------------------------------------------------
    \s+                      whitespace (\n, \r, \t, \f, and " ") (1
                             or more times (matching the most amount
                             possible))
----------------------------------------------------------------------
    ,?                       ',' (optional (matching the most amount
                             possible))
----------------------------------------------------------------------
    $                        before an optional \n, and the end of
                             the string
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  \d{10}                   digits (0-9) (10 times)
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  ,?                       ',' (optional (matching the most amount
                           possible))
----------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

Open file dialog and select a file using WPF controls and C#

var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"}; 
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;

Spring Boot: Cannot access REST Controller on localhost (404)

The problem is with your package structure. Spring Boot Application has a specific package structure to allow spring context to scan and load various beans in its context.

In com.nice.application is where your Main Class is and in com.nice.controller, you have your controller classes.

Move your com.nice.controller package into com.nice.application so that Spring can access your beans.

Simplest way to throw an error/exception with a custom message in Swift 2?

Throwing code should make clear whether the error message is appropriate for display to end users or is only intended for developer debugging. To indicate a description is displayable to the user, I use a struct DisplayableError that implements the LocalizedError protocol.

struct DisplayableError: Error, LocalizedError {
    let errorDescription: String?

    init(_ description: String) {
        errorDescription = description
    }
}

Usage for throwing:

throw DisplayableError("Out of pixie dust.")

Usage for display:

let messageToDisplay = error.localizedDescription

How to fix Git error: object file is empty?

I'm having this problem every once in a while, It is happening due to computer or VM operation problems during a git operation.

The best solution for me is to remove the git objects and all related ref git files:

sudo rm -r .git/objects/* .git/refs/heads/* .git/refs/remotes/* .git/refs/stash .git/refs/tags/*

and then pull the repo:

git pull

That solves everything for me in the easiest way without risking my source code or cloning the repo again.

How do I align spans or divs horizontally?

I would try to give them all display: block; attribute and using float: left;.

You can then set width and/or height as you like. You can even specify some vertical-alignment rules.

Python conversion between coordinates

If your coordinates are stored as complex numbers you can use cmath

node.js - request - How to "emitter.setMaxListeners()"?

It also happened to me

I use this code and it worked

require('events').EventEmitter.defaultMaxListeners = infinity;

Try it out. It may help

Thanks

Create a OpenSSL certificate on Windows

You can download a native OpenSSL for Windows, or you can always use Cygwin.

How to output git log with the first line only?

git log --format="%H" -n 1

Use the above command to get the commitid, hope this helps.

Where to get "UTF-8" string literal in Java?

This constant is available (among others as: UTF-16, US-ASCII, etc.) in the class org.apache.commons.codec.CharEncoding as well.

Replace and overwrite instead of appending

Using truncate(), the solution could be

import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
    #convert to string:
    data = f.read()
    f.seek(0)
    f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
    f.truncate()

How to completely remove node.js from Windows

In my case, the above alone didn't work. I had installed and uninstalled several versions of nodejs to fix this error: npm in windows Error: EISDIR, read at Error (native) that I kept getting on any npm command I tried to run, including getting the npm version with: npm -v.

So the npm directory was deleted in the nodejs folder and the latest npm version was copied over from the npm dist: and then everything started working.

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

Your web form should look like this:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebUI._Default" MasterPageFile="~/Site1.Master" %>
<asp:Content runat="server" ID="head" ContentPlaceHolderId="head">
<!-- stuff you want in &gt;head%lt; -->
</asp:Content>

<asp:Content runat="server" ID="content" ContentPlaceHolderId="ContentPlaceHolder1">
<h1>Your content</h1>
</asp:Content>

Note that there is no <html> tag

Iterating over every two elements in a list

you can use more_itertools package.

import more_itertools

lst = range(1, 7)
for i, j in more_itertools.chunked(lst, 2):
    print(f'{i} + {j} = {i+j}')

import an array in python

(I know the question is old, but I think this might be good as a reference for people with similar questions)

If you want to load data from an ASCII/text file (which has the benefit or being more or less human-readable and easy to parse in other software), numpy.loadtxt is probably what you want:

If you just want to quickly save and load numpy arrays/matrices to and from a file, take a look at numpy.save and numpy.load:

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

resolved this for me as well; however, I noticed that the servlet restart times were much worse, so while it was better in production, it was kind of a drag in development.

How to round a floating point number up to a certain decimal place?

You want to use the decimal module but you also need to specify the rounding mode. Here's an example:

>>> import decimal
>>> decimal.Decimal('8.333333').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_UP)
Decimal('8.34')
>>> decimal.Decimal('8.333333').quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
Decimal('8.33')
>>> 

Should I learn C before learning C++?

i think c is a really nice programming language, it's compact and somewhat easy to learn. but if you only want to learn c++ start with c++. but i suggest you to learn both. and if you want to do that; i think it's better to start with c. as said before: it's small and somewhat easy to learn. might be a nice step-up to a more complex programming language as c++. (since c provides you with some basics)

good luck.

Add all files to a commit except a single file?

Use git add -A to add all modified and newly added files at once.

Example

git add -A
git reset -- main/dontcheckmein.txt

Swift double to string

to make anything a string in swift except maybe enum values simply do what you do in the println() method

for example:

var stringOfDBL = "\(myDouble)"

SELECT CASE WHEN THEN (SELECT)

You Could try the other format for the case statement

CASE WHEN Product.type_id = 10
THEN
(
  Select Statement
)
ELSE
(
  Other select statement

)  
END
FROM Product 
WHERE Product.product_id = $pid

See http://msdn.microsoft.com/en-us/library/ms181765.aspx for more information.

Difference between PACKETS and FRAMES

Actually, there are five words commonly used when we talk about layers of reference models (or protocol stacks): data, segment, packet, frame and bit. And the term PDU (Protocol Data Unit) is used to refer to the packets in different layers of the OSI model. Thus PDU gives an abstract idea of the data packets. The PDU has a different meaning in different layers still we can use it as a common term.

When we come to your question, we can call all of them by using the general term PDU, but if you want to call them specifically at a given layer:

  • Data: PDU of Application, Presentation and Session Layers
  • Segment: PDU of Transport Layer
  • Packet: PDU of network Layer
  • Frame: PDU of data-link Layer
  • Bit: PDU of physical Layer

Here is a diagram, since a picture is worth a thousand words: a picture is worth a thousand words

How to toggle font awesome icon on click?

Generally and simply it works like this:

_x000D_
_x000D_
<script>_x000D_
            $(document).ready(function () {_x000D_
                $('i').click(function () {_x000D_
                    $(this).toggleClass('fa-plus-square fa-minus-square');_x000D_
                });_x000D_
            });_x000D_
</script>
_x000D_
_x000D_
_x000D_

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

If you use androidX instead of android, you need change

import android.support.v7.app.AppCompatActivity;

to

import androidx.appcompat.app.AppCompatActivity;

and change

<android.support.constraint.ConstraintLayout>

to

<androidx.constraintlayout.widget.ConstraintLayout>

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

"Actual or formal argument lists differs in length"

You try to instantiate an object of the Friends class like this:

Friends f = new Friends(friendsName, friendsAge);

The class does not have a constructor that takes parameters. You should either add the constructor, or create the object using the constructor that does exist and then use the set-methods. For example, instead of the above:

Friends f = new Friends();
f.setName(friendsName);
f.setAge(friendsAge);

How to get selected option using Selenium WebDriver with Java

var option = driver.FindElement(By.Id("employmentType"));
        var selectElement = new SelectElement(option);
        Task.Delay(3000).Wait();
        selectElement.SelectByIndex(2);
        Console.Read();

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

I would say that one should omit the __init__.py only if one wants to have the implicit namespace package. If you don't know what it means, you probably don't want it and therefore you should continue to use the __init__.py even in Python 3.

Java : Convert formatted xml file to one line string

FileUtils.readFileToString(fileName);

link

Storing data into list with class

This line is your problem:

lstemail.Add("JOhn","Smith","Los Angeles");

There is no direct cast from 3 strings to your custom class. The compiler has no way of figuring out what you're trying to do with this line. You need to Add() an instance of the class to lstemail:

lstemail.Add(new EmailData { FirstName = "JOhn", LastName = "Smith", Location = "Los Angeles" });

How do I check if an object has a specific property in JavaScript?

if (x.key !== undefined)

Armin Ronacher seems to have already beat me to it, but:

Object.prototype.hasOwnProperty = function(property) {
    return this[property] !== undefined;
};

x = {'key': 1};

if (x.hasOwnProperty('key')) {
    alert('have key!');
}

if (!x.hasOwnProperty('bar')) {
    alert('no bar!');
}

A safer, but slower solution, as pointed out by Konrad Rudolph and Armin Ronacher would be:

Object.prototype.hasOwnProperty = function(property) {
    return typeof this[property] !== 'undefined';
};

Can Android do peer-to-peer ad-hoc networking?

In addition to Telmo Marques answer: I use Virtual Router for this.

Like connectify it creates an accesspoint on your Windows 8, Windows 7 or 2008 R2 machine, but it's open-source.

How to get a file directory path from file path?

dirname and basename are the tools you're looking for for extracting path components:

$ export VAR='/home/pax/file.c'
$ echo "$(dirname "${VAR}")" ; echo "$(basename "${VAR}")"
/home/pax
file.c

They're not internal Bash commands but they're part of the POSIX standard - see dirname and basename. Hence, they're probably available on, or can be obtained for, most platforms that are capable of running bash.

Alter Table Add Column Syntax

The correct syntax for adding column into table is:

ALTER TABLE table_name
  ADD column_name column-definition;

In your case it will be:

ALTER TABLE Employees
  ADD EmployeeID int NOT NULL IDENTITY (1, 1)

To add multiple columns use brackets:

ALTER TABLE table_name
  ADD (column_1 column-definition,
       column_2 column-definition,
       ...
       column_n column_definition);

COLUMN keyword in SQL SERVER is used only for altering:

ALTER TABLE table_name
  ALTER COLUMN column_name column_type;

How to set java.net.preferIPv4Stack=true at runtime?

You can use System.setProperty("java.net.preferIPv4Stack" , "true");

This is equivalent to passing it in the command line via -Djava.net.preferIPv4Stack=true

How to JSON decode array elements in JavaScript?

Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -

echo json_encode($iniData);

In Javascript, use the following :

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: "ajaxCalls.php",
            data: "dataType=ini",
            success: function(msg)
            {
                var x = eval('(' + msg + ')');
                $('#allowed').html(x.allowed);              // these are the fields which you can now easily access..
                $('#completed').html(x.completed);
                $('#running').html(x.running);
                $('#expired').html(x.expired);
                $('#balance').html(x.balance);
            }
        });
    });
</script>

React - changing an uncontrolled input

Set a value to 'name' property in initial state.

_x000D_
_x000D_
this.state={ name:''};
_x000D_
_x000D_
_x000D_

fix java.net.SocketTimeoutException: Read timed out

I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).

e.g. (from the doc)

     System.out.println("<< Response: " + response.getStatusLine());
     System.out.println(EntityUtils.toString(response.getEntity()));

How to grant all privileges to root user in MySQL 8.0

My Specs:

mysql --version
mysql  Ver 8.0.19 for Linux on x86_64 (MySQL Community Server - GPL)

What worked for me:

mysql> USE mysql;
mysql> UPDATE User SET Host='%' WHERE User='root' AND Host='localhost';

Parsing xml using powershell

If you want to start with a file you can do this

[xml]$cn = Get-Content config.xml
$cn.xml.Section.BEName

Use PowerShell to Parse an XML File

Yii2 data provider default sorting

Try to this one

$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);

$sort = $dataProvider->getSort();

$sort->defaultOrder = ['id' => SORT_ASC];

$dataProvider->setSort($sort);