Programs & Examples On #Control flow

Control flow (or flow of control) refers to the order in which statements are evaluated or executed.

How to break out of multiple loops?

Solutions in 2 Ways

With an example: Are these two matrices equal/same?
matrix1 and matrix2 are same size, n, 2 dimentional matrices.

First Solution, without a function

same_matrices = True
inner_loop_broken_once = False
n = len(matrix1)

for i in range(n):
    for j in range(n):

        if matrix1[i][j] != matrix2[i][j]:
            same_matrices = False
            inner_loop_broken_once = True
            break

    if inner_loop_broken_once:
        break

Second Solution, with a function
This is the final solution for my case

def are_two_matrices_the_same (matrix1, matrix2):
    n = len(matrix1)
    for i in range(n):
        for j in range(n):
            if matrix1[i][j] != matrix2[i][j]:
                return False
    return True

Have a nice day!

How to exit an if clause

For what was actually asked, my approach is to put those ifs inside a one-looped loop

while (True):
    if (some_condition):
        ...
        if (condition_a):
            # do something
            # and then exit the outer if block
            break
        ...
        if (condition_b):
            # do something
            # and then exit the outer if block
            break
        # more code here
    # make sure it is looped once
    break

Test it:

conditions = [True,False]
some_condition = True

for condition_a in conditions:
    for condition_b in conditions:
        print("\n")
        print("with condition_a", condition_a)
        print("with condition_b", condition_b)
        while (True):
            if (some_condition):
                print("checkpoint 1")
                if (condition_a):
                    # do something
                    # and then exit the outer if block
                    print("checkpoint 2")
                    break
                print ("checkpoint 3")
                if (condition_b):
                    # do something
                    # and then exit the outer if block
                    print("checkpoint 4")
                    break
                print ("checkpoint 5")
                # more code here
            # make sure it is looped once
            break

SQL Server 2000: How to exit a stored procedure?

Unless you specify a severity of 20 or higher, raiserror will not stop execution. See the MSDN documentation.

The normal workaround is to include a return after every raiserror:

if @whoops = 1
    begin
    raiserror('Whoops!', 18, 1)
    return -1
    end

Passing ArrayList through Intent

//arraylist/Pojo you can Pass using bundle  like this 
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
                        args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
                        intent.putExtra("BUNDLE",args);
 startActivity(intent); 


Get SecondActivity like this
  Intent intent = getIntent();
        Bundle args = intent.getBundleExtra("BUNDLE");
String filter = bundle.getString("imageSliders");

//Happy coding

How to switch from POST to GET in PHP CURL

Solved: The problem lies here:

I set POST via both _CUSTOMREQUEST and _POST and the _CUSTOMREQUEST persisted as POST while _POST switched to _HTTPGET. The Server assumed the header from _CUSTOMREQUEST to be the right one and came back with a 411.

curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');

You can't specify target table for update in FROM clause

The Approach posted by BlueRaja is slow I modified it as I was using to delete duplicates from the table. In case it helps anyone with large tables Original Query

delete from table where id not in (select min(id) from table group by field 2)

This is taking more time:

DELETE FROM table where ID NOT IN(
  SELECT MIN(t.Id) from (select Id,field2 from table) AS t GROUP BY field2)

Faster Solution

DELETE FROM table where ID NOT IN(
   SELECT x.Id from (SELECT MIN(Id) as Id from table GROUP BY field2) AS t)

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

I just met the same problem with mysql 5.7 on OSX:

rm -rf {datadir}
mysqld --initialize --datadir {datadir}
mysqld --datadir {datadir}

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

Have you tried, after calling DataBind on your DropDownList, to do something like ddl.SelectedIndex = 0 ?

How can I remove a style added with .css() function?

I got the way to remove a style attribute with pure JavaScript just to let you know the way of pure JavaScript

var bodyStyle = document.body.style;
if (bodyStyle.removeAttribute)
    bodyStyle.removeAttribute('background-color');
else        
    bodyStyle.removeProperty('background-color');

Delegates in swift?

Simple Example:

protocol Work: class {
    func doSomething()
}

class Manager {
    weak var delegate: Work?
    func passAlong() {
        delegate?.doSomething()
    }
}

class Employee: Work {
    func doSomething() {
        print("Working on it")
    }
}

let manager = Manager()
let developer = Employee()
manager.delegate = developer
manager.passAlong() // PRINTS: Working on it

Cursor adapter and sqlite example

In Android, How to use a Cursor with a raw query in sqlite:

Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " +
           "where Age > 10 LIMIT 5", null);

if (c != null ) {
    if  (c.moveToFirst()) {
        do {
            String firstName = c.getString(c.getColumnIndex("FirstName"));
            int age = c.getInt(c.getColumnIndex("Age"));
            results.add("" + firstName + ",Age: " + age);
        }while (c.moveToNext());
    }
}
c.close();

Xcode Project vs. Xcode Workspace - Differences

Xcode Workspace vs Project

  1. What is the difference between the two of them?

Workspace is a set of projects

  1. What are they responsible for?

Workspace is responsible for dependencies between projects. Project is responsible for the source code.

  1. Which one of them should I work with when I'm developing my Apps in team/alone?

You choice should depends on a type of your project. For example if your project relies on CocoaPods dependency manager it creates a workspace.

  1. Is there anything else I should be aware of in matter of these two files?

A competitor of workspace is cross-project references[About]

[Xcode components]

Convert unix time stamp to date in java

You need to convert it to milliseconds by multiplying the timestamp by 1000:

java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);

Can promises have multiple arguments to onFulfilled?

I'm following the spec here and I'm not sure whether it allows onFulfilled to be called with multiple arguments.

Nope, just the first parameter will be treated as resolution value in the promise constructor. You can resolve with a composite value like an object or array.

I don't care about how any specific promises implementation does it, I wish to follow the w3c spec for promises closely.

That's where I believe you're wrong. The specification is designed to be minimal and is built for interoperating between promise libraries. The idea is to have a subset which DOM futures for example can reliably use and libraries can consume. Promise implementations do what you ask with .spread for a while now. For example:

Promise.try(function(){
    return ["Hello","World","!"];
}).spread(function(a,b,c){
    console.log(a,b+c); // "Hello World!";
});

With Bluebird. One solution if you want this functionality is to polyfill it.

if (!Promise.prototype.spread) {
    Promise.prototype.spread = function (fn) {
        return this.then(function (args) {
            return Promise.all(args); // wait for all
        }).then(function(args){
         //this is always undefined in A+ complaint, but just in case
            return fn.apply(this, args); 
        });
    };
}

This lets you do:

Promise.resolve(null).then(function(){
    return ["Hello","World","!"]; 
}).spread(function(a,b,c){
    console.log(a,b+c);    
});

With native promises at ease fiddle. Or use spread which is now (2018) commonplace in browsers:

Promise.resolve(["Hello","World","!"]).then(([a,b,c]) => {
  console.log(a,b+c);    
});

Or with await:

let [a, b, c] = await Promise.resolve(['hello', 'world', '!']);

How do I import other TypeScript files?

Quick Easy Process in Visual Studio

Drag and Drop the file with .ts extension from solution window to editor, it will generate inline reference code like..

/// <reference path="../../components/someclass.ts"/>

Format a datetime into a string with milliseconds

In python 3.6 and above using python f-strings:

from datetime import datetime 

i = datetime.utcnow()

print(f"""{i:%Y-%m-%d %H:%M:%S}.{"{:03d}".format(i.microsecond // 1000)}""")

The code specific to format milliseconds is:

{"{:03d}".format(i.microsecond // 1000)}

The format string {:03d} and microsecond to millisecond conversion // 1000 is from def _format_time in https://github.com/python/cpython/blob/master/Lib/datetime.py that is used for datetime.datetime.isoformat().

how to filter out a null value from spark dataframe

A good solution for me was to drop the rows with any null values:

Dataset<Row> filtered = df.filter(row => !row.anyNull);

In case one is interested in the other case, just call row.anyNull. (Spark 2.1.0 using Java API)

Possible to perform cross-database queries with PostgreSQL?

see https://www.cybertec-postgresql.com/en/joining-data-from-multiple-postgres-databases/ [published 2017]

These days you also have the option to use https://prestodb.io/

You can run SQL on that PrestoDB node and it will distribute the SQL query as required. It can connect to the same node twice for different databases, or it might be connecting to different nodes on different hosts.

It does not support:

DELETE
ALTER TABLE
CREATE TABLE (CREATE TABLE AS is supported)
GRANT
REVOKE
SHOW GRANTS
SHOW ROLES
SHOW ROLE GRANTS

So you should only use it for SELECT and JOIN needs. Connect directly to each database for the above needs. (It looks like you can also INSERT or UPDATE which is nice)

Client applications connect to PrestoDB primarily using JDBC, but other types of connection are possible including a Tableu compatible web API

This is an open source tool governed by the Linux Foundation and Presto Foundation.

The founding members of the Presto Foundation are: Facebook, Uber, Twitter, and Alibaba.

The current members are: Facebook, Uber, Twitter, Alibaba, Alluxio, Ahana, Upsolver, and Intel.

How to create a file in memory for user to download, but not through server?

The following method works in IE11+, Firefox 25+ and Chrome 30+:

<a id="export" class="myButton" download="" href="#">export</a>
<script>
    function createDownloadLink(anchorSelector, str, fileName){
        if(window.navigator.msSaveOrOpenBlob) {
            var fileData = [str];
            blobObject = new Blob(fileData);
            $(anchorSelector).click(function(){
                window.navigator.msSaveOrOpenBlob(blobObject, fileName);
            });
        } else {
            var url = "data:text/plain;charset=utf-8," + encodeURIComponent(str);
            $(anchorSelector).attr("download", fileName);               
            $(anchorSelector).attr("href", url);
        }
    }

    $(function () {
        var str = "hi,file";
        createDownloadLink("#export",str,"file.txt");
    });

</script>

See this in Action: http://jsfiddle.net/Kg7eA/

Firefox and Chrome support data URI for navigation, which allows us to create files by navigating to a data URI, while IE doesn't support it for security purposes.

On the other hand, IE has API for saving a blob, which can be used to create and download files.

C++ Pass A String

Not very technical answer but just letting you know.

For easy stuff like printing you can define a sort of function in your preprocessors like

#define print(x) cout << x << endl

Paging with Oracle

In the interest of completeness, for people looking for a more modern solution, in Oracle 12c there are some new features including better paging and top handling.

Paging

The paging looks like this:

SELECT *
FROM user
ORDER BY first_name
OFFSET 5 ROWS FETCH NEXT 10 ROWS ONLY;

Top N Records

Getting the top records looks like this:

SELECT *
FROM user
ORDER BY first_name
FETCH FIRST 5 ROWS ONLY

Notice how both the above query examples have ORDER BY clauses. The new commands respect these and are run on the sorted data.

I couldn't find a good Oracle reference page for FETCH or OFFSET but this page has a great overview of these new features.

Performance

As @wweicker points out in the comments below, performance is an issue with the new syntax in 12c. I didn't have a copy of 18c to test if Oracle has since improved it.

Interestingly enough, my actual results were returned slightly quicker the first time I ran the queries on my table (113 million+ rows) for the new method:

  • New method: 0.013 seconds.
  • Old method: 0.107 seconds.

However, as @wweicker mentioned, the explain plan looks much worse for the new method:

  • New method cost: 300,110
  • Old method cost: 30

The new syntax caused a full scan of the index on my column, which was the entire cost. Chances are, things get much worse when limiting on unindexed data.

Let's have a look when including a single unindexed column on the previous dataset:

  • New method time/cost: 189.55 seconds/998,908
  • Old method time/cost: 1.973 seconds/256

Summary: use with caution until Oracle improves this handling. If you have an index to work with, perhaps you can get away with using the new method.

Hopefully I'll have a copy of 18c to play with soon and can update

PHP - Notice: Undefined index:

You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an

if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }

Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string on the post vars before using them in SQL queries. mysql_real_escape_string is not good enough for a production site, but should score you extra points in class.

Delete newline in Vim

It probably depends on your settings, but I usually do this with A<delete>

Where A is append at the end of the line. It probably requires nocompatible mode :)

How to write a simple Html.DropDownListFor()?

See this MSDN article and an example usage here on Stack Overflow.

Let's say that you have the following Linq/POCO class:

public class Color
{
    public int ColorId { get; set; }
    public string Name { get; set; }
}

And let's say that you have the following model:

public class PageModel 
{
   public int MyColorId { get; set; }
}

And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:

public static IEnumerable<Color> Colors = new List<Color> { 
    new Color {
        ColorId = 1,
        Name = "Red"
    },
    new Color {
        ColorId = 2,
        Name = "Blue"
    }
};

In your view, you can create a drop down list like so:

<%= Html.DropDownListFor(n => n.MyColorId, 
                         new SelectList(Colors, "ColorId", "Name")) %>

How to dismiss notification after action has been clicked

Found this to be an issue when using Lollipop's Heads Up Display notification. See design guidelines. Here's the complete(ish) code to implement.

Until now, having a 'Dismiss' button was less important, but now it's more in your face.

heads up notification

Building the Notification

int notificationId = new Random().nextInt(); // just use a counter in some util class...
PendingIntent dismissIntent = NotificationActivity.getDismissIntent(notificationId, context);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setPriority(NotificationCompat.PRIORITY_MAX) //HIGH, MAX, FULL_SCREEN and setDefaults(Notification.DEFAULT_ALL) will make it a Heads Up Display Style
        .setDefaults(Notification.DEFAULT_ALL) // also requires VIBRATE permission
        .setSmallIcon(R.drawable.ic_action_refresh) // Required!
        .setContentTitle("Message from test")
        .setContentText("message")
        .setAutoCancel(true)
        .addAction(R.drawable.ic_action_cancel, "Dismiss", dismissIntent)
        .addAction(R.drawable.ic_action_boom, "Action!", someOtherPendingIntent);

// Gets an instance of the NotificationManager service
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

// Builds the notification and issues it.
notifyMgr.notify(notificationId, builder.build());

NotificationActivity

public class NotificationActivity extends Activity {

    public static final String NOTIFICATION_ID = "NOTIFICATION_ID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(getIntent().getIntExtra(NOTIFICATION_ID, -1));
        finish(); // since finish() is called in onCreate(), onDestroy() will be called immediately
    }

    public static PendingIntent getDismissIntent(int notificationId, Context context) {
        Intent intent = new Intent(context, NotificationActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra(NOTIFICATION_ID, notificationId);
        PendingIntent dismissIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        return dismissIntent;
    }

}

AndroidManifest.xml (attributes required to prevent SystemUI from focusing to a back stack)

<activity
    android:name=".NotificationActivity"
    android:taskAffinity=""
    android:excludeFromRecents="true">
</activity>

Find Facebook user (url to profile page) by known email address

Facebook has a strict policy on sharing only the content which a profile makes public to the end user.. Still what you want is possible if the user has actually left the email id open to public domain.. A wild try u can do is send batch requests for the maximum possible batch size to ids..."http://graph.facebook.com/ .. and parse the result to check if email exists and if it does then it matches to the one you want.. you don't need any access_token for the public information ..

in case you want email id of a FB user only possible way is that they authorize ur app and then you can use the access_token thus generated for the required task.

Expanding a parent <div> to the height of its children

Try this for the parent, it worked for me.

overflow:auto; 

UPDATE:

One more solution that worked:

Parent:

display: table;

Child:

display: table-row;

How to implement a binary search tree in Python?

Here is a working solution.

class BST:
    def __init__(self,data):
        self.root = data
        self.left = None
        self.right = None

    def insert(self,data):
        if self.root == None:
            self.root = BST(data)
        elif data > self.root:
            if self.right == None:
                self.right = BST(data)
            else:
                self.right.insert(data)
        elif data < self.root:
            if self.left == None:
                self.left = BST(data)
            else:
                self.left.insert(data)

    def inordertraversal(self):
        if self.left != None:
            self.left.inordertraversal()
        print (self.root),
        if self.right != None:
            self.right.inordertraversal()

t = BST(4)
t.insert(1)
t.insert(7)
t.insert(3)
t.insert(6)
t.insert(2)
t.insert(5)
t.inordertraversal()

Video streaming over websockets using JavaScript

To answer the question:

What is the fastest way to stream live video using JavaScript? Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?

Yes, Websocket can be used to transmit over 30 fps and even 60 fps.

The main issue with Websocket is that it is low-level and you have to deal with may other issues than just transmitting video chunks. All in all it's a great transport for video and also audio.

jquery ui Dialog: cannot call methods on dialog prior to initialization

If you cannot upgrade jQuery and you are getting:

Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

You can work around it like so:

$(selector).closest('.ui-dialog-content').dialog('close');

Or if you control the view and know no other dialogs should be in use at all on the entire page, you could do:

$('.ui-dialog-content').dialog('close');

I would only recommend doing this if using closest causes a performance issue. There are likely other ways to work around it without doing a global close on all dialogs.

jQuery selector for id starts with specific text

Use jquery starts with attribute selector

$('[id^=editDialog]')

Alternative solution - 1 (highly recommended)

A cleaner solution is to add a common class to each of the divs & use

$('.commonClass').

But you can use the first one if html markup is not in your hands & cannot change it for some reason.

Alternative solution - 2 (not recommended if n is a large number) (as per @Mihai Stancu's suggestion)

$('#editDialog-0, #editDialog-1, #editDialog-2,...,#editDialog-n')

Note: If there are 2 or 3 selectors and if the list doesn't change, this is probably a viable solution but it is not extensible because we have to update the selectors when there is a new ID in town.

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

please add these codes to your dependencies. It will work.

implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    implementation 'com.android.support:appcompat-v7:23.1.0'
    implementation 'com.android.support:design:23.1.0'
    implementation 'com.android.support:cardview-v7:23.1.0'
    implementation 'com.android.support:recyclerview-v7:23.1.0'

    implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}

Select folder dialog WPF

If you don't want to use Windows Forms nor edit manifest files, I came up with a very simple hack using WPF's SaveAs dialog for actually selecting a directory.

No using directive needed, you may simply copy-paste the code below !

It should still be very user-friendly and most people will never notice.

The idea comes from the fact that we can change the title of that dialog, hide files, and work around the resulting filename quite easily.

It is a big hack for sure, but maybe it will do the job just fine for your usage...

In this example I have a textbox object to contain the resulting path, but you may remove the related lines and use a return value if you wish...

// Create a "Save As" dialog for selecting a directory (HACK)
var dialog = new Microsoft.Win32.SaveFileDialog();
dialog.InitialDirectory = textbox.Text; // Use current value for initial dir
dialog.Title = "Select a Directory"; // instead of default "Save As"
dialog.Filter = "Directory|*.this.directory"; // Prevents displaying files
dialog.FileName = "select"; // Filename will then be "select.this.directory"
if (dialog.ShowDialog() == true) {
    string path = dialog.FileName;
    // Remove fake filename from resulting path
    path = path.Replace("\\select.this.directory", "");
    path = path.Replace(".this.directory", "");
    // If user has changed the filename, create the new directory
    if (!System.IO.Directory.Exists(path)) {
        System.IO.Directory.CreateDirectory(path);
    }
    // Our final value is in path
    textbox.Text = path;
}

The only issues with this hack are :

  • Acknowledge button still says "Save" instead of something like "Select directory", but in a case like mines I "Save" the directory selection so it still works...
  • Input field still says "File name" instead of "Directory name", but we can say that a directory is a type of file...
  • There is still a "Save as type" dropdown, but its value says "Directory (*.this.directory)", and the user cannot change it for something else, works for me...

Most people won't notice these, although I would definitely prefer using an official WPF way if microsoft would get their heads out of their asses, but until they do, that's my temporary fix.

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

In the build.gradle file for your app module, add this to the defaultConfig section (under the android section). This will write out the schema to a schemas subfolder of your project folder.

javaCompileOptions {
    annotationProcessorOptions {
        arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
    }
}

Like this:

// ...

android {
    
    // ... (compileSdkVersion, buildToolsVersion, etc)

    defaultConfig {

        // ... (applicationId, miSdkVersion, etc)
        
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }
   
    // ... (buildTypes, compileOptions, etc)

}

// ...

How can I remove file extension from a website address?

Just add an .htaccess file to the root folder of your site (for example, /home/domains/domain.com/htdocs/) with the following content:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

More about how this works in these pages: mod_rewrite guide (introduction, using it), reference documentation

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

if you have mount points add the the SQL server service account to volume security accordingly

Auto-fit TextView for Android

Convert the text view to an image, and the scale the image within the boundaries.

Here's an example on how to convert a view to an Image: Converting a view to Bitmap without displaying it in Android?

The problem is, your text will not be selectable, but it should do the trick. I haven't tried it, so I'm not sure how it would look (because of the scaling).

Insert some string into given string at given index in Python

An important point that often bites new Python programmers but the other posters haven't made explicit is that strings in Python are immutable -- you can't ever modify them in place.

You need to retrain yourself when working with strings in Python so that instead of thinking, "How can I modify this string?" instead you're thinking "how can I create a new string that has some pieces from this one I've already gotten?"

How to Update Date and Time of Raspberry Pi With out Internet

You will need to configure your Win7 PC as a Time Server, and then configure the RasPi to connect to it for NTP services.

Configure Win7 as authoritative time server. Configure RasPi time server lookup.

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

Try this

Change the order of files it should be like below..

<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/wow.min.js"></script>

C++ code file extension? .cc vs .cpp

As with most style conventions, there are only two things that matter:

  1. Be consistent in what you use, wherever possible.
  2. Don't design anything that depends on a specific choice being used.

Those may seem to contradict, but they each have value for their own reasons.

Property 'value' does not exist on type 'EventTarget'

Angular 10+

Open tsconfig.json and disable strictDomEventTypes.

  "angularCompilerOptions": {
    ....
    ........
    "strictDomEventTypes": false
  }

How to remove non-alphanumeric characters?

preg_replace("/\W+/", '', $string)

You can test it here : http://regexr.com/

If input value is blank, assign a value of "empty" with Javascript

I'm guessing this is what you want...

When the form is submitted, check if the value is empty and if so, send a value = empty.

If so, you could do the following with jQuery.

$('form').submit(function(){
    var input = $('#test').val();
    if(input == ''){
         $('#test').val('empty');
    }    
});

HTML

<form> 
    <input id="test" type="text" />
</form>

http://jsfiddle.net/jasongennaro/NS6Ca/

Click your cursor in the box and then hit enter to see the form submit the value.

In which conda environment is Jupyter executing?

Because none of the answers above worked for me, I write here the solution that finally solved my problem on Ubuntu. My problem was:
I did the following steps:

  1. Activate my environment: conda activate MyEnv
  2. Start jupyter notebook:jupyter notebook

Although MyEnv was active in the terminal and had an asterix when writing conda env list, but jupyter notebook was started with the base environment. Installing nb_conda and ipykernel didn't solve the problem for me either. Additionally, the conda tab wasn't appearing in jupyter notebook and also clicking on the kernels or going to the menu Kernel->Change Kernel didn't show the kernel MyEnv.
Solution was: install the jupyter_environment_kernel in MyEnv environment:

pip install environment_kernels

After that when starting jupyter notebook, it is started with the right environment. You can also switch between environments without stopping the kernel, by going to the menu Kernel->Change Kernel and selecting the desired kernel.

Creating an empty bitmap and drawing though canvas in Android

Do not use Bitmap.Config.ARGB_8888

Instead use int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_4444; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

ARGB_8888 can land you in OutOfMemory issues when dealing with more bitmaps or large bitmaps. Or better yet, try avoiding usage of ARGB option itself.

SQL Format as of Round off removing decimals

check the round function and how does the length argument works. It controls the behaviour of the precision of the result

Difference between Inheritance and Composition

Inheritance brings out IS-A relation. Composition brings out HAS-A relation. Strategy pattern explain that Composition should be used in cases where there are families of algorithms defining a particular behaviour.
Classic example being of a duck class which implements a flying behaviour.

public interface Flyable{
 public void fly();
}

public class Duck {
 Flyable fly;

 public Duck(){
  fly = new BackwardFlying();
 }
}

Thus we can have multiple classes which implement flying eg:

public class BackwardFlying implements Flyable{
  public void fly(){
    Systemout.println("Flies backward ");
  }
}
public class FastFlying implements Flyable{
  public void fly(){
    Systemout.println("Flies 100 miles/sec");
  }
}

Had it been for inheritance, we would have two different classes of birds which implement the fly function over and over again. So inheritance and composition are completely different.

How many characters in varchar(max)

See the MSDN reference table for maximum numbers/sizes.

Bytes per varchar(max), varbinary(max), xml, text, or image column: 2^31-1

There's a two-byte overhead for the column, so the actual data is 2^31-3 max bytes in length. Assuming you're using a single-byte character encoding, that's 2^31-3 characters total. (If you're using a character encoding that uses more than one byte per character, divide by the total number of bytes per character. If you're using a variable-length character encoding, all bets are off.)

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

For JDBC based project (directly or indirectly, e.g. JPA, EJB, ...) you can mockup not the entire database (in such case it would be better to use a test db on a real RDBMS), but only mockup at JDBC level.

Advantage is abstraction which comes with that way, as JDBC data (result set, update count, warning, ...) are the same whatever is the backend: your prod db, a test db, or just some mockup data provided for each test case.

With JDBC connection mocked up for each case there is no need to manage test db (cleanup, only one test at time, reload fixtures, ...). Every mockup connection is isolated and there is no need to clean up. Only minimal required fixtures are provided in each test case to mock up JDBC exchange, which help to avoid complexity of managing a whole test db.

Acolyte is my framework which includes a JDBC driver and utility for this kind of mockup: http://acolyte.eu.org .

Converting A String To Hexadecimal In Java

Convert a letter in hex code and hex code in letter.

        String letter = "a";
    String code;
    int decimal;

    code = Integer.toHexString(letter.charAt(0));
    decimal = Integer.parseInt(code, 16);

    System.out.println("Hex code to " + letter + " = " + code);
    System.out.println("Char to " + code + " = " + (char) decimal);

Virtualbox shared folder permissions

Try this (on the guest machine. i.e. the OS running in the Virtual box):

sudo adduser your-user vboxsf

Now reboot the OS running in the virtual box.

How to make a dropdown readonly using jquery?

To simplify things here's a jQuery plugin that does that without the hassle: https://github.com/haggen/readonly

Setting timezone in Python

>>> import os, time
>>> time.strftime('%X %x %Z')
'12:45:20 08/19/09 CDT'
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'18:45:39 08/19/09 BST'

To get the specific values you've listed:

>>> year = time.strftime('%Y')
>>> month = time.strftime('%m')
>>> day = time.strftime('%d')
>>> hour = time.strftime('%H')
>>> minute = time.strftime('%M')

See here for a complete list of directives. Keep in mind that the strftime() function will always return a string, not an integer or other type.

Increase distance between text and title on the y-axis

Based on this forum post: https://groups.google.com/forum/#!topic/ggplot2/mK9DR3dKIBU

Sounds like the easiest thing to do is to add a line break (\n) before your x axis, and after your y axis labels. Seems a lot easier (although dumber) than the solutions posted above.

ggplot(mpg, aes(cty, hwy)) + 
    geom_point() + 
    xlab("\nYour_x_Label") + ylab("Your_y_Label\n")

Hope that helps!

SQL Server after update trigger

CREATE TRIGGER [dbo].[after_update] ON [dbo].[MYTABLE]
AFTER UPDATE
AS
BEGIN
    DECLARE @ID INT

    SELECT @ID = D.ID
    FROM inserted D

    UPDATE MYTABLE
    SET mytable.CHANGED_ON = GETDATE()
        ,CHANGED_BY = USER_NAME(USER_ID())
    WHERE ID = @ID
END

How do you declare an interface in C++?

You can also consider contract classes implemented with the NVI (Non Virtual Interface Pattern). For instance:

struct Contract1 : boost::noncopyable
{
    virtual ~Contract1();
    void f(Parameters p) {
        assert(checkFPreconditions(p)&&"Contract1::f, pre-condition failure");
        // + class invariants.
        do_f(p);
        // Check post-conditions + class invariants.
    }
private:
    virtual void do_f(Parameters p) = 0;
};
...
class Concrete : public Contract1, public Contract2
{
private:
    virtual void do_f(Parameters p); // From contract 1.
    virtual void do_g(Parameters p); // From contract 2.
};

How to write to a CSV line by line?

What about this:

with open("your_csv_file.csv", "w") as f:
    f.write("\n".join(text))

str.join() Return a string which is the concatenation of the strings in iterable. The separator between elements is the string providing this method.

Batch Renaming of Files in a Directory

I have this to simply rename all files in subfolders of folder

import os

def replace(fpath, old_str, new_str):
    for path, subdirs, files in os.walk(fpath):
        for name in files:
            if(old_str.lower() in name.lower()):
                os.rename(os.path.join(path,name), os.path.join(path,
                                            name.lower().replace(old_str,new_str)))

I am replacing all occurences of old_str with any case by new_str.

Embedding DLLs in a compiled executable

The following method DO NOT use external tools and AUTOMATICALLY include all needed DLL (no manual action required, everything done at compilation)

I read a lot of answer here saying to use ILMerge, ILRepack or Jeffrey Ritcher method but none of that worked with WPF applications nor was easy to use.

When you have a lot of DLL it can be hard to manually include the one you need in your exe. The best method i found was explained by Wegged here on StackOverflow

Copy pasted his answer here for clarity (all credit to Wegged)


1) Add this to your .csproj file:

<Target Name="AfterResolveReferences">
  <ItemGroup>
    <EmbeddedResource Include="@(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'">
      <LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
    </EmbeddedResource>
  </ItemGroup>
</Target>

2) Make your Main Program.cs look like this:

[STAThreadAttribute]
public static void Main()
{
    AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
    App.Main();
}

3) Add the OnResolveAssembly method:

private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
    Assembly executingAssembly = Assembly.GetExecutingAssembly();
    AssemblyName assemblyName = new AssemblyName(args.Name);

    var path = assemblyName.Name + ".dll";
    if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false) path = String.Format(@"{0}\{1}", assemblyName.CultureInfo, path);

    using (Stream stream = executingAssembly.GetManifestResourceStream(path))
    {
        if (stream == null) return null;

        var assemblyRawBytes = new byte[stream.Length];
        stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
        return Assembly.Load(assemblyRawBytes);
    }
}

how to write value into cell with vba code without auto type conversion?

This is probably too late, but I had a similar problem with dates that I wanted entered into cells from a text variable. Inevitably, it converted my variable text value to a date. What I finally had to do was concatentate a ' to the string variable and then put it in the cell like this:

prvt_rng_WrkSht.Cells(prvt_rng_WrkSht.Rows.Count, cnst_int_Col_Start_Date).Formula = "'" & _ 
    param_cls_shift.Start_Date (string property of my class) 

Rounding to 2 decimal places in SQL

Try this...

SELECT TO_CHAR(column_name,'99G999D99MI')
as format_column
FROM DUAL;

To show a new Form on click of a button in C#

Try this:

private void Button1_Click(Object sender, EventArgs e ) 
{
   var myForm = new Form1();
   myForm.Show();
}

What is the difference between persist() and merge() in JPA and Hibernate?

Persist should be called only on new entities, while merge is meant to reattach detached entities.

If you're using the assigned generator, using merge instead of persist can cause a redundant SQL statement.

Also, calling merge for managed entities is also a mistake since managed entities are automatically managed by Hibernate, and their state is synchronized with the database record by the dirty checking mechanism upon flushing the Persistence Context.

Issue with background color and Google Chrome

I had the same issue on a couple of sites and fixed it by moving the background styling from body to html (which I guess is a variation of the body {} to html, body{} technique already mentioned but shows that you can make do with the style on html only), e.g.

body {
   background-color:#000000;
   background-image:url('images/bg.png');
   background-repeat:repeat-x;
   font-family:Arial,Helvetica,sans-serif;
   font-size:85%;
   color:#cccccc;

}

becomes

html {
   background-color:#000000;
   background-image:url('images/bg.png');
   background-repeat:repeat-x;
}
body {
   font-family:Arial,Helvetica,sans-serif;
   font-size:85%;
   color:#cccccc;
}

This worked in IE6-8, Chrome 4-5, Safari 4, Opera 10 and Firefox 3.x with no obvious nasty side-effects.

How to access accelerometer/gyroscope data from Javascript?

Can't add a comment to the excellent explanation in the other post but wanted to mention that a great documentation source can be found here.

It is enough to register an event function for accelerometer like so:

if(window.DeviceMotionEvent){
  window.addEventListener("devicemotion", motion, false);
}else{
  console.log("DeviceMotionEvent is not supported");
}

with the handler:

function motion(event){
  console.log("Accelerometer: "
    + event.accelerationIncludingGravity.x + ", "
    + event.accelerationIncludingGravity.y + ", "
    + event.accelerationIncludingGravity.z
  );
}

And for magnetometer a following event handler has to be registered:

if(window.DeviceOrientationEvent){
  window.addEventListener("deviceorientation", orientation, false);
}else{
  console.log("DeviceOrientationEvent is not supported");
}

with a handler:

function orientation(event){
  console.log("Magnetometer: "
    + event.alpha + ", "
    + event.beta + ", "
    + event.gamma
  );
}

There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).

There is a simple working code on GitHub

Return date as ddmmyyyy in SQL Server

select replace(convert(VARCHAR,getdate(),103),'/','')

select right(convert(VARCHAR,getdate(),112),2) + 
       substring(convert(VARCHAR,getdate(),112),5,2) + 
       left(convert(VARCHAR,getdate(),112),4)

How can I get the DateTime for the start of the week?

Using Fluent DateTime:

var monday = DateTime.Now.Previous(DayOfWeek.Monday);
var sunday = DateTime.Now.Previous(DayOfWeek.Sunday);

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

Enable cross-origin requests in ASP.NET Web API click for more info

Enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

Install-Package Microsoft.AspNet.WebApi.Cors

This command installs the latest package and updates all dependencies, including the core Web API libraries. Use the -Version flag to target a specific version. The CORS package requires Web API 2.0 or later.

Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Next, add the [EnableCors] attribute to your controller/ controller methods

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

Enable Cross-Origin Requests (CORS) in ASP.NET Core

How can I use JQuery to post JSON data?

You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.

If you pass the data as a string, it won't be serialized:

$.ajax({
    type: 'POST',
    url: '/form/',
    data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'
});

C++ IDE for Macs

Xcode is free and good, which is lucky because it's pretty much the only option on the Mac.

Detecting an undefined object property

Review

A lot of the given answers give a wrong result because they do not distinguish between the case when an object property does not exist and the case when a property has value undefined. Here is proof for most popular solutions:

_x000D_
_x000D_
let obj = {
  a: 666,
  u: undefined // The 'u' property has value 'undefined'
               // The 'x' property does not exist
}

console.log('>>> good results:');
console.log('A', "u" in obj, "x" in obj);
console.log('B', obj.hasOwnProperty("u"),      obj.hasOwnProperty("x"));

console.log('\n>>> bad results:');
console.log('C', obj.u === undefined,          obj.x === undefined);
console.log('D', obj.u == undefined,           obj.x == undefined);
console.log('E', obj["u"] === undefined,       obj["x"] === undefined);
console.log('F', obj["u"] == undefined,        obj["x"] == undefined);
console.log('G', !obj.u,                      !obj.x);
console.log('H', typeof obj.u === 'undefined', typeof obj.x === 'undefined');
_x000D_
_x000D_
_x000D_

How do I create a nice-looking DMG for Mac OS X using command-line tools?

.DS_Store files stores windows settings in Mac. Windows settings include the icons layout, the window background, the size of the window, etc. The .DS_Store file is needed in creating the window for mounted images to preserve the arrangement of files and the windows background.

Once you have .DS_Store file created, you can just copy it to your created installer (DMG).

How to check if an array is empty?

Your problem is that you are NOT testing the length of the array until it is too late.

But I just want to point out that the way to solve this problem is to READ THE STACK TRACE.

The exception message will clearly tell you are trying to create an array with length -1, and the trace will tell you exactly which line of your code is doing this. The rest is simple logic ... working back to why the length you are using is -1.

How to plot two histograms together in R?

So many great answers but since I've just written a function (plotMultipleHistograms() in 'basicPlotteR' package) function to do this, I thought I would add another answer.

The advantage of this function is that it automatically sets appropriate X and Y axis limits and defines a common set of bins that it uses across all the distributions.

Here's how to use it:

# Install the plotteR package
install.packages("devtools")
devtools::install_github("JosephCrispell/basicPlotteR")
library(basicPlotteR)

# Set the seed
set.seed(254534)

# Create random samples from a normal distribution
distributions <- list(rnorm(500, mean=5, sd=0.5), 
                      rnorm(500, mean=8, sd=5), 
                      rnorm(500, mean=20, sd=2))

# Plot overlapping histograms
plotMultipleHistograms(distributions, nBins=20, 
                       colours=c(rgb(1,0,0, 0.5), rgb(0,0,1, 0.5), rgb(0,1,0, 0.5)), 
                       las=1, main="Samples from normal distribution", xlab="Value")

enter image description here

The plotMultipleHistograms() function can take any number of distributions, and all the general plotting parameters should work with it (for example: las, main, etc.).

How to disable scrolling the document body?

with css

body,html{
  overflow:hidden
}

How to loop through an array of objects in swift

The photos property is an optional array and must be unwrapped before accessing its elements (the same as you do to get the count property of the array):

for var i = 0; i < userPhotos!.count ; ++i {
    let url = userPhotos![i].url
}

batch file to check 64bit or 32bit OS

Seems to work if you do only these:

echo "%PROCESSOR_ARCHITECTURE%"

I've found these script which will do specific stuff depending of OS Architecture (x64 or x86):

@echo off
echo Detecting OS processor type

if "%PROCESSOR_ARCHITECTURE%"=="AMD64" goto 64BIT
echo 32-bit OS
\\savdaldpm01\ProtectionAgents\RA\3.0.7558.0\i386\DPMAgentInstaller_x86 /q
goto END
:64BIT
echo 64-bit OS
\\savdaldpm01\ProtectionAgents\RA\3.0.7558.0\amd64\DPMAgentInstaller_x64 /q
:END

"C:\Program Files\Microsoft Data Protection Manager\DPM\bin\setdpmserver.exe" -dpmservername sa

Try to find a way without GOTO please...

For people whom work with Unix systems, uname -m will do the trick.

How to check if a number is between two values?

It's an old question, however might be useful for someone like me.

lodash has _.inRange() function https://lodash.com/docs/4.17.4#inRange

Example:

_.inRange(3, 2, 4);
// => true

Please note that this method utilizes the Lodash utility library, and requires access to an installed version of Lodash.

Hide keyboard in react-native

We can use keyboard and tochablewithoutfeedback from react-native

const DismissKeyboard = ({ children }) => (
  <TouchableWithoutFeedback
    onPress={() => Keyboard.dismiss()}
  >
    {children}
  </TouchableWithoutFeedback>
);

And use it in this way:

const App = () => (
  <DismissKeyboard>
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="username"
        keyboardType="numeric"
      />
      <TextInput
        style={styles.input}
        placeholder="password"
      />
    </View>
  </DismissKeyboard>
);

I also explained here with source code.

convert string to char*

There are many ways. Here are at least five:

/*
 * An example of converting std::string to (const)char* using five
 * different methods. Error checking is emitted for simplicity.
 *
 * Compile and run example (using gcc on Unix-like systems):
 *
 *  $ g++ -Wall -pedantic -o test ./test.cpp
 *  $ ./test
 *  Original string (0x7fe3294039f8): hello
 *  s1 (0x7fe3294039f8): hello
 *  s2 (0x7fff5dce3a10): hello
 *  s3 (0x7fe3294000e0): hello
 *  s4 (0x7fe329403a00): hello
 *  s5 (0x7fe329403a10): hello
 */

#include <alloca.h>
#include <string>
#include <cstring>

int main()
{
    std::string s0;
    const char *s1;
    char *s2;
    char *s3;
    char *s4;
    char *s5;

    // This is the initial C++ string.
    s0 = "hello";

    // Method #1: Just use "c_str()" method to obtain a pointer to a
    // null-terminated C string stored in std::string object.
    // Be careful though because when `s0` goes out of scope, s1 points
    // to a non-valid memory.
    s1 = s0.c_str();

    // Method #2: Allocate memory on stack and copy the contents of the
    // original string. Keep in mind that once a current function returns,
    // the memory is invalidated.
    s2 = (char *)alloca(s0.size() + 1);
    memcpy(s2, s0.c_str(), s0.size() + 1);

    // Method #3: Allocate memory dynamically and copy the content of the
    // original string. The memory will be valid until you explicitly
    // release it using "free". Forgetting to release it results in memory
    // leak.
    s3 = (char *)malloc(s0.size() + 1);
    memcpy(s3, s0.c_str(), s0.size() + 1);

    // Method #4: Same as method #3, but using C++ new/delete operators.
    s4 = new char[s0.size() + 1];
    memcpy(s4, s0.c_str(), s0.size() + 1);

    // Method #5: Same as 3 but a bit less efficient..
    s5 = strdup(s0.c_str());

    // Print those strings.
    printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
    printf("s1 (%p): %s\n", s1, s1);
    printf("s2 (%p): %s\n", s2, s2);
    printf("s3 (%p): %s\n", s3, s3);
    printf("s4 (%p): %s\n", s4, s4);
    printf("s5 (%p): %s\n", s5, s5);

    // Release memory...
    free(s3);
    delete [] s4;
    free(s5);
}

c++ array assignment of multiple values

const static int newvals[] = {34,2,4,5,6};

std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);

Adding event listeners to dynamically added elements using jQuery

Using .on() you can define your function once, and it will execute for any dynamically added elements.

for example

$('#staticDiv').on('click', 'yourSelector', function() {
  //do something
});

How to establish ssh key pair when "Host key verification failed"

Its means your remote host key was changed (May be host password change),

Your terminal suggested to execute this command as root user

$ ssh-keygen -f "/root/.ssh/known_hosts" -R [www.website.net]:4231

You have to remove that host name from hosts list on your pc/server. Copy that suggested command and execute as a root user.

$ sudo su                                                            // Login as a root user

$ ssh-keygen -f "/root/.ssh/known_hosts" -R [www.website.net]:4231   // Terminal suggested command execute here
Host [www.website.net]:4231 found: line 16 type ECDSA
/root/.ssh/known_hosts updated.
Original contents retained as /root/.ssh/known_hosts.old

$ exit                                                               // Exist from root user

$ sudo ssh [email protected] -p 4231                              // Try again

I Hope this works.

Why maven? What are the benefits?

I've never come across point 2? Can you explain why you think this affects deployment in any way. If anything maven allows you to structure your projects in a modularised way that actually allows hot fixes for bugs in a particular tier, and allows independent development of an API from the remainder of the project for example.

It is possible that you are trying to cram everything into a single module, in which case the problem isn't really maven at all, but the way you are using it.

SVN Repository on Google Drive or DropBox

For free private SVN hosting try the following:

Or use BitBucket for free private git/mercurial repositories

How can I get a side-by-side diff when I do "git diff"?

ydiff

Formerly called cdiff, this tool can display side by side, incremental, and colorful diff.

Instead of doing git diff, do:

ydiff -s -w0

This will launch ydiff in side-by-side display mode for each of the files with differences.

Install with:

python3 -m pip install --user ydiff

-or-

brew install ydiff

For git log, you can use:

ydiff -ls -w0

-w0 auto-detects your terminal width. See the ydiff GitHub repository page for detail and demo.

Tested in Git 2.18.0, ydiff 1.1.

Angular2 set value for formGroup

Yes you can use setValue to set value for edit/update purpose.

this.personalform.setValue({
      name: items.name,
      address: {
        city: items.address.city,
        country: items.address.country
      }
    });

You can refer http://musttoknow.com/use-angular-reactive-form-addinsert-update-data-using-setvalue-setpatch/ to understand how to use Reactive forms for add/edit feature by using setValue. It saved my time

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

Restart MySQL, it works fine.

BUT beware that if such a query is stuck, there is a problem somewhere :

  • in your query (misplaced char, cartesian product, ...)
  • very numerous records to edit
  • complex joins or tests (MD5, substrings, LIKE %...%, etc.)
  • data structure problem
  • foreign key model (chain/loop locking)
  • misindexed data

As @syedrakib said, it works but this is no long-living solution for production.

Beware : doing the restart can affect your data with inconsistent state.

Also, you can check how MySQL handles your query with the EXPLAIN keyword and see if something is possible there to speed up the query (indexes, complex tests,...).

Access PHP variable in JavaScript

metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>

how to move elasticsearch data from one server to another

You can use snapshot/restore feature available in Elasticsearch for this. Once you have setup a Filesystem based snapshot store, you can move it around between clusters and restore on a different cluster

How can I get the current stack trace in Java?

Silly me, it's Thread.currentThread().getStackTrace();

What is the correct way to do a CSS Wrapper?

You don't need a wrapper, just use the body as the wrapper.

CSS:

body {
    margin:0 auto;
    width:200px;
}

HTML:

<body>
    <p>some content</p>
<body>

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

Is it possible to install another version of Python to Virtualenv?

I'm using virtualenvwrapper and don't want to modify $PATH, here's how:

$ which python3
/usr/local/bin/python3

$ mkvirtualenv --python=/usr/local/bin/python3 env_name

How to resolve this System.IO.FileNotFoundException

I came across a similar situation after publishing a ClickOnce application, and one of my colleagues on a different domain reported that it fails to launch.

To find out what was going on, I added a try catch statement inside the MainWindow method as @BradleyDotNET mentioned in one comment on the original post, and then published again.

public MainWindow()
{
    try
    {
        InitializeComponent();
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.ToString());
    }
}

Then my colleague reported to me the exception detail, and it was a missing reference of a third party framework dll file.

Added the reference and problem solved.

Binding to static property

These answers are all good if you want to follow good conventions but the OP wanted something simple, which is what I wanted too instead of dealing with GUI design patterns. If all you want to do is have a string in a basic GUI app you can update ad-hoc without anything fancy, you can just access it directly in your C# source.

Let's say you've got a really basic WPF app MainWindow XAML like this,

<Window x:Class="MyWPFApp.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:MyWPFApp"
            mc:Ignorable="d"
            Title="MainWindow"
            Height="200"
            Width="400"
            Background="White" >
    <Grid>
        <TextBlock x:Name="textBlock"                   
                       Text=".."
                       HorizontalAlignment="Center"
                       VerticalAlignment="Top"
                       FontWeight="Bold"
                       FontFamily="Helvetica"
                       FontSize="16"
                       Foreground="Blue" Margin="0,10,0,0"
             />
        <Button x:Name="Find_Kilroy"
                    Content="Poke Kilroy"
                    Click="Button_Click_Poke_Kilroy"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    FontFamily="Helvetica"
                    FontWeight="Bold"
                    FontSize="14"
                    Width="280"
            />
    </Grid>
</Window>

That will look something like this:

enter image description here

In your MainWindow XAML's source, you could have something like this where all we're doing in changing the value directly via textBlock.Text's get/set functionality:

using System.Windows;

namespace MyWPFApp
{
    public partial class MainWindow : Window
    {
        public MainWindow() { InitializeComponent(); }

        private void Button_Click_Poke_Kilroy(object sender, RoutedEventArgs e)
        {
            textBlock.Text = "              \\|||/\r\n" +
                             "              (o o) \r\n" +
                             "----ooO- (_) -Ooo----";
        }
    }
}

Then when you trigger that click event by clicking the button, voila! Kilroy appears :)

enter image description here

Redirecting to a new page after successful login

First of all, move all your PHP code to the top. Without it, my code below wont work.

To do the redirect, use:

header('Location: http://www.example.com/');

Also, please consider my advice. Since it's not the first question today and all your questions are related to basics, you should consider reading some good PHP book to understand how things work.

Here you can find useful links to free books: https://stackoverflow.com/tags/php/info

Convert datetime to Unix timestamp and convert it back in python

If you want to convert a python datetime to seconds since epoch you should do it explicitly:

>>> import datetime
>>> datetime.datetime(2012, 04, 01, 0, 0).strftime('%s')
'1333234800'
>>> (datetime.datetime(2012, 04, 01, 0, 0) - datetime.datetime(1970, 1, 1)).total_seconds()
1333238400.0

In Python 3.3+ you can use timestamp() instead:

>>> import datetime
>>> datetime.datetime(2012, 4, 1, 0, 0).timestamp()
1333234800.0

How do I check if an HTML element is empty using jQuery?

White space and line breaks are the main issues with using :empty selector. Careful, in CSS the :empty pseudo class behaves the same way. I like this method:

if ($someElement.children().length == 0){
     someAction();
}

Why does the JFrame setSize() method not set the size correctly?

I know that this question is about 6+ years old, but the answer by @Kyle doesn't work.

Using this

setSize(width - (getInsets().left + getInsets().right), height - (getInsets().top + getInsets().bottom));

But this always work in any size:

setSize(width + 14, height + 7);

If you don't want the border to border, and only want the white area, here:

setSize(width + 16, height + 39);

Also this only works on Windows 10, for MacOS users, use @ben's answer.

What is private bytes, virtual bytes, working set?

You should not try to use perfmon, task manager or any tool like that to determine memory leaks. They are good for identifying trends, but not much else. The numbers they report in absolute terms are too vague and aggregated to be useful for a specific task such as memory leak detection.

A previous reply to this question has given a great explanation of what the various types are.

You ask about a tool recommendation: I recommend Memory Validator. Capable of monitoring applications that make billions of memory allocations.

http://www.softwareverify.com/cpp/memory/index.html

Disclaimer: I designed Memory Validator.

Select rows where column is null

select * from tableName where columnName is null

Basic text editor in command prompt?

In a pinch, just type 'notepad (filename)' and notepad will pop up with the file you want to edit in it. Otherwise Vim or some such will have to be installed.

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

You can do like this:

    TimeZone tz = TimeZone.getDefault();
    int offset = tz.getRawOffset();

    String timeZone = String.format("%s%02d%02d", offset >= 0 ? "+" : "-", offset / 3600000, (offset / 60000) % 60);

ERROR 1064 (42000): You have an error in your SQL syntax;

Use varchar instead of VAR_CHAR and omit the comma in the last line i.e.phone INT NOT NULL );. The last line during creating table is kept "comma free". Ex:- CREATE TABLE COMPUTER ( Model varchar(50) ); Here, since we have only one column ,that's why there is no comma used during entire code.

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and Java 8 you could do

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);

Update: For pre 26 use Joda time

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);

In app/build.gradle file, add like this-

dependencies {    
    compile 'joda-time:joda-time:2.9.4'
}

How to store phone numbers on MySQL databases?

Form my point of view, below is my suggestions:

  1. Store phone number into a single field as varchar and if you need to split then after retrieve split accordingly.
  2. If you store as number then preceding 0 will truncate, so always store as varchar
  3. Validate users phone number before inserting into your table.

How to pass a view's onClick event to its parent on Android?

Declare your TextView not clickable / focusable by using android:clickable="false" and android:focusable="false" or v.setClickable(false) and v.setFocusable(false). The click events should be dispatched to the TextView's parent now.

Note:

In order to achieve this, you have to add click to its direct parent. or set android:clickable="false" and android:focusable="false" to its direct parent to pass listener to further parent.

Best way to parse command line arguments in C#?

Genghis Command Line Parser may be a little out of date, but it is very feature complete and works pretty well for me.

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

    Set-ExecutionPolicy RemoteSigned
    
  2. Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

C:\Users\MacEwin\Desktop>python helloworld.py
Hello World

get jquery `$(this)` id

Do you mean that for a select element with an id of "next" you need to perform some specific script?

$("#next").change(function(){
    //enter code here
});

How do I conditionally apply CSS styles in AngularJS?

This solution did the trick for me

<a ng-style="{true: {paddingLeft: '25px'}, false: {}}[deleteTriggered]">...</a>

how to add a day to a date using jquery datepicker

This answer really helped me get started (noob) - but I encountered some weird behavior when I set a start date of 12/31/2014 and added +1 to default the end date. Instead of giving me an end date of 01/01/2015 I was getting 02/01/2015 (!!!). This version parses the components of the start date to avoid these end of year oddities.


 $( "#date_start" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
         $("#date_end").datepicker("option","minDate", selected); //  mindate on the End datepicker cannot be less than start date already selected.
         var date = $(this).datepicker('getDate');
         var tempStartDate = new Date(date);
         var default_end = new Date(tempStartDate.getFullYear(), tempStartDate.getMonth(), tempStartDate.getDate()+1); //this parses date to overcome new year date weirdness
         $('#date_end').datepicker('setDate', default_end); // Set as default                           
   }

 });

 $( "#date_end" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
     $("#date_start").datepicker("option","maxDate", selected); //  maxdate on the Start datepicker cannot be more than end date selected.

  }

});

How do I test which class an object is in Objective-C?

You can also check run time. Put one breakpoint in code and inside (lldb) console write

(lldb) po [yourObject class]

Like this..

enter image description here

How to build a 'release' APK in Android Studio?

Follow this steps:

-Build
-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

What are the options for (keyup) in Angular2?

Have hit the same problem today.

These are poorly documented, an open issue exist.

Some for keyup, like space:

<input (keyup.space)="doSomething()">
<input (keyup.spacebar)="doSomething()">  

Some for keydown
(may work for keyup too):

<input (keydown.enter)="...">
<input (keydown.a)="...">
<input (keydown.esc)="...">
<input (keydown.alt)="...">
<input (keydown.shift.esc)="...">
<input (keydown.shift.arrowdown)="...">
<input (keydown.f4)="...">

All above are from below links:

https://github.com/angular/angular/issues/18870
https://github.com/angular/angular/issues/8273
https://github.com/angular/angular/blob/master/packages/platform-browser/src/dom/events/key_events.ts
https://alligator.io/angular/binding-keyup-keydown-events/

Killing a process created with Python's subprocess.Popen()

In your code it should be

proc1.kill()

Both kill or terminate are methods of the Popen object which sends the signal signal.SIGKILL to the process.

What does the "no version information available" error from linux dynamic linker mean?

How are you compiling your app? What compiler flags?

In my experience, when targeting the vast realm of Linux systems out there, build your packages on the oldest version you are willing to support, and because more systems tend to be backwards compatible, your app will continue to work. Actually this is the whole reason for library versioning - ensuring backward compatibility.

How to cherry-pick multiple commits

You can use a serial combination of git rebase and git branch to apply a group of commits onto another branch. As already posted by wolfc the first command actually copies the commits. However, the change is not visible until you add a branch name to the top most commit of the group.

Please open the picture in a new tab ...

Workflow

To summarize the commands in text form:

  1. Open gitk as a independent process using the command: gitk --all &.
  2. Run git rebase --onto a b f.
  3. Press F5 in gitk. Nothing changes. But no HEAD is marked.
  4. Run git branch selection
  5. Press F5 in gitk. The new branch with its commits appears.

This should clarify things:

  • Commit a is the new root destination of the group.
  • Commit b is the commit before the first commit of the group (exclusive).
  • Commit f is the last commit of the group (inclusive).

Afterwards, you could use git checkout feature && git reset --hard b to delete the commits c till f from the feature branch.

In addition to this answer, I wrote a blog post which describes the commands in another scenario which should help to generally use it.

Does file_get_contents() have a timeout setting?

It is worth noting that if changing default_socket_timeout on the fly, it might be useful to restore its value after your file_get_contents call:

$default_socket_timeout = ini_get('default_socket_timeout');
....
ini_set('default_socket_timeout', 10);
file_get_contents($url);
...
ini_set('default_socket_timeout', $default_socket_timeout);

Unable to allocate array with shape and data type

I came across this problem on Windows too. The solution for me was to switch from a 32-bit to a 64-bit version of Python. Indeed, a 32-bit software, like a 32-bit CPU, can adress a maximum of 4 GB of RAM (2^32). So if you have more than 4 GB of RAM, a 32-bit version cannot take advantage of it.

With a 64-bit version of Python (the one labeled x86-64 in the download page), the issue disappeared.

You can check which version you have by entering the interpreter. I, with a 64-bit version, now have: Python 3.7.5rc1 (tags/v3.7.5rc1:4082f600a5, Oct 1 2019, 20:28:14) [MSC v.1916 64 bit (AMD64)], where [MSC v.1916 64 bit (AMD64)] means "64-bit Python".

Note : as of the time of this writing (May 2020), matplotlib is not available on python39, so I recommand installing python37, 64 bits.

Sources :

How do I access properties of a javascript object if I don't know the names?

var obj = {
 a: [1, 3, 4],
 b: 2,
 c: ['hi', 'there']
 }
for(let r in obj){  //for in loop iterates all properties in an object
 console.log(r) ;  //print all properties in sequence
 console.log(obj[r]);//print all properties values
}

Proper way to wait for one function to finish before continuing?

Use async/await :

async function firstFunction(){
  for(i=0;i<x;i++){
    // do something
  }
  return;
};

then use await in your other function to wait for it to return:

async function secondFunction(){
  await firstFunction();
  // now wait for firstFunction to finish...
  // do something else
};

Show Curl POST Request Headers? Is there a way to do this?

You can save all headers sent by curl to a file using :

$f = fopen('request.txt', 'w');
curl_setopt($ch,CURLOPT_VERBOSE,true);
curl_setopt($ch,CURLOPT_STDERR ,$f);

Add a dependency in Maven

Actually, on investigating this, I think all these answers are incorrect. Your question is misleading because of our level of understanding of maven. And I say our because I'm just getting introduced to maven.

In Eclipse, when you want to add a jar file to your project, normally you download the jar manually and then drop it into the lib directory. With maven, you don't do it this way. Here's what you do:

  • Go to mvnrepository
  • Search for the library you want to add
  • Copy the dependency statement into your pom.xml
  • rebuild via mvn

Now, maven will connect and download the jar along with the list of dependencies, and automatically resolve any additional dependencies that jar may have had. So if the jar also needed commons-logging, that will be downloaded as well.

Java Object Null Check for method

First you should check if books itself isn't null, then simply check whether books[i] != null:

if(books==null) throw new IllegalArgumentException();

for (int i = 0; i < books.length; i++){
   if(books[i] != null){
        total += books[i].getPrice();
   }
}

number_format() with MySQL

FORMAT(X,D) Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns the result as a string. If D is 0, the result has no decimal point or fractional part.

 SELECT FORMAT(12332.123456, 4);
        -> '12,332.1235'

Initializing C# auto-properties

You can do it via the constructor of your class:

public class foo {
  public foo(){
    Bar = "bar";
  }
  public string Bar {get;set;}
}

If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):

public class foo {
  private foo(){
    Bar = "bar";
    Baz = "baz";
  }
  public foo(int something) : this(){
    //do specialized initialization here
    Baz = string.Format("{0}Baz", something);
  }
  public string Bar {get; set;}
  public string Baz {get; set;}
}

If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.

org.hibernate.MappingException: Unknown entity: annotations.Users

I was facing the same issue and I searched for almost 2 hours and tried with different possible ways like replacing old hibernate JARs and changing the DB table schema. But finally got the solution as below:

SessionFactory factory = new Configuration().configure().buildSessionFactory(); //This line to be replaced with below commented line

Replace above for

//Configuration config = new Configuration().configure();
//ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
//SessionFactory factory = config.buildSessionFactory(servReg);

It will then work fine..

copy all files and folders from one drive to another drive using DOS (command prompt)

Use robocopy. Robocopy is shipped by default on Windows Vista and newer, and is considered the replacement for xcopy. (xcopy has some significant limitations, including the fact that it can't handle paths longer than 256 characters, even if the filesystem can).

robocopy c:\ d:\ /e /zb /copyall /purge /dcopy:dat

Note that using /purge on the root directory of the volume will cause Robocopy to apply the requested operation on files inside the System Volume Information directory. Run robocopy /? for help. Also note that you probably want to open the command prompt as an administrator to be able to copy system files. To speed things up, use /b instead of /zb.

Java how to sort a Linked List?

In order to sort Strings alphabetically you will need to use a Collator, like:

 LinkedList<String> list = new LinkedList<String>();
 list.add("abc");
 list.add("Bcd");
 list.add("aAb");
 Collections.sort(list, new Comparator<String>() {
     @Override
     public int compare(String o1, String o2) {
         return Collator.getInstance().compare(o1, o2);
     }
 });

Because if you just call Collections.sort(list) you will have trouble with strings that contain uppercase characters.

For instance in the code I pasted, after the sorting the list will be: [aAb, abc, Bcd] but if you just call Collections.sort(list); you will get: [Bcd, aAb, abc]

Note: When using a Collator you can specify the locale Collator.getInstance(Locale.ENGLISH) this is usually pretty handy.

How do I get out of 'screen' without typing 'exit'?

  • Ctrl + A and then Ctrl+D. Doing this will detach you from the screen session which you can later resume by doing screen -r.

  • You can also do: Ctrl+A then type :. This will put you in screen command mode. Type the command detach to be detached from the running screen session.

How would you make two <div>s overlap?

I might approach it like so (CSS and HTML):

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0px;_x000D_
}_x000D_
#logo {_x000D_
  position: absolute; /* Reposition logo from the natural layout */_x000D_
  left: 75px;_x000D_
  top: 0px;_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
  z-index: 2;_x000D_
}_x000D_
#content {_x000D_
  margin-top: 100px; /* Provide buffer for logo */_x000D_
}_x000D_
#links {_x000D_
  height: 75px;_x000D_
  margin-left: 400px; /* Flush links (with a 25px "padding") right of logo */_x000D_
}
_x000D_
<div id="logo">_x000D_
  <img src="https://via.placeholder.com/200x100" />_x000D_
</div>_x000D_
<div id="content">_x000D_
  _x000D_
  <div id="links">dssdfsdfsdfsdf</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

MySql: is it possible to 'SUM IF' or to 'COUNT IF'?

There is a slight difference between the top answers, namely SUM(case when kind = 1 then 1 else 0 end) and SUM(kind=1).

When all values in column kind happen to be NULL, the result of SUM(case when kind = 1 then 1 else 0 end) is 0, whereas the result of SUM(kind=1) is NULL.

An example (http://sqlfiddle.com/#!9/b23807/2):

Schema:

CREATE TABLE Table1
(`first_col` int, `second_col` int)
;

INSERT INTO Table1
    (`first_col`, `second_col`)
VALUES
       (1, NULL),
       (1, NULL),
       (NULL, NULL)
;

Query results:

SELECT SUM(first_col=1) FROM Table1;
-- Result: 2
SELECT SUM(first_col=2) FROM Table1;
-- Result: 0
SELECT SUM(second_col=1) FROM Table1;
-- Result: NULL
SELECT SUM(CASE WHEN second_col=1 THEN 1 ELSE 0 END) FROM Table1;
-- Result: 0

How to add number of days to today's date?

Pure JS solution, with date formatted YYYY-mm-dd format

_x000D_
_x000D_
var someDate = new Date('2014-05-14');_x000D_
someDate.setDate(someDate.getDate() + 15); //number  of days to add, e.x. 15 days_x000D_
var dateFormated = someDate.toISOString().substr(0,10);_x000D_
console.log(dateFormated);
_x000D_
_x000D_
_x000D_

ArrayList: how does the size increase?

When ArrayList is declared and initialized using the default constructor, memory space for 10 elements is created.

NO. When ArrayList is initialized, memory allocation is made for an empty array. Memory allocation for default capacity (10) is made only upon addition of first element to ArrayList.

 /**
 * The array buffer into which the elements of the ArrayList are stored.
 * The capacity of the ArrayList is the length of this array buffer. Any
 * empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to
 * DEFAULT_CAPACITY when the first element is added.
 */
private transient Object[] elementData;

P.S. Don't have enough reputation to comment on question, so I am putting this as an answer as nobody pointed out this incorrect assumption earlier.

How to style SVG <g> element?

You cannot add style to an SVG <g> element. Its only purpose is to group children. That means, too, that style attributes you give to it are given down to its children, so a fill="green" on the <g> means an automatic fill="green" on its child <rect> (as long as it has no own fill specification).

Your only option is to add a new <rect> to the SVG and place it accordingly to match the <g> children's dimensions.

Best way to retrieve variable values from a text file?

But what i'll love is to refer to the variable direclty, as i declared it in the python script..

Assuming you're happy to change your syntax slightly, just use python and import the "config" module.

# myconfig.py:

var_a = 'home'
var_b = 'car'
var_c = 15.5

Then do

from myconfig import *

And you can reference them by name in your current context.

Carriage return and Line feed... Are both required in C#?

I know this is a little old, but for anyone stumbling across this page should know there is a difference between \n and \r\n.

The \r\n gives a CRLF end of line and the \n gives an LF end of line character. There is very little difference to the eye in general.

Create a .txt from the string and then try and open in notepad (normal not notepad++) and you will notice the difference

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIOD
Q44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901
Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

The above is using 'CRLF' and the below is what 'LF only' would look like (There is a character that cant be seen where the LF shows).

SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIODQ44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901

If the Line Ends need to be corrected and the file is small enough in size, you can change the line endings in NotePad++ (or paste into word then back into Notepad - although this will make CRLF only).

This may cause some functions that read these files to potenitially no longer function (The example lines given are from GP Prescribing data - England. The file has changed from a CRLF Line end to an LF line end). This stopped an SSIS job from running and failed as couldn't read the LF line endings.

Source of Line Ending Information: https://en.wikipedia.org/wiki/Newline#Representations_in_different_character_encoding_specifications

Hope this helps someone in future :) CRLF = Windows based, LF or CF are from Unix based systems (Linux, MacOS etc.)

How to indent HTML tags in Notepad++

Step 1: Open plugin manager in notepad++

Plugins -> Plugin Manager -> Show Plugin Manager.

Step 2:install XML Tool plugin

Search "XML TOOLS" from the "Available" option then click in install.

Now you can use shortcut key CTRL+ALT+SHIFT+B to indent the code.

Why std::cout instead of simply cout?

You probably had using namespace std; before in your code you did in class. That explicitly tells the precompiler to look for the symbols in std, which means you don't need to std::. Though it is good practice to std::cout instead of cout so you explicitly invoke std::cout every time. That way if you are using another library that redefines cout, you still have the std::cout behavior instead of some other custom behavior.

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

For Windows 10 / Windows Server 2016 use the following command:

dism /online /enable-feature /featurename:IIS-ASPNET45 /all

The suggested answers with aspnet_regiis doesn't work on Windows 10 (Creators Update and later) or Windows Server 2016:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
Microsoft (R) ASP.NET RegIIS version 4.0.30319.0
Administration utility to install and uninstall ASP.NET on the local machine.
Copyright (C) Microsoft Corporation. All rights reserved.
Start installing ASP.NET (4.0.30319.0).
This option is not supported on this version of the operating system. Administrators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Windows Features On/Off" dialog, the Server Manager management tool, or the dism.exe command line tool. For more details please see http://go.microsoft.com/fwlink/?LinkID=216771.
Finished installing ASP.NET (4.0.30319.0).

Interestingly, the "Turn Windows Features On/Off" dialog didn't allow me to untick .NET nor ASP.NET 4.6, and only the above DISM command worked. Not sure whether the featurename is correct, but it worked for me.

Elevating process privilege programmatically?

You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows:

startInfo.Verb = "runas";

This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.

This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by Create and Embed an Application Manifest (UAC) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.

Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

I know this is an older thread but I just bumped into this. If the user is trying to run inserts on the Identity column after some other session Set IDENTITY_INSERT ON, then he is bound to get the above error.

Setting the Identity Insert value and the subsequent Insert DML commands are to be run by the same session.

Here @Beginner was setting Identity Insert ON separately and then running the inserts from his application. That is why he got the below Error:

Cannot insert explicit value for identity column in table 'Baskets' when 
IDENTITY_INSERT is set to OFF.

Class vs. static method in JavaScript

When i faced such a situation, i have done something like this:

Logger = {
    info: function (message, tag) {
        var fullMessage = '';        
        fullMessage = this._getFormatedMessage(message, tag);
        if (loggerEnabled) {
            console.log(fullMessage);
        }
    },
    warning: function (message, tag) {
        var fullMessage = '';
        fullMessage = this._getFormatedMessage(message, tag);
        if (loggerEnabled) {
            console.warn(fullMessage);`enter code here`
        }
    },
    _getFormatedMessage: function () {}
};

so now i can call the info method as Logger.info("my Msg", "Tag");

Can someone explain Microsoft Unity?

Unity is an IoC. The point of IoC is to abstract the wiring of dependencies between types outside of the types themselves. This has a couple of advantages. First of all, it is done centrally which means you don't have to change a lot of code when dependencies change (which may be the case for unit tests).

Furthermore, if the wiring is done using configuration data instead of code, you can actually rewire the dependencies after deployment and thus change the behavior of the application without changing the code.

How can my iphone app detect its own version number?

Swift version for both separately:

Swift 3

let versionNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String

Swift 2

let versionNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") as! String

Its included in this repo, check it out:

https://github.com/goktugyil/EZSwiftExtensions

How to change TIMEZONE for a java.util.Calendar/Date

  1. The class Date/Timestamp represents a specific instant in time, with millisecond precision, since January 1, 1970, 00:00:00 GMT. So this time difference (from epoch to current time) will be same in all computers across the world with irrespective of Timezone.

  2. Date/Timestamp doesn't know about the given time is on which timezone.

  3. If we want the time based on timezone we should go for the Calendar or SimpleDateFormat classes in java.

  4. If you try to print a Date/Timestamp object using toString(), it will convert and print the time with the default timezone of your machine.

  5. So we can say (Date/Timestamp).getTime() object will always have UTC (time in milliseconds)

  6. To conclude Date.getTime() will give UTC time, but toString() is on locale specific timezone, not UTC.

Now how will I create/change time on specified timezone?

The below code gives you a date (time in milliseconds) with specified timezones. The only problem here is you have to give date in string format.

   DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
   dateFormatLocal.setTimeZone(timeZone);
   java.util.Date parsedDate = dateFormatLocal.parse(date);

Use dateFormat.format for taking input Date (which is always UTC), timezone and return date as String.

How to store UTC/GMT time in DB:

If you print the parsedDate object, the time will be in default timezone. But you can store the UTC time in DB like below.

        Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        Timestamp tsSchedStartTime = new Timestamp (parsedDate.getTime());
        if (tsSchedStartTime != null) {
            stmt.setTimestamp(11, tsSchedStartTime, calGMT );
        } else {
            stmt.setNull(11, java.sql.Types.DATE);
        }

How do I delete virtual interface in Linux?

Have you tried:

ifconfig 10:35978f0 down

As the physical interface is 10 and the virtual aspect is after the colon :.

See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/

Vue equivalent of setTimeout?

If you want to use the this keyword in your function, you need to write the setTimeout function in ES6

setTimeout(() => {
   this.filters.max_budget_gt_eq = this.budgetHigherValue;
}, 1000);

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Update: I should have probably started with this as your projects are SNAPSHOTs. It is part of the SNAPSHOT semantics that Maven will check for updates on each build. Being a SNAPSHOT means that it is volatile and subject to change so updates should be checked for. However it's worth pointing out that the Maven super POM configures central to have snapshots disabled, so Maven shouldn't ever check for updates for SNAPSHOTs on central unless you've overridden that in your own pom/settings.


You can configure Maven to use a mirror for the central repository, this will redirect all requests that would normally go to central to your internal repository.

In your settings.xml you would add something like this to set your internal repository as as mirror for central:

<mirrors>
  <mirror>
    <id>ibiblio.org</id>
    <name>ibiblio Mirror of http://repo1.maven.org/maven2/</name>
    <url>http://path/to/my/repository</url>
    <mirrorOf>central</mirrorOf>
  </mirror>
</mirrors>

If you are using a repository manager like Nexus for your internal repository. You can set up a proxy repository for proxy central, so any requests that would normally go to Central are instead sent to your proxy repository (or a repository group containing the proxy), and subsequent requests are cached in the internal repository manager. You can even set the proxy cache timeout to -1, so it will never request for contents from central that are already on the proxy repository.


A more basic solution if you are only working with local repositories is to set the updatePolicy for the central repository to "never", this means Maven will only ever check for artifacts that aren't already in the local repository. This can then be overridden at the command line when needed by using the -U switch to force Maven to check for updates.

You would configure the repository (in your pom or a profile in the settings.xml) as follows:

<repository>
  <id>central</id>
  <url>http://repo1.maven.org/maven2</url>
  <updatePolicy>never</updatePolicy>
</repository>

Java : Accessing a class within a package, which is the better way?

Import package is for better readability;

Fully qualified class has to be used in special scenarios. For example, same class name in different package, or use reflect such as Class.forName().

Add directives from directive in AngularJS

You can actually handle all of this with just a simple template tag. See http://jsfiddle.net/m4ve9/ for an example. Note that I actually didn't need a compile or link property on the super-directive definition.

During the compilation process, Angular pulls in the template values before compiling, so you can attach any further directives there and Angular will take care of it for you.

If this is a super directive that needs to preserve the original internal content, you can use transclude : true and replace the inside with <ng-transclude></ng-transclude>

Hope that helps, let me know if anything is unclear

Alex

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail 
WHERE ISDATE(LoginTime) = 1

EDIT :

As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT

SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail 

or

SELECT LEFT(LoginTime,10) FROM AuditTrail

EDIT 2 :

The major reason for the error will be in your date in WHERE clause.ie,

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('06/18/2012' AS DATE)

will be different from

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('18/06/2012' AS DATE)

CONCLUSION

In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.

LINQ Group By into a Dictionary Object

I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.

Use it like:

var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]

Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().

Checking session if empty or not

If It is simple Session you can apply NULL Check directly Session["emp_num"] != null

But if it's a session of a list Item then You need to apply any one of the following option

Option 1:

if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
 {
 //Your Logic here
 }

Option 2:

List<int> val= Session["emp_num"] as List<int>;  //Get the value from Session.

if (val.FirstOrDefault() != null)
 {
 //Your Logic here
 }

Debugging JavaScript in IE7

you might want to try microsoft script debugger it's pretty old but it's quite useful in the sense if you stumble on any javascript error, the debugger will popup to show you which line is messing up. it could get irrating sometimes when you do normal surfing, but you can turn if off.

here's a good startup on how to use this tool too. HOW-TO: Debug JavaScript in Internet Explorer

Create table (structure) from existing table

SELECT * 
INTO NewTable
FROM OldTable
WHERE 1 = 2

How to print jquery object/array

_x000D_
_x000D_
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];_x000D_
var data = arrofobject.map(arrofobject => arrofobject);_x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

for more details please look at jQuery.map()

Get list of all tables in Oracle?

select * from dba_tables

gives all the tables of all the users only if the user with which you logged in is having the sysdba privileges.

How to programmatically set the SSLContext of a JAX-WS client?

This is how I solved it based on this post with some minor tweaks. This solution does not require creation of any additional classes.

SSLContext sc = SSLContext.getInstance("SSLv3");

KeyManagerFactory kmf =
    KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );

KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
ks.load(new FileInputStream( certPath ), certPasswd.toCharArray() );

kmf.init( ks, certPasswd.toCharArray() );

sc.init( kmf.getKeyManagers(), null, null );

((BindingProvider) webservicePort).getRequestContext()
    .put(
        "com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
        sc.getSocketFactory() );

Return Boolean Value on SQL Select Statement

Use 'Exists' which returns either 0 or 1.

The query will be like:

SELECT EXISTS(SELECT * FROM USER WHERE UserID = 20070022)

UIGestureRecognizer on UIImageView

Check that userInteractionEnabled is YES on the UIImageView. Then you can add a gesture recognizer.

imageView.userInteractionEnabled = YES;
UIPinchGestureRecognizer *pgr = [[UIPinchGestureRecognizer alloc] 
    initWithTarget:self action:@selector(handlePinch:)];
pgr.delegate = self;
[imageView addGestureRecognizer:pgr];
[pgr release];
:
:
- (void)handlePinch:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
  //handle pinch...
}

In Mongoose, how do I sort by date? (node.js)

I do this:

Data.find( { $query: { user: req.user }, $orderby: { dateAdded: -1 } } function ( results ) {
    ...
})

This will show the most recent things first.

PHP ini file_get_contents external url

Complementing Aillyn's answer, you could use a function like the one below to mimic the behavior of file_get_contents:

function get_content($URL){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_URL, $URL);
      $data = curl_exec($ch);
      curl_close($ch);
      return $data;
}

echo get_content('http://example.com');

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

How can I hide select options with JavaScript? (Cross browser)

Since you mentioned that you want to re-add the options later, I would suggest that you load an array or object with the contents of the select box on page load - that way you always have a "master list" of the original select if you need to restore it.

I made a simple example that removes the first element in the select and then a restore button puts the select box back to it's original state:

http://jsfiddle.net/CZcvM/

how to get the one entry from hashmap without iterating

Stumbled here looking for the same thing...I then remembered the Iterables class from the Guava library.

To get the "first" element: Iterables.getFirst( someMap.values(), null );.
Essentially does the same as Map.values().iterator().next(), but also allows you to specify a default (in this case null) should there be nothing in the Map.

Iterables.getLast( someMap.values(), null ); returns the last element in the Map.

Iterables.get( someMap.values(), 7, null ); returns the 7th element in the Map if exists, otherwise a default value (in this case null).

Remember though that HashMaps are not ordered...so don't expect Iterables.getFirst to return the first item you tossed in there...likewise with Iterables.getLast. Perhaps useful to get a mapped value though.

It may not be worth adding the Guava library for just that, but if you happen to be using some of the other cool utilities within that library...

How to use std::sort to sort an array in C++

You can sort it std::sort(v, v + 2000)

Maximum number of rows of CSV data in excel sheet

CSV files have no limit of rows you can add to them. Excel won't hold more that the 1 million lines of data if you import a CSV file having more lines.

Excel will actually ask you whether you want to proceed when importing more than 1 million data rows. It suggests to import the remaining data by using the text import wizard again - you will need to set the appropriate line offset.

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

In my case it was pretty much what Mayank Shukla's top answer says. The only detail was that my state was lacking completely the property I was defining.

For example, if you have this state:

state = {
    "a" : "A",
    "b" : "B",
}

If you're expanding your code, you might want to add a new prop so, someplace else in your code you might create a new property c whose value is not only undefined on the component's state but the property itself is undefined.

To solve this just make sure to add c into your state and give it a proper initial value.

e.g.,

state = {
    "a" : "A",
    "b" : "B",
    "c" : "C", // added and initialized property!
}

Hope I was able to explain my edge case.

How to check if internet connection is present in Java?

I usually break it down into three steps.

  1. I first see if I can resolve the domain name to an IP address.
  2. I then try to connect via TCP (port 80 and/or 443) and close gracefully.
  3. Finally, I'll issue an HTTP request and check for a 200 response back.

If it fails at any point, I provide the appropriate error message to the user.

When should you use 'friend' in C++?

Firstly (IMO) don't listen to people who say friend is not useful. It IS useful. In many situations you will have objects with data or functionality that are not intended to be publicly available. This is particularly true of large codebases with many authors who may only be superficially familiar with different areas.

There ARE alternatives to the friend specifier, but often they are cumbersome (cpp-level concrete classes/masked typedefs) or not foolproof (comments or function name conventions).

Onto the answer;

The friend specifier allows the designated class access to protected data or functionality within the class making the friend statement. For example in the below code anyone may ask a child for their name, but only the mother and the child may change the name.

You can take this simple example further by considering a more complex class such as a Window. Quite likely a Window will have many function/data elements that should not be publicly accessible, but ARE needed by a related class such as a WindowManager.

class Child
{
//Mother class members can access the private parts of class Child.
friend class Mother;

public:

  string name( void );

protected:

  void setName( string newName );
};

Rails :include vs. :joins

tl;dr

I contrast them in two ways:

joins - For conditional selection of records.

includes - When using an association on each member of a result set.

Longer version

Joins is meant to filter the result set coming from the database. You use it to do set operations on your table. Think of this as a where clause that performs set theory.

Post.joins(:comments)

is the same as

Post.where('id in (select post_id from comments)')

Except that if there are more than one comment you will get duplicate posts back with the joins. But every post will be a post that has comments. You can correct this with distinct:

Post.joins(:comments).count
=> 10
Post.joins(:comments).distinct.count
=> 2

In contract, the includes method will simply make sure that there are no additional database queries when referencing the relation (so that we don't make n + 1 queries)

Post.includes(:comments).count
=> 4 # includes posts without comments so the count might be higher.

The moral is, use joins when you want to do conditional set operations and use includes when you are going to be using a relation on each member of a collection.

Returning binary file from controller in ASP.NET Web API

The overload that you're using sets the enumeration of serialization formatters. You need to specify the content type explicitly like:

httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

"No rule to make target 'install'"... But Makefile exists

I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install. When I changed to the directory that had my makefile it worked.

So possibly you aren't in the right directory.

How to get the size of a JavaScript object?

There is a NPM module to get object sizeof, you can install it with npm install object-sizeof

  var sizeof = require('object-sizeof');

  // 2B per character, 6 chars total => 12B
  console.log(sizeof({abc: 'def'}));

  // 8B for Number => 8B
  console.log(sizeof(12345));

  var param = { 
    'a': 1, 
    'b': 2, 
    'c': {
      'd': 4
    }
  };
  // 4 one two-bytes char strings and 3 eighth-bytes numbers => 32B
  console.log(sizeof(param));

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

Just to elaborate a bit more on Henry's answer, you can also use specific error codes, from raise_application_error and handle them accordingly on the client side. For example:

Suppose you had a PL/SQL procedure like this to check for the existence of a location record:

   PROCEDURE chk_location_exists
   (
      p_location_id IN location.gie_location_id%TYPE
   )
   AS
      l_cnt INTEGER := 0;
   BEGIN
      SELECT COUNT(*)
        INTO l_cnt
        FROM location
       WHERE gie_location_id = p_location_id;

       IF l_cnt = 0
       THEN
          raise_application_error(
             gc_entity_not_found,
             'The associated location record could not be found.');
       END IF;
   END;

The raise_application_error allows you to raise a specific error code. In your package header, you can define: gc_entity_not_found INTEGER := -20001;

If you need other error codes for other types of errors, you can define other error codes using -20002, -20003, etc.

Then on the client side, you can do something like this (this example is for C#):

/// <summary>
/// <para>Represents Oracle error number when entity is not found in database.</para>
/// </summary>
private const int OraEntityNotFoundInDB = 20001;

And you can execute your code in a try/catch

try
{
   // call the chk_location_exists SP
}
catch (Exception e)
{
    if ((e is OracleException) && (((OracleException)e).Number == OraEntityNotFoundInDB))
    {
        // create an EntityNotFoundException with message indicating that entity was not found in
        // database; use the message of the OracleException, which will indicate the table corresponding
        // to the entity which wasn't found and also the exact line in the PL/SQL code where the application
        // error was raised
        return new EntityNotFoundException(
            "A required entity was not found in the database: " + e.Message);
    }
}

How to start a background process in Python?

You probably want to start investigating the os module for forking different threads (by opening an interactive session and issuing help(os)). The relevant functions are fork and any of the exec ones. To give you an idea on how to start, put something like this in a function that performs the fork (the function needs to take a list or tuple 'args' as an argument that contains the program's name and its parameters; you may also want to define stdin, out and err for the new thread):

try:
    pid = os.fork()
except OSError, e:
    ## some debug output
    sys.exit(1)
if pid == 0:
    ## eventually use os.putenv(..) to set environment variables
    ## os.execv strips of args[0] for the arguments
    os.execv(args[0], args)

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

The accepted answer of using npm-install-peers did not work, nor removing node_modules and rebuilding. The answer to run

npm install --save-dev @xxxxx/xxxxx@latest

for each one, with the xxxxx referring to the exact text in the peer warning, worked. I only had four warnings, if I had a dozen or more as in the question, it might be a good idea to script the commands.

How to set the custom border color of UIView programmatically?

Swift 5*

I, always use view extension to make view corners round, set border color and width and it has been the most convenient way for me. just copy and paste this code and controlle these properties in attribute inspector.

extension UIView {
    @IBInspectable
    var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
        }
    }
    
    @IBInspectable
    var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
    
    @IBInspectable
    var borderColor: UIColor? {
        get {
            if let color = layer.borderColor {
                return UIColor(cgColor: color)
            }
            return nil
        }
        set {
            if let color = newValue {
                layer.borderColor = color.cgColor
            } else {
                layer.borderColor = nil
            }
        }
    }
}

Passing $_POST values with cURL

$query_string = "";

if ($_POST) {
    $kv = array();
    foreach ($_POST as $key => $value) {
        $kv[] = stripslashes($key) . "=" . stripslashes($value);
    }
    $query_string = join("&", $kv);
}

if (!function_exists('curl_init')){
    die('Sorry cURL is not installed!');
}

$url = 'https://www.abcd.com/servlet/';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);

curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

$result = curl_exec($ch);

curl_close($ch);

Error: could not find function ... in R

Rdocumentation.org has a very handy search function that - among other things - lets you find functions - from all the packages on CRAN, as well as from packages from Bioconductor and GitHub.

enter image description here

What is the symbol for whitespace in C?

To check a space symbol you can use the following approach

if ( c == ' ' ) { /*...*/ }

To check a space and/or a tab symbol (standard blank characters) you can use the following approach

#include <ctype.h>

//...

if ( isblank( c ) ) { /*...*/ }

To check a white space you can use the following approach

#include <ctype.h>

//...

if ( isspace( c ) ) { /*...*/ }

Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

Please check whether another mysql service is running.

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

I ran into the 'Expecting: ANY PRIVATE KEY' error when using openssl on Windows (Ubuntu Bash and Git Bash had the same issue).

The cause of the problem was that I'd saved the key and certificate files in Notepad using UTF8. Resaving both files in ANSI format solved the problem.

Should I use pt or px?

Here you've got a very detailed explanation of their differences

http://kyleschaeffer.com/development/css-font-size-em-vs-px-vs-pt-vs/

The jist of it (from source)

Pixels are fixed-size units that are used in screen media (i.e. to be read on the computer screen). Pixel stands for "picture element" and as you know, one pixel is one little "square" on your screen. Points are traditionally used in print media (anything that is to be printed on paper, etc.). One point is equal to 1/72 of an inch. Points are much like pixels, in that they are fixed-size units and cannot scale in size.

Query an XDocument for elements by name at any depth

An example indicating the namespace:

String TheDocumentContent =
@"
<TheNamespace:root xmlns:TheNamespace = 'http://www.w3.org/2001/XMLSchema' >
   <TheNamespace:GrandParent>
      <TheNamespace:Parent>
         <TheNamespace:Child theName = 'Fred'  />
         <TheNamespace:Child theName = 'Gabi'  />
         <TheNamespace:Child theName = 'George'/>
         <TheNamespace:Child theName = 'Grace' />
         <TheNamespace:Child theName = 'Sam'   />
      </TheNamespace:Parent>
   </TheNamespace:GrandParent>
</TheNamespace:root>
";

XDocument TheDocument = XDocument.Parse( TheDocumentContent );

//Example 1:
var TheElements1 =
from
    AnyElement
in
    TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" )
select
    AnyElement;

ResultsTxt.AppendText( TheElements1.Count().ToString() );

//Example 2:
var TheElements2 =
from
    AnyElement
in
    TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" )
where
    AnyElement.Attribute( "theName" ).Value.StartsWith( "G" )
select
    AnyElement;

foreach ( XElement CurrentElement in TheElements2 )
{
    ResultsTxt.AppendText( "\r\n" + CurrentElement.Attribute( "theName" ).Value );
}

Extract parameter value from url using regular expressions

v is a query parameter, technically you need to consider cases ala: http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk

In .NET I would recommend to use System.Web.HttpUtility.ParseQueryString

HttpUtility.ParseQueryString(url)["v"];

And you don't even need to check the key, as it will return null if the key is not in the collection.

Force div element to stay in same place, when page is scrolled

You can do this replacing position:absolute; by position:fixed;.

What is the iPhone 4 user-agent?

Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7

Extract code country from phone number [libphonenumber]

Okay, so I've joined the google group of libphonenumber ( https://groups.google.com/forum/?hl=en&fromgroups#!forum/libphonenumber-discuss ) and I've asked a question.

I don't need to set the country in parameter if my phone number begins with "+". Here is an example :

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    // phone must begin with '+'
    PhoneNumber numberProto = phoneUtil.parse(phone, "");
    int countryCode = numberProto.getCountryCode();
} catch (NumberParseException e) {
    System.err.println("NumberParseException was thrown: " + e.toString());
}

Save child objects automatically using JPA Hibernate

in your setChilds, you might want to try looping thru the list and doing something like

child.parent = this;

you also should set up the cascade on the parent to the appropriate values.

Objective-C : BOOL vs bool

From the definition in objc.h:

#if (TARGET_OS_IPHONE && __LP64__)  ||  TARGET_OS_WATCH
typedef bool BOOL;
#else
typedef signed char BOOL; 
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C" 
// even if -funsigned-char is used.
#endif

#define YES ((BOOL)1)
#define NO  ((BOOL)0)

So, yes, you can assume that BOOL is a char. You can use the (C99) bool type, but all of Apple's Objective-C frameworks and most Objective-C/Cocoa code uses BOOL, so you'll save yourself headache if the typedef ever changes by just using BOOL.

How do I declare a two dimensional array?

Firstly, PHP doesn't have multi-dimensional arrays, it has arrays of arrays.

Secondly, you can write a function that will do it:

function declare($m, $n, $value = 0) {
  return array_fill(0, $m, array_fill(0, $n, $value));
}

Which port(s) does XMPP use?

The official ports (TCP:5222 and TCP:5269) are listed in RFC 6120. Contrary to the claims of a previous answer, XEP-0174 does not specify a port. Thus TCP:5298 might be customary for Link-Local XMPP, but is not official.

You can use other ports than the reserved ones, though: You can make your DNS SRV record point to any machine and port you like.

File transfers (XEP-0234) are these days handled using Jingle (XEP-0166). The same goes for RTP sessions (XEP-0167). They do not specify ports, though, since Jingle negotiates the creation of the data stream between the XMPP clients, but the actual data is then transferred by other means (e.g. RTP) through that stream (i.e. not usually through the XMPP server, even though in-band transfers are possible). Beware that Jingle is comprised of several XEPs, so make sure to have a look at the whole list of XMPP extensions.

How to convert byte[] to InputStream?

ByteArrayInputStream extends InputStream:

InputStream myInputStream = new ByteArrayInputStream(myBytes); 

Body set to overflow-y:hidden but page is still scrollable in Chrome

The correct answer is, you need to set JUST body to overflow:hidden. For whatever reason, if you also set html to overflow:hidden the result is the problem you've described.

Restricting input to textbox: allowing only numbers and decimal point

Working on the issue myself, and that's what I've got so far. This more or less works, but it's impossible to add minus afterwards due to the new value check. Also doesn't allow comma as a thousand separator, only decimal.

It's not perfect, but might give some ideas.

app.directive('isNumber', function () {
            return function (scope, elem, attrs) {
                elem.bind('keypress', function (evt) {
                    var keyCode = (evt.which) ? evt.which : event.keyCode;
                    var testValue = (elem[0].value + String.fromCharCode(keyCode) + "0").replace(/ /g, ""); //check ignores spaces
                    var regex = /^\-?\d+((\.|\,)\d+)?$/;                        
                    var allowedChars = [8,9,13,27,32,37,39,44,45, 46] //control keys and separators             

                   //allows numbers, separators and controll keys and rejects others
                    if ((keyCode > 47 && keyCode < 58) || allowedChars.indexOf(keyCode) >= 0) {             
                        //test the string with regex, decline if doesn't fit
                        if (elem[0].value != "" && !regex.test(testValue)) {
                            event.preventDefault();
                            return false;
                        }
                        return true;
                    }
                    event.preventDefault();
                    return false;
                });
            };
        });

Allows:

11 11 .245 (in controller formatted on blur to 1111.245)

11,44

-123.123

-1 014

0123 (formatted on blur to 123)

doesn't allow:

!@#$/*

abc

11.11.1

11,11.1

.42