Programs & Examples On #Core data

Core Data is Apple's object modeling and persistence framework for macOS and iOS. Xcode provides an object model editor for specifying entities, attributes, and relationships.

Xcode 6 iPhone Simulator Application Support location

Here is the sh for last used simulator and application. Just run sh and copy printed text and paste and run command for show in finder.

#!/bin/zsh

lastUsedSimulatorAndApplication=`ls -td -- ~/Library/Developer/CoreSimulator/Devices/*/data/Containers/Data/Application/*/ | head -n1`

echo $lastUsedSimulatorAndApplication

Delete/Reset all entries in Core Data?

I've written a clearStores method that goes through every store and delete it both from the coordinator and the filesystem (error handling left aside):

NSArray *stores = [persistentStoreCoordinator persistentStores];

for(NSPersistentStore *store in stores) {
    [persistentStoreCoordinator removePersistentStore:store error:nil];
    [[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];
}

[persistentStoreCoordinator release], persistentStoreCoordinator = nil;

This method is inside a coreDataHelper class that takes care of (among other things) creating the persistentStore when it's nil.

Core Data: Quickest way to delete all instances of an entity

    func deleteAll(entityName: String) {

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    deleteRequest.resultType = .resultTypeObjectIDs
    guard let context = self.container?.viewContext
        else { print("error in deleteAll")
            return }

    do {
        let result = try context.execute(deleteRequest) as? NSBatchDeleteResult
        let objectIDArray = result?.result as? [NSManagedObjectID]
        let changes: [AnyHashable : Any] = [NSDeletedObjectsKey : objectIDArray as Any]
        NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [context])
    } catch {
        print(error.localizedDescription)
    }
}

How do I declare class-level properties in Objective-C?

Here's a thread safe way of doing it:

// Foo.h
@interface Foo {
}

+(NSDictionary*) dictionary;

// Foo.m
+(NSDictionary*) dictionary
{
  static NSDictionary* fooDict = nil;

  static dispatch_once_t oncePredicate;

  dispatch_once(&oncePredicate, ^{
        // create dict
    });

  return fooDict;
}

These edits ensure that fooDict is only created once.

From Apple documentation: "dispatch_once - Executes a block object once and only once for the lifetime of an application."

Adding to a vector of pair

Or you can use initialize list:

revenue.push_back({"string", map[i].second});

Java: Check the date format of current string is according to required format or not

Regex can be used for this with some detailed info for validation, for example this code can be used to validate any date in (DD/MM/yyyy) format with proper date and month value and year between (1950-2050)

    public Boolean checkDateformat(String dateToCheck){   
        String rex="([0]{1}[1-9]{1}|[1-2]{1}[0-9]{1}|[3]{1}[0-1]{1})+
        \/([0]{1}[1-9]{1}|[1]{1}[0-2]{2})+
        \/([1]{1}[9]{1}[5-9]{1}[0-9]{1}|[2]{1}[0]{1}([0-4]{1}+
        [0-9]{1}|[5]{1}[0]{1}))";

        return(dateToCheck.matches(rex));
    }

PHP: Return all dates between two dates in an array

Here's a way of doing this using Carbon https://github.com/briannesbitt/Carbon:

public function buildDateRangeArray($first, $last)
{
    while ($first <= $last) {
        $dates[] = $first->toDateString();

        $first->addDay();
    }

    return $dates;
}

This, of course, can be tweaked to not use Carbon. The $first and $last parameters passed to the function are Carbon instances.

"static const" vs "#define" vs "enum"

#define var 5 will cause you trouble if you have things like mystruct.var.

For example,

struct mystruct {
    int var;
};

#define var 5

int main() {
    struct mystruct foo;
    foo.var = 1;
    return 0;
}

The preprocessor will replace it and the code won't compile. For this reason, traditional coding style suggest all constant #defines uses capital letters to avoid conflict.

Connection string with relative path to the database file

Try this code to the working directory if database file exists like below.

D:\HMProject\DataBase\HMProject.sdf

string Path = Environment.CurrentDirectory;
string[] appPath =  Path.Split(new string[] { "bin" }, StringSplitOptions.None);
AppDomain.CurrentDomain.SetData("DataDirectory", appPath[0]);

Connection string for .sdf file

<add name="LocalDB" connectionString="metadata=res://*/Client.HMProject.csdl|res://*/Client.HMProject.ssdl|res://*/Client.HMProject.msl;provider=System.Data.SqlServerCe.4.0;provider connection string=&quot;Data Source=|DataDirectory|\Database\HMProjectDB.sdf;Password=HMProject;Persist Security Info=False;&quot;" providerName="System.Data.EntityClient" />

Thanks

ck.Nitin (TinTin)

Invalid default value for 'dateAdded'

CURRENT_TIMESTAMP is version specific and is now allowed for DATETIME columns as of version 5.6.

See MySQL docs.

link with target="_blank" does not open in new tab in Chrome

most simple answer

<a onclick="window.open(this.href,'_blank');return false;" href="http://www.foracure.org.au">Some Other Site</a>

it will work

Parse JSON String into a Particular Object Prototype in JavaScript

The current answers contain a lot of hand-rolled or library code. This is not necessary.

  1. Use JSON.parse('{"a":1}') to create a plain object.

  2. Use one of the standardized functions to set the prototype:

    • Object.assign(new Foo, { a: 1 })
    • Object.setPrototypeOf({ a: 1 }, Foo.prototype)

Pointer to incomplete class type is not allowed

You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:

namespace X
{
  namespace Y
  {
    class A;

    void func(A* a) { ... } // incomplete type here!
  }
}

...but, in class A was defined like this:

namespace X
{
  class A { ... };
}

Thus, A was defined as X::A, but I was using it as X::Y::A.

The fix obviously is to move the forward reference to its proper place like so:

namespace X
{
  class A;
  namespace Y
  {
    void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
  }
}

How to create a file in Android?

I decided to write a class from this thread that may be helpful to others. Note that this is currently intended to write in the "files" directory only (e.g. does not write to "sdcard" paths).

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.content.Context;

public class AndroidFileFunctions {

    public static String getFileValue(String fileName, Context context) {
        try {
            StringBuffer outStringBuf = new StringBuffer();
            String inputLine = "";
            /*
             * We have to use the openFileInput()-method the ActivityContext
             * provides. Again for security reasons with openFileInput(...)
             */
            FileInputStream fIn = context.openFileInput(fileName);
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader inBuff = new BufferedReader(isr);
            while ((inputLine = inBuff.readLine()) != null) {
                outStringBuf.append(inputLine);
                outStringBuf.append("\n");
            }
            inBuff.close();
            return outStringBuf.toString();
        } catch (IOException e) {
            return null;
        }
    }

    public static boolean appendFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context, Context.MODE_APPEND);
    }

    public static boolean setFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context,
                Context.MODE_WORLD_READABLE);
    }

    public static boolean writeToFile(String fileName, String value,
            Context context, int writeOrAppendMode) {
        // just make sure it's one of the modes we support
        if (writeOrAppendMode != Context.MODE_WORLD_READABLE
                && writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
                && writeOrAppendMode != Context.MODE_APPEND) {
            return false;
        }
        try {
            /*
             * We have to use the openFileOutput()-method the ActivityContext
             * provides, to protect your file from others and This is done for
             * security-reasons. We chose MODE_WORLD_READABLE, because we have
             * nothing to hide in our file
             */
            FileOutputStream fOut = context.openFileOutput(fileName,
                    writeOrAppendMode);
            OutputStreamWriter osw = new OutputStreamWriter(fOut);
            // Write the string to the file
            osw.write(value);
            // save and close
            osw.flush();
            osw.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public static void deleteFile(String fileName, Context context) {
        context.deleteFile(fileName);
    }
}

Install php-mcrypt on CentOS 6

I was having same issue in centos 6.5

Finaly solution below worked for me

-go to http://dl.fedoraproject.org/pub/epel/6/x86_64/
-search for php-mcrypt(http://dl.fedoraproject.org/pub/epel/6/x86_64/php-mcrypt-5.3.3-3.el6.x86_64.rpm)
-execute wget http://dl.fedoraproject.org/pub/epel/6/x86_64/php-mcrypt-5.3.3-3.el6.x86_64.rpm
-rpm -ivh php-mcrypt-5.3.3-3.el6.x86_64.rpm

if there are any dependencies you can download same using http://dl.fedoraproject.org/pub/epel/6/x86_64/

Pipe output and capture exit status in Bash

(command | tee out.txt; exit ${PIPESTATUS[0]})

Unlike @cODAR's answer this returns the original exit code of the first command and not only 0 for success and 127 for failure. But as @Chaoran pointed out you can just call ${PIPESTATUS[0]}. It is important however that all is put into brackets.

ReferenceError: fetch is not defined

This is the related github issue This bug is related to the 2.0.0 version, you can solve it by simply upgrading to version 2.1.0. You can run npm i [email protected]

Can a div have multiple classes (Twitter Bootstrap)

separate the classes with a space.

<button class="btn btn-success dropdown-toggle active" data-toggle="dropdown">Success <span class="caret"></span></button>

demo: http://jsfiddle.net/wNfcg/

Git: How to squash all commits on branch

You can use tool I've created specifically for this task:

https://github.com/sheerun/git-squash

Basically you need to call git squash master and you're done

How to fill a Javascript object literal with many static key/value pairs efficiently?

Give this a try:

var map = {"aaa": "rrr", "bbb": "ppp"};

How to remove a Gitlab project?

? Just at the bottom of your project settings .?

New version new version

URL : https://gitlab.com/{USER_NAME}/{PROJECT_NAME}/edit

  • Advanced : expand
  • Remove project

What are the differences between a program and an application?

I use the term program to include applications (apps), utilities and even operating systems like windows, linux and mac OS. We kinda need an overall term for all the different terms available. It might be wrong but works for me. :)

How to append rows to an R data frame

My solution is almost the same as the original answer but it doesn't worked for me.

So, I gave names for the columns and it works:

painel <- rbind(painel, data.frame("col1" = xtweets$created_at,
                                   "col2" = xtweets$text))

How to browse for a file in java swing library?

In WebStart and the new 6u10 PlugIn you can use the FileOpenService, even without security permissions. For obvious reasons, you only get the file contents, not the file path.

Using a bitmask in C#

One other really good reason to use a bitmask vs individual bools is as a web developer, when integrating one website to another, we frequently need to send parameters or flags in the querystring. As long as all of your flags are binary, it makes it much simpler to use a single value as a bitmask than send multiple values as bools. I know there are otherways to send data (GET, POST, etc.), but a simple parameter on the querystring is most of the time sufficient for nonsensitive items. Try to send 128 bool values on a querystring to communicate with an external site. This also gives the added ability of not pushing the limit on url querystrings in browsers

How to display request headers with command line curl

the -v option for curl is too verbose in the error output which contains the leading *(status line) or >(request head field) or <(response head field). to get only the request head field:

curl -v -sS www.stackoverflow.com 2>&1 >/dev/null | grep '>' | cut -c1-2 --complement

to get only the request head field:

curl -v -sS www.stackoverflow.com 2>&1 >/dev/null | grep '<' | cut -c1-2 --complement

or to dump it into /tmp/test.txt file with the -D option

curl -D /tmp/test.txt -sS www.stackoverflow.com > /dev/null

in order to filter the -v output, you should direct the error output to terminal and the std output to /dev/null, the -s option is to forbid the progress metering

Highlight Bash/shell code in Markdown files

Using the knitr package:

```{r, engine='bash', code_block_name} ...

E.g.:

```{r, engine='bash', count_lines}
wc -l en_US.twitter.txt
```

You can also use:

  • engine='sh' for shell
  • engine='python' for Python
  • engine='perl', engine='haskell' and a bunch of other C-like languages and even gawk, AWK, etc.

Remove HTML tags from string including &nbsp in C#

I have used the @RaviThapliyal & @Don Rolling's code but made a little modification. Since we are replacing the &nbsp with empty string but instead &nbsp should be replaced with space, so added an additional step. It worked for me like a charm.

public static string FormatString(string value) {
    var step1 = Regex.Replace(value, @"<[^>]+>", "").Trim();
    var step2 = Regex.Replace(step1, @"&nbsp;", " ");
    var step3 = Regex.Replace(step2, @"\s{2,}", " ");
    return step3;
}

Used &nbps without semicolon because it was getting formatted by the Stack Overflow.

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

Answering to myself. From the RequireJS website:

//THIS WILL FAIL
define(['require'], function (require) {
    var namedModule = require('name');
});

This fails because requirejs needs to be sure to load and execute all dependencies before calling the factory function above. [...] So, either do not pass in the dependency array, or if using the dependency array, list all the dependencies in it.

My solution:

// Modules configuration (modules that will be used as Jade helpers)
define(function () {
    return {
        'moment':   'path/to/moment',
        'filesize': 'path/to/filesize',
        '_':        'path/to/lodash',
        '_s':       'path/to/underscore.string'
    };
});

The loader:

define(['jade', 'lodash', 'config'], function (Jade, _, Config) {
    var deps;

    // Dynamic require
    require(_.values(Config), function () {
        deps = _.object(_.keys(Config), arguments);

        // Use deps...
    });
});

C# List of objects, how do I get the sum of a property

Here is example code you could run to make such test:

var f = 10000000;
var p = new int[f];

for(int i = 0; i < f; ++i)
{
    p[i] = i % 2;
}

var time = DateTime.Now;
p.Sum();
Console.WriteLine(DateTime.Now - time);

int x = 0;
time = DateTime.Now;
foreach(var item in p){
   x += item;
}
Console.WriteLine(DateTime.Now - time);

x = 0;
time = DateTime.Now;
for(int i = 0, j = f; i < j; ++i){
   x += p[i];
}
Console.WriteLine(DateTime.Now - time);

The same example for complex object is:

void Main()
{
    var f = 10000000;
    var p = new Test[f];

    for(int i = 0; i < f; ++i)
    {
        p[i] = new Test();
        p[i].Property = i % 2;
    }

    var time = DateTime.Now;
    p.Sum(k => k.Property);
    Console.WriteLine(DateTime.Now - time);

    int x = 0;
    time = DateTime.Now;
    foreach(var item in p){
        x += item.Property;
    }
    Console.WriteLine(DateTime.Now - time);

    x = 0;
    time = DateTime.Now;
    for(int i = 0, j = f; i < j; ++i){
        x += p[i].Property;
    }
    Console.WriteLine(DateTime.Now - time);
}

class Test
{
    public int Property { get; set; }
}

My results with compiler optimizations off are:

00:00:00.0570370 : Sum()
00:00:00.0250180 : Foreach()
00:00:00.0430272 : For(...)

and for second test are:

00:00:00.1450955 : Sum()
00:00:00.0650430 : Foreach()
00:00:00.0690510 : For()

it looks like LINQ is generally slower than foreach(...) but what is weird for me is that foreach(...) appears to be faster than for loop.

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

I was getting similar error in VS2017 while trying to publish my solution to Azure.

This algorithm helped me to resolve it:

  1. Close VS2017
  2. Open C:\Users{your user name}\AppData\Local\Microsoft\VisualStudio\ folder
  3. Rename 15.0_08edcd83 folder
  4. Start VS
  5. Publish works fine!

Note that this will remove your Visual Studio's recent files / projects from it's history and also linking to MS account.

This method is slightly different from the Top answer. Here you don't have to delete other folders except renaming abovementioned one.

Unresolved external symbol in object files

sometimes if a new header file is added, and this error starts coming due to that, you need to add library as well to get rid of unresolved external symbol.

for example:

#include WtsApi32.h

will need:

#pragma comment(lib, "Wtsapi32.lib") 

SQL Server - SELECT FROM stored procedure

Try converting your procedure in to an Inline Function which returns a table as follows:

CREATE FUNCTION MyProc()
RETURNS TABLE AS
RETURN (SELECT * FROM MyTable)

And then you can call it as

SELECT * FROM MyProc()

You also have the option of passing parameters to the function as follows:

CREATE FUNCTION FuncName (@para1 para1_type, @para2 para2_type , ... ) 

And call it

SELECT * FROM FuncName ( @para1 , @para2 )

OpenSSL and error in reading openssl.conf file

I just had a similar error using the openssl.exe from the Apache for windows bin folder. I had the -config flag specified by had a typo in the path of the openssl.cnf file. I think you'll find that

openssl req -config C:\OpenSSL\bin\openssl.conf -x509 -days 365 -newkey rsa:1024 -keyout hostkey.pem -nodes -out hostcert.pem

should be

openssl req -config "C:\OpenSSL\bin\openssl.cnf" -x509 -days 365 -newkey rsa:1024 -keyout hostkey.pem -nodes -out hostcert.pem

Note: the conf should probably be cnf.

Reading/parsing Excel (xls) files with Python

You can use any of the libraries listed here (like Pyxlreader that is based on JExcelApi, or xlwt), plus COM automation to use Excel itself for the reading of the files, but for that you are introducing Office as a dependency of your software, which might not be always an option.

How can I detect whether an iframe is loaded?

I imagine this like that:

<html>
<head>
<script>
var frame_loaded = 0;
function setFrameLoaded()
{
   frame_loaded = 1;
   alert("Iframe is loaded");
}
$('#click').click(function(){
   if(frame_loaded == 1)
    console.log('iframe loaded')
   } else {
    console.log('iframe not loaded')
   }
})
</script>
</head>
<button id='click'>click me</button>

<iframe id='MainPopupIframe' onload='setFrameLoaded();' src='http://...' />...</iframe>

Delete from two tables in one query

Can't you just separate them by a semicolon?

Delete from messages where messageid = '1';
Delete from usersmessages where messageid = '1'

OR

Just use INNER JOIN as below

DELETE messages , usersmessages  FROM messages  INNER JOIN usersmessages  
WHERE messages.messageid= usersmessages.messageid and messages.messageid = '1'

select certain columns of a data table

DataView dv = new DataView(Your DataTable);

DataTable dt = dv.ToTable(true, "Your Specific Column Name");

The dt contains only selected column values.

how to programmatically fake a touch event to a UIButton?

Swift 3:

self.btn.sendActions(for: .touchUpInside)

How to query first 10 rows and next time query other 10 rows from table

Ok. So I think you just need to implement Pagination.

$perPage = 10;

$pageNo = $_GET['page'];

Now find total rows in database.

$totalRows = Get By applying sql query;

$pages = ceil($totalRows/$perPage);    

$offset = ($pageNo - 1) * $perPage + 1

$sql = "SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT ".$offset." ,".$perPage

using nth-child in tables tr td

table tr td:nth-child(2) {
    background: #ccc;
}

Working example: http://jsfiddle.net/gqr3J/

Debug JavaScript in Eclipse

MyEclipse (eclipse based, subscription required) and Webclipse (an eclipse plug-in, currently free), from my company, Genuitec, have newly engineered (as of 2015) JavaScript debugging built in:

enter image description here

You can debug both generic web applications and Node.js files.

How to change title of Activity in Android?

Just an FYI, you can optionally do it from the XML.

In the AndroidManifest.xml, you can set it with

android:label="My Activity Title"

Or

android:label="@string/my_activity_label"

Example:

    <activity
        android:name=".Splash"
        android:label="@string/splash_activity_title" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Array of arrays (Python/NumPy)

You'll have problems creating lists without commas. It shouldn't be too hard to transform your data so that it uses commas as separating character.

Once you have commas in there, it's a relatively simple list creation operations:

array1 = [1,2,3]
array2 = [4,5,6]

array3 = [array1, array2]

array4 = [7,8,9]
array5 = [10,11,12]

array3 = [array3, [array4, array5]]

When testing we get:

print(array3)

[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]

And if we test with indexing it works correctly reading the matrix as made up of 2 rows and 2 columns:

array3[0][1]
[4, 5, 6]

array3[1][1]
[10, 11, 12]

Hope that helps.

Angular2 disable button

May be below code can help:

<button [attr.disabled]="!isValid ? true : null">Submit</button>

Email address validation using ASP.NET MVC data type attributes

[RegularExpression(@"^[A-Za-z0-9]+@([a-zA-Z]+\\.)+[a-zA-Z]{2,6}]&")]

The POM for project is missing, no dependency information available

Change:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

To:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

Appending values to dictionary in Python

If you want to append to the lists of each key inside a dictionary, you can append new values to them using + operator (tested in Python 3.7):

mydict = {'a':[], 'b':[]}
print(mydict)
mydict['a'] += [1,3]
mydict['b'] += [4,6]
print(mydict)
mydict['a'] += [2,8]
print(mydict)

and the output:

{'a': [], 'b': []}
{'a': [1, 3], 'b': [4, 6]}
{'a': [1, 3, 2, 8], 'b': [4, 6]}

mydict['a'].extend([1,3]) will do the job same as + without creating a new list (efficient way).

How to JSON serialize sets?

JSON notation has only a handful of native datatypes (objects, arrays, strings, numbers, booleans, and null), so anything serialized in JSON needs to be expressed as one of these types.

As shown in the json module docs, this conversion can be done automatically by a JSONEncoder and JSONDecoder, but then you would be giving up some other structure you might need (if you convert sets to a list, then you lose the ability to recover regular lists; if you convert sets to a dictionary using dict.fromkeys(s) then you lose the ability to recover dictionaries).

A more sophisticated solution is to build-out a custom type that can coexist with other native JSON types. This lets you store nested structures that include lists, sets, dicts, decimals, datetime objects, etc.:

from json import dumps, loads, JSONEncoder, JSONDecoder
import pickle

class PythonObjectEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (list, dict, str, unicode, int, float, bool, type(None))):
            return JSONEncoder.default(self, obj)
        return {'_python_object': pickle.dumps(obj)}

def as_python_object(dct):
    if '_python_object' in dct:
        return pickle.loads(str(dct['_python_object']))
    return dct

Here is a sample session showing that it can handle lists, dicts, and sets:

>>> data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'}, Decimal('3.14')]

>>> j = dumps(data, cls=PythonObjectEncoder)

>>> loads(j, object_hook=as_python_object)
[1, 2, 3, set(['knights', 'say', 'who', 'ni']), {u'key': u'value'}, Decimal('3.14')]

Alternatively, it may be useful to use a more general purpose serialization technique such as YAML, Twisted Jelly, or Python's pickle module. These each support a much greater range of datatypes.

Laravel requires the Mcrypt PHP extension

Using Ubuntu, just

sudo php5enmod mcrypt

did the trick for me. You don't need to restart Apache since you need to use PHP just from the CLI.

Get variable from PHP to JavaScript

It depends on what type of PHP variable you want to use in Javascript. For example, entire PHP objects with class methods cannot be used in Javascript. You can, however, use the built-in PHP JSON (JavaScript Object Notation) functions to convert simple PHP variables into JSON representations. For more information, please read the following links:

You can generate the JSON representation of your PHP variable and then print it into your Javascript code when the page loads. For example:

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

How does Java resolve a relative path in new File()?

There is a concept of a working directory.
This directory is represented by a . (dot).
In relative paths, everything else is relative to it.

Simply put the . (the working directory) is where you run your program.
In some cases the working directory can be changed but in general this is
what the dot represents. I think this is C:\JavaForTesters\ in your case.

So test\..\test.txt means: the sub-directory test
in my working directory, then one level up, then the
file test.txt. This is basically the same as just test.txt.

For more details check here.

http://docs.oracle.com/javase/7/docs/api/java/io/File.html

http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

python: how to send mail with TO, CC and BCC?

It did not worked for me until i created:

#created cc string
cc = ""[email protected];
#added cc to header
msg['Cc'] = cc

and than added cc in recipient [list] like:

s.sendmail(me, [you,cc], msg.as_string())

How can I select an element in a component template?

In case you are using Angular Material, you can take advantage of cdkFocusInitial directive.

Example: <input matInput cdkFocusInitial>

Read more here: https://material.angular.io/cdk/a11y/overview#regions

How do I store the select column in a variable?

select @EmpID = ID from dbo.Employee

Or

set @EmpID =(select id from dbo.Employee)

Note that the select query might return more than one value or rows. so you can write a select query that must return one row.

If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable

DECLARE @sampleTable TABLE(column1 type1)
INSERT INTO @sampleTable
SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..

As table type variable do not exist in Oracle and others, you would have to define it:

DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;

-- Then to declare a TABLE variable of this type: variable_name type_name;

-- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text';

-- Where 'n' is the index value

Changing button text onclick

Or more simple without having to name the element (with 'button' element):

<button onclick="toggleLog(this)">Stop logs</button>

and script :

var bWriteLog = true;

function toggleLog(elt) {

  bWriteLog = !bWriteLog;
  elt.innerHTML = bWriteLog ? 'Stop logs' : 'Watch logs';
}

POST JSON to API using Rails and HTTParty

I solved this by adding .to_json and some heading information

@result = HTTParty.post(@urlstring_to_post.to_str, 
    :body => { :subject => 'This is the screen name', 
               :issue_type => 'Application Problem', 
               :status => 'Open', 
               :priority => 'Normal', 
               :description => 'This is the description for the problem'
             }.to_json,
    :headers => { 'Content-Type' => 'application/json' } )

Python sys.argv lists and indexes

As explained in the different asnwers already, sys.argv contains the command line arguments that called your Python script.

However, Python comes with libraries that help you parse command line arguments very easily. Namely, the new standard argparse. Using argparse would spare you the need to write a lot of boilerplate code.

Limiting the number of characters in a string, and chopping off the rest

You can also use String.format("%3.3s", "abcdefgh"). The first digit is the minimum length (the string will be left padded if it's shorter), the second digit is the maxiumum length and the string will be truncated if it's longer. So

System.out.printf("'%3.3s' '%3.3s'", "abcdefgh", "a");

will produce

'abc' '  a'

(you can remove quotes, obviously).

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

In the first example, you are reassigning the variable a, while in the second one you are modifying the data in-place, using the += operator.

See the section about 7.2.1. Augmented assignment statements :

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

+= operator calls __iadd__. This function makes the change in-place, and only after its execution, the result is set back to the object you are "applying" the += on.

__add__ on the other hand takes the parameters and returns their sum (without modifying them).

Deleting an SVN branch

From the working copy:

svn rm branches/features
svn commit -m "delete stale feature branch"

TypeError: 'builtin_function_or_method' object is not subscriptable

This error arises when you don't use brackets with pop operation. Write the code in this manner.

listb.pop(0)

This is a valid python expression.

__proto__ VS. prototype in JavaScript

prototype is a property of a Function object. It is the prototype of objects constructed by that function.

__proto__ is internal property of an object, pointing to its prototype. Current standards provide an equivalent Object.getPrototypeOf(O) method, though de facto standard __proto__ is quicker.

You can find instanceof relationships by comparing a function's prototype to an object's __proto__ chain, and you can break these relationships by changing prototype.

function Point(x, y) {
    this.x = x;
    this.y = y;
}

var myPoint = new Point();

// the following are all true
myPoint.__proto__ == Point.prototype
myPoint.__proto__.__proto__ == Object.prototype
myPoint instanceof Point;
myPoint instanceof Object;

Here Point is a constructor function, it builds an object (data structure) procedurally. myPoint is an object constructed by Point() so Point.prototype gets saved to myPoint.__proto__ at that time.

How to "properly" print a list?

Using .format for string formatting,

mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))

Output:

[x, 3, b]

Explanation:

  1. map is used to map each element of the list to string type.
  2. The elements are joined together into a string with , as separator.
  3. We use [ and ] in the print statement to show the list braces.

Reference: .format for string formatting PEP-3101

error: src refspec master does not match any

Setup username and password in the git config

In terminal, type

vi .git/config

edit url with

url = https://username:[email protected]/username/repo.git

type :wq to save

What are some uses of template template parameters?

Actually, usecase for template template parameters is rather obvious. Once you learn that C++ stdlib has gaping hole of not defining stream output operators for standard container types, you would proceed to write something like:

template<typename T>
static inline std::ostream& operator<<(std::ostream& out, std::list<T> const& v)
{
    out << '[';
    if (!v.empty()) {
        for (typename std::list<T>::const_iterator i = v.begin(); ;) {
            out << *i;
            if (++i == v.end())
                break;
            out << ", ";
        }
    }
    out << ']';
    return out;
}

Then you'd figure out that code for vector is just the same, for forward_list is the same, actually, even for multitude of map types it's still just the same. Those template classes don't have anything in common except for meta-interface/protocol, and using template template parameter allows to capture the commonality in all of them. Before proceeding to write a template though, it's worth to check a reference to recall that sequence containers accept 2 template arguments - for value type and allocator. While allocator is defaulted, we still should account for its existence in our template operator<<:

template<template <typename, typename> class Container, class V, class A>
std::ostream& operator<<(std::ostream& out, Container<V, A> const& v)
...

Voila, that will work automagically for all present and future sequence containers adhering to the standard protocol. To add maps to the mix, it would take a peek at reference to note that they accept 4 template params, so we'd need another version of the operator<< above with 4-arg template template param. We'd also see that std:pair tries to be rendered with 2-arg operator<< for sequence types we defined previously, so we would provide a specialization just for std::pair.

Btw, with C+11 which allows variadic templates (and thus should allow variadic template template args), it would be possible to have single operator<< to rule them all. For example:

#include <iostream>
#include <vector>
#include <deque>
#include <list>

template<typename T, template<class,class...> class C, class... Args>
std::ostream& operator <<(std::ostream& os, const C<T,Args...>& objs)
{
    os << __PRETTY_FUNCTION__ << '\n';
    for (auto const& obj : objs)
        os << obj << ' ';
    return os;
}

int main()
{
    std::vector<float> vf { 1.1, 2.2, 3.3, 4.4 };
    std::cout << vf << '\n';

    std::list<char> lc { 'a', 'b', 'c', 'd' };
    std::cout << lc << '\n';

    std::deque<int> di { 1, 2, 3, 4 };
    std::cout << di << '\n';

    return 0;
}

Output

std::ostream &operator<<(std::ostream &, const C<T, Args...> &) [T = float, C = vector, Args = <std::__1::allocator<float>>]
1.1 2.2 3.3 4.4 
std::ostream &operator<<(std::ostream &, const C<T, Args...> &) [T = char, C = list, Args = <std::__1::allocator<char>>]
a b c d 
std::ostream &operator<<(std::ostream &, const C<T, Args...> &) [T = int, C = deque, Args = <std::__1::allocator<int>>]
1 2 3 4 

How to create a batch file to run cmd as administrator

Press Ctrl+Shift and double-click a shortcut to run as an elevated process.

Works from the start menu as well.

Android - How to achieve setOnClickListener in Kotlin?

Here's the solution. Your code will like this:

button.setOnClickListener {
            //your code here
        }

No need to add anything. like below:

val button = findViewById<Button>(R.id.Button)
button.setOnClickListener {

}

TypeScript - Append HTML to container element in Angular 2

There is a better solution to this answer that is more Angular based.

  1. Save your string in a variable in the .ts file

    MyStrings = ["one","two","three"]

  2. In the html file use *ngFor.

    <div class="one" *ngFor="let string of MyStrings; let i = index"> <div class="two">{{string}}</div> </div>

  3. if you want to dynamically insert the div element, just push more strings into the MyStrings array

    myFunction(nextString){ this.MyString.push(nextString) }

this way every time you click the button containing the myFunction(nextString) you effectively add another class="two" div which acts the same way as inserting it into the DOM with pure javascript.

What do the different readystates in XMLHttpRequest mean, and how can I use them?

kieron's answer contains w3schools ref. to which nobody rely , bobince's answer gives link , which actually tells native implementation of IE ,

so here is the original documentation quoted to rightly understand what readystate represents :

The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:

UNSENT (numeric value 0)
The object has been constructed.

OPENED (numeric value 1)
The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

LOADING (numeric value 3)
The response entity body is being received.

DONE (numeric value 4)
The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

Please Read here : W3C Explaination Of ReadyState

How to disable an input type=text?

document.getElementById('foo').disabled = true;

or

document.getElementById('foo').readOnly = true;

Note that readOnly should be in camelCase to work correctly in Firefox (magic).

Demo: https://jsfiddle.net/L96svw3c/ -- somewhat explains the difference between disabled and readOnly.

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.

Why do you need to put #!/bin/bash at the beginning of a script file?

Also you will see some other parameters after #!/bin/bash, for example
#!/bin/bash -v -x
read this to get more idea.
https://unix.stackexchange.com/questions/124272/what-do-the-arguments-v-and-x-mean-to-bash .

How can I select all children of an element except the last child?

Make it simple:

You can apply your style to all the div and re-initialize the last one with :last-child:

for example in CSS:

.yourclass{
    border: 1px solid blue;
}
.yourclass:last-child{
    border: 0;
}

or in SCSS:

.yourclass{
    border: 1px solid rgba(255, 255, 255, 1);
    &:last-child{
        border: 0;
    }
}
  • easy to read/remember
  • fast to execute
  • browser compatible (IE9+ since it's still CSS3)

How to append a newline to StringBuilder

Another option is to use Apache Commons StrBuilder, which has the functionality that's lacking in StringBuilder.

StrBuilder.appendLn()

As of version 3.6 StrBuilder has been deprecated in favour of TextStringBuilder which has the same functionality

jQuery click event on radio button doesn't get fired

There are a couple of things wrong in this code:

  1. You're using <input> the wrong way. You should use a <label> if you want to make the text behind it clickable.
  2. It's setting the enabled attribute, which does not exist. Use disabled instead.
  3. If it would be an attribute, it's value should not be false, use disabled="disabled" or simply disabled without a value.
  4. If checking for someone clicking on a form event that will CHANGE it's value (like check-boxes and radio-buttons), use .change() instead.

I'm not sure what your code is supposed to do. My guess is that you want to disable the input field with class roomNumber once someone selects "Walk in" (and possibly re-enable when deselected). If so, try this code:

HTML:

<form class="type">
    <p>
        <input type="radio" name="type" checked="checked" id="guest" value="guest" />
        <label for="guest">In House</label>
    </p>
    <p>
        <input type="radio" name="type" id="walk_in" value="walk_in" />
        <label for="walk_in">Walk in</label>
    </p>
    <p>
        <input type="text" name="roomnumber" class="roomNumber" value="12345" />
    </p>
</form>

Javascript:

$("form input:radio").change(function () {
    if ($(this).val() == "walk_in") {
        // Disable your roomnumber element here
        $('.roomNumber').attr('disabled', 'disabled');
    } else {
        // Re-enable here I guess
        $('.roomNumber').removeAttr('disabled');
    }
});

I created a fiddle here: http://jsfiddle.net/k28xd/1/

How to update a value, given a key in a hashmap?

The cleaner solution without NullPointerException is:

map.replace(key, map.get(key) + 1);

How do I obtain a Query Execution Plan in SQL Server?

Assuming you're using Microsoft SQL Server Management Studio

  • For Estimated Query Plan you can press Ctrl + L or the following button.

enter image description here

  • For Actual Query Plan, you can press Ctrl + M or the following button before executing query.

enter image description here

  • For Live Query Plan, (only in SSMS 2016) use the following button before executing query.

enter image description here

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

Converting string to Date and DateTime

If you wish to accept dates using American ordering (month, date, year) for European style formats (using dash or period as day, month, year) while still accepting other formats, you can extend the DateTime class:

/**
 * Quietly convert European format to American format
 *
 * Accepts m-d-Y, m-d-y, m.d.Y, m.d.y, Y-m-d, Y.m.d
 * as well as all other built-in formats
 * 
 */
class CustomDateTime extends DateTime 
{
  public function __construct(string $time="now", DateTimeZone $timezone = null) 
  {
    // convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y (substr avoids microtime error)
    $time = str_replace(['-','.'], '/', substr($time, 0, 10)) . substr($time, 10 );

    parent::__construct($time, $timezone);
  }
}

// usage:
$date = new CustomDateTime('7-24-2019');
print $date->format('Y-m-d');

// => '2019-07-24'

Or, you can make a function to accept m-d-Y and output Y-m-d:

/**
 * Accept dates in various m, d, y formats and return as Y-m-d
 * 
 * Changes PHP's default behaviour for dates with dashes or dots.
 * Accepts:
 *   m-d-y, m-d-Y, Y-m-d,
 *   m.d.y, m.d.Y, Y.m.d,
 *   m/d/y, m/d/Y, Y/m/d,
 *   ... and all other formats natively supported 
 * 
 * Unsupported formats or invalid dates will generate an Exception
 * 
 * @see https://www.php.net/manual/en/datetime.formats.date.php PHP formats supported
 * @param  string $d various representations of date
 * @return string    Y-m-d or '----' for null or blank
 */
function asYmd($d) {
  if(is_null($d) || $d=='') { return '----'; }

  // convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y
  $d = str_replace(['-','.'], '/', $d);

  return (new DateTime($d))->format('Y-m-d');
}

// usage:

<?= asYmd('7-24-2019') ?>

// or

<?php echo asYmd('7-24-2019'); ?>

How can I verify if an AD account is locked?

If you want to check via command line , then use command "net user username /DOMAIN"

enter image description here

Width equal to content

Using display:inline-block; it will work only for a correct sentence with spaces like

_x000D_
_x000D_
#container {_x000D_
    width: 30%;_x000D_
    background-color: grey;_x000D_
    overflow:hidden;_x000D_
    margin:10px;_x000D_
}_x000D_
#container p{_x000D_
    display:inline-block;_x000D_
    background-color: green;_x000D_
}
_x000D_
<h5>Correct sentence with spaces </h5>_x000D_
<div id="container">_x000D_
    <p>Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1</p>_x000D_
</div>_x000D_
<h5>No specaes (not working )</h5>_x000D_
<div id="container">_x000D_
    <p>SampleSampleSampleSampleSampleSampleSampleSampleSampleSampleSamplesadasdsadasdasdsa</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why not using word-wrap: break-word;? it's made to allow long words to be able to break and wrap onto the next line.

_x000D_
_x000D_
#container {_x000D_
    width: 30%;_x000D_
    background-color: grey;_x000D_
    overflow:hidden;_x000D_
    margin:10px;_x000D_
}_x000D_
#container p{_x000D_
   word-wrap: break-word;_x000D_
    background-color: green;_x000D_
}
_x000D_
<h5> Correct sentence with spaces </h5>_x000D_
<div id="container">_x000D_
    <p>Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1</p>_x000D_
</div>_x000D_
<h5>No specaes</h5>_x000D_
<div id="container">_x000D_
    <p>SampleSampleSampleSampleSampleSampleSampleSampleSampleSampleSamplesadasdsadasdasdsa</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why am I getting "Thread was being aborted" in ASP.NET?

Nope, ThreadAbortException is thrown by a simple Response.Redirect

How can I pass a username/password in the header to a SOAP WCF Service

There is probably a smarter way, but you can add the headers manually like this:

var client = new IdentityProofingService.IdentityProofingWSClient();

using (new OperationContextScope(client.InnerChannel))
{
    OperationContext.Current.OutgoingMessageHeaders.Add(
        new SecurityHeader("UsernameToken-49", "12345/userID", "password123"));
    client.invokeIdentityService(new IdentityProofingRequest());
}

Here, SecurityHeader is a custom implemented class, which needs a few other classes since I chose to use attributes to configure the XML serialization:

public class SecurityHeader : MessageHeader
{
    private readonly UsernameToken _usernameToken;

    public SecurityHeader(string id, string username, string password)
    {
        _usernameToken = new UsernameToken(id, username, password);
    }

    public override string Name
    {
        get { return "Security"; }
    }

    public override string Namespace
    {
        get { return "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; }
    }

    protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(UsernameToken));
        serializer.Serialize(writer, _usernameToken);
    }
}


[XmlRoot(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")]
public class UsernameToken
{
    public UsernameToken()
    {
    }

    public UsernameToken(string id, string username, string password)
    {
        Id = id;
        Username = username;
        Password = new Password() {Value = password};
    }

    [XmlAttribute(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")]
    public string Id { get; set; }

    [XmlElement]
    public string Username { get; set; }

    [XmlElement]
    public Password Password { get; set; }
}

public class Password
{
    public Password()
    {
        Type = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";
    }

    [XmlAttribute]
    public string Type { get; set; }

    [XmlText]
    public string Value { get; set; }
}

I have not added the Nonce bit to the UsernameToken XML, but it is very similar to the Password one. The Created element also needs to be added still, but it's a simple [XmlElement].

How to store array or multiple values in one column

You have a couple of questions here, so I'll address them separately:

I need to store a number of selected items in one field in a database

My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).

You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:

Base table (what you have now):

| id primary_key sequence
| -- other columns here.

Items table:

| id primary_key sequence
| descript VARCHAR(30) UNIQUE

Map table:

| base_id  bigint
| items_id bigint

Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.

And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.

What format should I use store the data?

If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.

What column type should I use store the data?

Personally, I would use TEXT. It does not sound like you'd gain much by making this a BLOB, and TEXT, in my experience, is easier to read if you're using some form of IDE.

How to style UITextview to like Rounded Rect text field?

I wanted the real deal, so I add UIImageView as a subview of the UITextView. This matches the native border on a UITextField, including the gradient from top to bottom:

textView.backgroundColor = [UIColor clearColor];
UIImageView *borderView = [[UIImageView alloc] initWithFrame: CGRectMake(0, 0, textView.frame.size.width, textView.frame.size.height)];
borderView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
UIImage *textFieldImage = [[UIImage imageNamed:@"TextField.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(15, 8, 15, 8)];
borderView.image = textFieldImage;
[textField addSubview: borderView];
[textField sendSubviewToBack: borderView];

These are the images I use:

enter image description here enter image description here

MongoDB query with an 'or' condition

Using a $where query will be slow, in part because it can't use indexes. For this sort of problem, I think it would be better to store a high value for the "expires" field that will naturally always be greater than Now(). You can either store a very high date millions of years in the future, or use a separate type to indicate never. The cross-type sort order is defined at here.

An empty Regex or MaxKey (if you language supports it) are both good choices.

How to Import Excel file into mysql Database from PHP

For >= 2nd row values insert into table-

$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";

$count = 0;                                         // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
    //print_r($emapData);
    //exit();
    $count++;                                      // add this line

    if($count>1){                                  // add this line
      $sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
      mysql_query($sql);
    }                                              // add this line
}

Combining paste() and expression() functions in plot labels

EDIT: added a new example for ggplot2 at the end

See ?plotmath for the different mathematical operations in R

You should be able to use expression without paste. If you use the tilda (~) symbol within the expression function it will assume there is a space between the characters, or you could use the * symbol and it won't put a space between the arguments

Sometimes you will need to change the margins in you're putting superscripts on the y-axis.

par(mar=c(5, 4.3, 4, 2) + 0.1)
plot(1:10, xlab = expression(xLab ~ x^2 ~ m^-2),
     ylab = expression(yLab ~ y^2 ~ m^-2),
     main="Plot 1")

enter image description here

plot(1:10, xlab = expression(xLab * x^2 * m^-2),
     ylab = expression(yLab * y^2 * m^-2),
     main="Plot 2")

enter image description here

plot(1:10, xlab = expression(xLab ~ x^2 * m^-2),
     ylab = expression(yLab ~ y^2 * m^-2),
     main="Plot 3")

enter image description here

Hopefully you can see the differences between plots 1, 2 and 3 with the different uses of the ~ and * symbols. An extra note, you can use other symbols such as plotting the degree symbol for temperatures for or mu, phi. If you want to add a subscript use the square brackets.

plot(1:10, xlab = expression('Your x label' ~ mu[3] * phi),
     ylab = expression("Temperature (" * degree * C *")"))

enter image description here

Here is a ggplot example using expression with a nonsense example

require(ggplot2)

Or if you have the pacman library installed you can use p_load to automatically download and load and attach add-on packages

# require(pacman)
# p_load(ggplot2)

data = data.frame(x = 1:10, y = 1:10)

ggplot(data, aes(x,y)) + geom_point() + 
  xlab(expression(bar(yourUnits) ~ g ~ m^-2 ~ OR ~ integral(f(x)*dx, a,b))) + 
  ylab(expression("Biomass (g per" ~ m^3 *")")) + theme_bw()

enter image description here

Typescript - multidimensional array initialization

If you want to do it typed:

class Something {

  areas: Area[][];

  constructor() {
    this.areas = new Array<Array<Area>>();
    for (let y = 0; y <= 100; y++) {
      let row:Area[]  = new Array<Area>();      
      for (let x = 0; x <=100; x++){
        row.push(new Area(x, y));
      }
      this.areas.push(row);
    }
  }
}

How can I delay a :hover effect in CSS?

For a more aesthetic appearance :) can be:

left:-9999em; 
top:-9999em; 

position for .sNv2 .nav UL can be replaced by z-index:-1 and z-index:1 for .sNv2 .nav LI:Hover UL

Where in memory are my variables stored in C?

  • Variables/automatic variables ---> stack section
  • Dynamically allocated variables ---> heap section
  • Initialised global variables -> data section
  • Uninitialised global variables -> data section (bss)
  • Static variables -> data section
  • String constants -> text section/code section
  • Functions -> text section/code section
  • Text code -> text section/code section
  • Registers -> CPU registers
  • Command line inputs -> environmental/command line section
  • Environmental variables -> environmental/command line section

Capture Signature using HTML5 and iPad

The options already listed are very good, however here a few more on this topic that I've researched and came across.

1) http://perfectionkills.com/exploring-canvas-drawing-techniques/
2) http://mcc.id.au/2010/signature.html
3) https://zipso.net/a-simple-touchscreen-sketchpad-using-javascript-and-html5/

And as always you may want to save the canvas to image:
http://www.html5canvastutorials.com/advanced/html5-canvas-save-drawing-as-an-image/

good luck and happy signing

How to tell if a file is git tracked (by shell exit code)?

I don't know of any git command that gives a "bad" exit code, but it seems like an easy way to do it would be to use a git command that gives no output for a file that isn't tracked, such as git-log or git-ls-files. That way you don't really have to do any parsing, you can run it through another simple utility like grep to see if there was any output.

For example,

git-ls-files test_file.c | grep .

will exit with a zero code if the file is tracked, but a exit code of one if the file is not tracked.

Search an Oracle database for tables with specific column names?

The data you want is in the "cols" meta-data table:

SELECT * FROM COLS WHERE COLUMN_NAME = 'id'

This one will give you a list of tables that have all of the columns you want:

select distinct
  C1.TABLE_NAME
from
  cols c1
  inner join
  cols c2
  on C1.TABLE_NAME = C2.TABLE_NAME
  inner join
  cols c3
  on C2.TABLE_NAME = C3.TABLE_NAME
  inner join
  cols c4
  on C3.TABLE_NAME = C4.TABLE_NAME  
  inner join
  tab t
  on T.TNAME = C1.TABLE_NAME
where T.TABTYPE = 'TABLE' --could be 'VIEW' if you wanted
  and upper(C1.COLUMN_NAME) like upper('%id%')
  and upper(C2.COLUMN_NAME) like upper('%fname%')
  and upper(C3.COLUMN_NAME) like upper('%lname%')
  and upper(C4.COLUMN_NAME) like upper('%address%')  

To do this in a different schema, just specify the schema in front of the table, as in

SELECT * FROM SCHEMA1.COLS WHERE COLUMN_NAME LIKE '%ID%';

If you want to combine the searches of many schemas into one output result, then you could do this:

SELECT DISTINCT
  'SCHEMA1' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA1.COLS
WHERE COLUMN_NAME LIKE '%ID%'
UNION
SELECT DISTINCT
  'SCHEMA2' AS SCHEMA_NAME
 ,TABLE_NAME
FROM SCHEMA2.COLS
WHERE COLUMN_NAME LIKE '%ID%'

Pandas: ValueError: cannot convert float NaN to integer

I know this has been answered but wanted to provide alternate solution for anyone in the future:

You can use .loc to subset the dataframe by only values that are notnull(), and then subset out the 'x' column only. Take that same vector, and apply(int) to it.

If column x is float:

df.loc[df['x'].notnull(), 'x'] = df.loc[df['x'].notnull(), 'x'].apply(int)

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

You can fire the event manually after changing the selected option on the onclick event doing: document.getElementById("sel").onchange();

Factorial using Recursion in Java

result is a local variable of the fact method. So each time the fact method is called, the result is stored in a different variable than the previous fact invocation.

So when fact is invoked with 3 as argument, you can imagine that its result is

 result3 = fact(2) * 3
 result3 = result2 * 3
 result3 = 1 * 2 * 3

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

Is there a difference between "throw" and "throw ex"?

Yes, there is a difference;

  • throw ex resets the stack trace (so your errors would appear to originate from HandleException)
  • throw doesn't - the original offender would be preserved.

    static void Main(string[] args)
    {
        try
        {
            Method2();
        }
        catch (Exception ex)
        {
            Console.Write(ex.StackTrace.ToString());
            Console.ReadKey();
        }
    }
    
    private static void Method2()
    {
        try
        {
            Method1();
        }
        catch (Exception ex)
        {
            //throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
            throw ex;
        }
    }
    
    private static void Method1()
    {
        try
        {
            throw new Exception("Inside Method1");
        }
        catch (Exception)
        {
            throw;
        }
    }
    

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

Node.js Write a line into a .txt file

Inserting data into the middle of a text file is not a simple task. If possible, you should append it to the end of your file.

The easiest way to append data some text file is to use build-in fs.appendFile(filename, data[, options], callback) function from fs module:

var fs = require('fs')
fs.appendFile('log.txt', 'new data', function (err) {
  if (err) {
    // append failed
  } else {
    // done
  }
})

But if you want to write data to log file several times, then it'll be best to use fs.createWriteStream(path[, options]) function instead:

var fs = require('fs')
var logger = fs.createWriteStream('log.txt', {
  flags: 'a' // 'a' means appending (old data will be preserved)
})

logger.write('some data') // append string to your file
logger.write('more data') // again
logger.write('and more') // again

Node will keep appending new data to your file every time you'll call .write, until your application will be closed, or until you'll manually close the stream calling .end:

logger.end() // close string

Hunk #1 FAILED at 1. What's that mean?

In some cases, there is no difference in file versions, but only in indentation, spacing, line ending or line numbers.

To patch despite those differences, it's possible to use the following two arguments :

--ignore-whitespace : It ignores whitespace differences (indentation, etc).

--fuzz 3 : the "--fuzz X" option sets the maximum fuzz factor to lines. This option only applies to context and unified diffs; it ignores up to X lines while looking for the place to install a hunk. Note that a larger fuzz factor increases the odds of making a faulty patch. The default fuzz factor is 2; there is no point to setting it to more than the number of lines of context in the diff, ordinarily 3.

Don't forget to user "--dry-run" : It'll try the patch without applying it.

Example :

patch --verbose --dry-run --ignore-whitespace --fuzz 3 < /path/to/patch.patch

More informations about Fuzz :

https://www.gnu.org/software/diffutils/manual/html_node/Inexact.html

Does React Native styles support gradients?

Here is a good choice for gradients for both platforms iOS and Android:

https://github.com/react-native-community/react-native-linear-gradient

There are others approaches like expo, however react-native-linear-gradient have worked better for me.

<LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']} style={styles.linearGradient}>
  <Text style={styles.buttonText}>
    Sign in with Facebook
  </Text>
</LinearGradient>

// Later on in your styles..
var styles = StyleSheet.create({
  linearGradient: {
    flex: 1,
    paddingLeft: 15,
    paddingRight: 15,
    borderRadius: 5
  },
  buttonText: {
    fontSize: 18,
    fontFamily: 'Gill Sans',
    textAlign: 'center',
    margin: 10,
    color: '#ffffff',
    backgroundColor: 'transparent',
  },
});

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

Set AUTO_INCREMENT to PRIMARY KEY

Set mouse focus and move cursor to end of input using jQuery

Chris Coyier has a mini jQuery plugin for this which works perfectly well: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/

It uses setSelectionRange if supported, else has a solid fallback.

jQuery.fn.putCursorAtEnd = function() {
  return this.each(function() {
    $(this).focus()
    // If this function exists...
    if (this.setSelectionRange) {
      // ... then use it (Doesn't work in IE)
      // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
      var len = $(this).val().length * 2;
      this.setSelectionRange(len, len);
    } else {
      // ... otherwise replace the contents with itself
      // (Doesn't work in Google Chrome)
      $(this).val($(this).val());
    }
    // Scroll to the bottom, in case we're in a tall textarea
    // (Necessary for Firefox and Google Chrome)
    this.scrollTop = 999999;
  });
};

Then you can just do:

input.putCursorAtEnd();

App can't be opened because it is from an unidentified developer

Right-click (or control-click) the application in question and choose "Open"

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

AngularJS: ng-model not binding to ng-checked for checkboxes

Can Declare As the in ng-init also getting true

<!doctype html>
<html ng-app="plunker" >
  <head>
    <meta charset="utf-8">
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
    <script src="app.js"></script>
  </head>
  <body ng-controller="MainCtrl" ng-init="testModel['item1']= true">
    <label><input type="checkbox" name="test" ng-model="testModel['item1']"  /> Testing</label><br />
    <label><input type="checkbox" name="test" ng-model="testModel['item2']" /> Testing 2</label><br />
    <label><input type="checkbox" name="test" ng-model="testModel['item3']" /> Testing 3</label><br />
    <input type="button" ng-click="submit()" value="Submit" />
  </body>
</html>

And You Can Select the First One and Object Also Shown here true,false,flase

Adding items to a JComboBox

Wrap the values in a class and override the toString() method.

class ComboItem
{
    private String key;
    private String value;

    public ComboItem(String key, String value)
    {
        this.key = key;
        this.value = value;
    }

    @Override
    public String toString()
    {
        return key;
    }

    public String getKey()
    {
        return key;
    }

    public String getValue()
    {
        return value;
    }
}

Add the ComboItem to your comboBox.

comboBox.addItem(new ComboItem("Visible String 1", "Value 1"));
comboBox.addItem(new ComboItem("Visible String 2", "Value 2"));
comboBox.addItem(new ComboItem("Visible String 3", "Value 3"));

Whenever you get the selected item.

Object item = comboBox.getSelectedItem();
String value = ((ComboItem)item).getValue();

vi/vim editor, copy a block (not usual action)

Another option which may be easier to remember would be to place marks on the two lines with ma and mb, then run :'a,'byank.

Many different ways to accomplish this task, just offering another.

bootstrap popover not showing on top of all elements

<div class="testDiv">
<a tabindex = "-1" id="testPop" title="stuff" data-toggle="popover" data-trigger="focus" data-placement="bottom" data-container=".testDiv">
 <i class="fa fa-info-circle"></i>
</a>

</div>

Above answers were helpful as setting value in data-container did the job but if i set data-container="body" then it doesn't align properly in my case. So i specified the class of the parent div of popover and it worked fine.

html

data-container=".testDiv"

js

$("#testPop").popover({container: '.testDiv'})

Using a batch to copy from network drive to C: or D: drive

Just do the following change

echo off
cls

echo Would you like to do a backup?

pause

copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER

pause

regex.test V.S. string.match to know if a string matches a regular expression

Don't forget to take into consideration the global flag in your regexp :

var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi');    // => true
reg.test('abcdefghi');    // => false <=

This is because Regexp keeps track of the lastIndex when a new match is found.

How do I get the number of elements in a list?

Besides len you can also use operator.length_hint (requires Python 3.4+). For a normal list both are equivalent, but length_hint makes it possible to get the length of a list-iterator, which could be useful in certain circumstances:

>>> from operator import length_hint
>>> l = ["apple", "orange", "banana"]
>>> len(l)
3
>>> length_hint(l)
3

>>> list_iterator = iter(l)
>>> len(list_iterator)
TypeError: object of type 'list_iterator' has no len()
>>> length_hint(list_iterator)
3

But length_hint is by definition only a "hint", so most of the time len is better.

I've seen several answers suggesting accessing __len__. This is all right when dealing with built-in classes like list, but it could lead to problems with custom classes, because len (and length_hint) implement some safety checks. For example, both do not allow negative lengths or lengths that exceed a certain value (the sys.maxsize value). So it's always safer to use the len function instead of the __len__ method!

MongoDB running but can't connect using shell

I think there is some default config what is missing in this version of mongoDb client. Try to run:

mongo 127.0.0.1:27017

It's strange, but then I've experienced the issue went away :) (so the simple command 'mongo' w/o any params started to work again for me)

[Ubuntu Linux 11.10 x64 / MongoDB 2.0.1]

How do I convert a file path to a URL in ASP.NET

The simple solution seems to be to have a temporary location within the website that you can access easily with URL and then you can move files to the physical location when you need to save them.

Checking if sys.argv[x] is defined

I use this - it never fails:

startingpoint = 'blah'
if sys.argv[1:]:
   startingpoint = sys.argv[1]

Load a bitmap image into Windows Forms using open file dialog

You have to create an instance of the Bitmap class, using the constructor overload that loads an image from a file on disk. As your code is written now, you're trying to use the PictureBox.Image property as if it were a method.

Change your code to look like this (also taking advantage of the using statement to ensure proper disposal, rather than manually calling the Dispose method):

private void button1_Click(object sender, EventArgs e)
{
    // Wrap the creation of the OpenFileDialog instance in a using statement,
    // rather than manually calling the Dispose method to ensure proper disposal
    using (OpenFileDialog dlg = new OpenFileDialog())
    {
        dlg.Title = "Open Image";
        dlg.Filter = "bmp files (*.bmp)|*.bmp";

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            PictureBox PictureBox1 = new PictureBox();

            // Create a new Bitmap object from the picture file on disk,
            // and assign that to the PictureBox.Image property
            PictureBox1.Image = new Bitmap(dlg.FileName);
        }
    }
}

Of course, that's not going to display the image anywhere on your form because the picture box control that you've created hasn't been added to the form. You need to add the new picture box control that you've just created to the form's Controls collection using the Add method. Note the line added to the above code here:

private void button1_Click(object sender, EventArgs e)
{
    using (OpenFileDialog dlg = new OpenFileDialog())
    {
        dlg.Title = "Open Image";
        dlg.Filter = "bmp files (*.bmp)|*.bmp";

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            PictureBox PictureBox1 = new PictureBox();
            PictureBox1.Image = new Bitmap(dlg.FileName);

            // Add the new control to its parent's controls collection
            this.Controls.Add(PictureBox1);
        }
    }
}

How do I authenticate a WebClient request?

This helped me to call API that was using cookie authentication. I have passed authorization in header like this:

request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));

complete code:

// utility method to read the cookie value:
        public static string ReadCookie(string cookieName)
        {
            var cookies = HttpContext.Current.Request.Cookies;
            var cookie = cookies.Get(cookieName);
            if (cookie != null)
                return cookie.Value;
            return null;
        }

// using statements where you are creating your webclient
using System.Web.Script.Serialization;
using System.Net;
using System.IO;

// WebClient:

var requestUrl = "<API_url>";
var postRequest = new ClassRoom { name = "kushal seth" };

using (var webClient = new WebClient()) {
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      byte[] requestData = Encoding.ASCII.GetBytes(serializer.Serialize(postRequest));
      HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
      request.Method = "POST";
      request.ContentType = "application/json";                        
      request.ContentLength = requestData.Length;
      request.ContentType = "application/json";
      request.Expect = "application/json";
      request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));
      request.GetRequestStream().Write(requestData, 0, requestData.Length);

      using (var response = (HttpWebResponse)request.GetResponse()) {
         var reader = new StreamReader(response.GetResponseStream());
         var objText = reader.ReadToEnd(); // objText will have the value
      }
}


python-pandas and databases like mysql

This should work just fine.

import MySQLdb as mdb
import pandas as pd
con = mdb.connect(‘127.0.0.1’, ‘root’, ‘password’, ‘database_name’);
with con:
 cur = con.cursor()
 cur.execute(“select random_number_one, random_number_two, random_number_three from randomness.a_random_table”)
 rows = cur.fetchall()
 df = pd.DataFrame( [[ij for ij in i] for i in rows] )
 df.rename(columns={0: ‘Random Number One’, 1: ‘Random Number Two’, 2: ‘Random Number Three’}, inplace=True);
 print(df.head(20))

2D cross-platform game engine for Android and iOS?

Check out Loom (http://theengine.co) is a new cross platform 2D game engine featuring hot swapping code & assets on devices. This means that you can work in Photoshop on your assets, you can update your code, modify the UI of your app/game and then see the changes on your device(s) while the app is running.

Thinking to the other cross platform game engines I’ve heard of or even played with, the Loom Game Engine is by far the best in my oppinion with lots of great features. Most of the other similar game engines (Corona SDK, MOAI SDK, Gideros Mobile) are Lua based (with an odd syntax, at least for me). The Loom Game Engine uses LoomScripts, a scripting language inspired from ActionScript 3, with a couple of features borrowed from C#. If you ever developed in ActionScript 3, C# or Java, LoomScript will look familiar to you (and I’m more comfortable with this syntax than with Lua’s syntax).

The 1 year license for the Loom Game Engine costs $500, and I think it’s an affordable price for any indie game developer. Couple of weeks ago the offered a 1 year license for free too. After the license expires, you can still use Loom to create and deploy your own games, but you won’t get any further updates. The creators of Loom are very confident and they promised to constantly improve their baby making it worthwile to purchase another license.

Without further ado, here are Loom’s great features:

  1. Cross platform (iOS, Android, OS X, Windows, Linux/Ubuntu)

  2. Rails-inspired workflow lets you spend your time working with your game (one command to create a new project, and another command to run it)

  3. Fast compiler

  4. Live code and assets editing

  5. Possibility to integrate third party libraries

  6. Uses Cocos2DX for rendering

  7. XML, JSON support

  8. LML (markup language) and CSS for styling UI elements

  9. UI library

  10. Dependency injection

  11. Unit test framework

  12. Chipmunk physics

  13. Seeing your changes live makes multidevice development easy

  14. Small download size

  15. Built for teams

You can find more videos about Loom here: http://www.youtube.com/user/LoomEngine?feature=watch

Check out this 4 part in-depth tutorial too: http://www.gamefromscratch.com/post/2013/02/28/A-closer-look-at-the-Loom-game-engine-Part-one-getting-started.aspx

nullable object must have a value

I got this solution and it is working for me

if (myNewDT.MyDateTime == null)
{
   myNewDT.MyDateTime = DateTime.Now();
}

Reversing a linked list in Java, recursively

I think this is more cleaner solution, which resembles LISP

// Example:
// reverse0(1->2->3, null) => 
//      reverse0(2->3, 1) => 
//          reverse0(3, 2->1) => reverse0(null, 3->2->1)
// once the first argument is null, return the second arg
// which is nothing but the reveresed list.

Link reverse0(Link f, Link n) {
    if (f != null) {
        Link t = new Link(f.data1, f.data2); 
        t.nextLink = n;                      
        f = f.nextLink;             // assuming first had n elements before, 
                                    // now it has (n-1) elements
        reverse0(f, t);
    }
    return n;
}

How to create border in UIButton?

Here's a UIButton subclass that supports the highlighted state animation without using images. It also updates the border color when the view's tint mode changes.

class BorderedButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)

        layer.borderColor = tintColor.CGColor
        layer.borderWidth = 1
        layer.cornerRadius = 5

        contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("NSCoding not supported")
    }

    override func tintColorDidChange() {
        super.tintColorDidChange()

        layer.borderColor = tintColor.CGColor
    }

    override var highlighted: Bool {
        didSet {
            let fadedColor = tintColor.colorWithAlphaComponent(0.2).CGColor

            if highlighted {
                layer.borderColor = fadedColor
            } else {
                layer.borderColor = tintColor.CGColor

                let animation = CABasicAnimation(keyPath: "borderColor")
                animation.fromValue = fadedColor
                animation.toValue = tintColor.CGColor
                animation.duration = 0.4
                layer.addAnimation(animation, forKey: "")
            }
        }
    }
}

Usage:

let button = BorderedButton(style: .System) //style .System is important

Appearance:

enter image description here

enter image description here

How to validate a date?

function isValidDate(year, month, day) {
        var d = new Date(year, month - 1, day, 0, 0, 0, 0);
        return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
    }

ReactJS SyntheticEvent stopPropagation() only works with React events?

React 17 delegates events to root instead of document, which might solve the problem. More details here.

Getting input values from text box

Javascript document.getElementById("<%=contrilid.ClientID%>").value; or using jquery

$("#<%= txt_iplength.ClientID %>").val();

Is there Java HashMap equivalent in PHP?

Create a Java like HashMap in PHP with O(1) read complexity.

Open a phpsh terminal:

php> $myhashmap = array();
php> $myhashmap['mykey1'] = 'myvalue1';
php> $myhashmap['mykey2'] = 'myvalue2';
php> echo $myhashmap['mykey2'];
myvalue2

The complexity of the $myhashmap['mykey2'] in this case appears to be constant time O(1), meaning that as the size of $myhasmap approaches infinity, the amount of time it takes to retrieve a value given a key stays the same.

Evidence the php array read is constant time:

Run this through the PHP interpreter:

php> for($x = 0; $x < 1000000000; $x++){
 ... $myhashmap[$x] = $x . " derp";
 ... }

The loop adds 1 billion key/values, it takes about 2 minutes to add them all to the hashmap which may exhaust your memory.

Then see how long it takes to do a lookup:

php> system('date +%N');echo "  " . $myhashmap[10333] . "  ";system('date +%N');
786946389  10333 derp  789008364

So how fast is the PHP array map lookup?

The 10333 is the key we looked up. 1 million nanoseconds == 1 millisecond. The amount of time it takes to get a value from a key is 2.06 million nanoseconds or about 2 milliseconds. About the same amount of time if the array were empty. This looks like constant time to me.

'dependencies.dependency.version' is missing error, but version is managed in parent

You must build parent module before doing child module.

The value violated the integrity constraints for the column

the point can be if you are not using valid login for linked server. Problem is on destination server side.

There are few steps to try:

  1. Align db user and login on destination server: alter user [DBUSER_of_linkedserverlogin] with login = [linkedserverlogin]

  2. recreate login on destination server used by linked server.

  3. Backup table and recreate it.

2nd resolved my issue with "The value violated the integrity constraints for the column.".

Nullable type as a generic parameter possible?

public static T GetValueOrDefault<T>(this IDataRecord rdr, int index)
{
    object val = rdr[index];

    if (!(val is DBNull))
        return (T)val;

    return default(T);
}

Just use it like this:

decimal? Quantity = rdr.GetValueOrDefault<decimal?>(1);
string Unit = rdr.GetValueOrDefault<string>(2);

Ignore .pyc files in git repository

i try to use the sentence of a prior post and don't work recursively, then read some help and get this line:

find . -name "*.pyc" -exec git rm -f "{}" \;

p.d. is necessary to add *.pyc in .gitignore file to maintain git clean

echo "*.pyc" >> .gitignore

Enjoy.

Java Currency Number format

double amount =200.0;
Locale locale = new Locale("en", "US");      
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(locale);
System.out.println(currencyFormatter.format(amount));

or

double amount =200.0;
System.out.println(NumberFormat.getCurrencyInstance(new Locale("en", "US"))
        .format(amount));

The best way to display currency

Output

$200.00

If you don't want to use sign use this method

double amount = 200;
DecimalFormat twoPlaces = new DecimalFormat("0.00");
System.out.println(twoPlaces.format(amount));

200.00

This also can be use (With the thousand separator )

double amount = 2000000;    
System.out.println(String.format("%,.2f", amount));          

2,000,000.00

How to serve an image using nodejs

You should use the express framework.

npm install express

and then

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);

and then the URL localhost:8080/images/logo.gif should work.

dotnet ef not found in .NET Core 3

I was having this problem after I installed the dotnet-ef tool using Ansible with sudo escalated previllage on Ubuntu. I had to add become: no for the Playbook task, then the dotnet-ef tool became available to the current user.

  - name: install dotnet tool dotnet-ef
    command: dotnet tool install --global dotnet-ef --version {{dotnetef_version}}
    become: no

Response Buffer Limit Exceeded

If you are looking for the reason and don't want to fight the system settings, these are two major situations I faced:

  1. You may have an infinite loop without next or recordest.movenext
  2. Your text data is very large but you think it is not! The common reason for this situation is to copy-paste an Image from Microsoft word directly into the editor and so the server translates the image to data objects and saves it in your text field. This can easily occupies the database resources and causes buffer problem when you call the data again.

How to change the background color of Action Bar's Option Menu in Android 4.2?

I was able to change colour of action overflow by just putting hex value at:

    <!-- The beef: background color for Action Bar overflow menu -->
<style name="MyApp.PopupMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
    <item name="android:popupBackground">HEX VALUE OF COLOR</item>
</style>

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

So for people who want semantics similar to:

$ chmod 755 somefile

Use:

$ python -c "import os; os.chmod('somefile', 0o755)"

If your Python is older than 2.6:

$ python -c "import os; os.chmod('somefile', 0755)"

Move / Copy File Operations in Java

Not yet, but the New NIO (JSR 203) will have support for these common operations.

In the meantime, there are a few things to keep in mind.

File.renameTo generally works only on the same file system volume. I think of this as the equivalent to a "mv" command. Use it if you can, but for general copy and move support, you'll need to have a fallback.

When a rename doesn't work you will need to actually copy the file (deleting the original with File.delete if it's a "move" operation). To do this with the greatest efficiency, use the FileChannel.transferTo or FileChannel.transferFrom methods. The implementation is platform specific, but in general, when copying from one file to another, implementations avoid transporting data back and forth between kernel and user space, yielding a big boost in efficiency.

How to allow http content within an iframe on a https site

add <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> in head

reference: http://thehackernews.com/2015/04/disable-mixed-content-warning.html

browser compatibility: http://caniuse.com/#feat=upgradeinsecurerequests

How to preventDefault on anchor tags?

Since you are making a web app why do you need links?

Swap your anchors to buttons!

<button ng-click="do()"></button>

Iterating through a string word by word

for word in string.split():
    print word

Generating (pseudo)random alpha-numeric strings

You can use the following code. It is similar to existing functions except that you can force special character count:

function random_string() {
    // 8 characters: 7 lower-case alphabets and 1 digit
    $character_sets = [
        ["count" => 7, "characters" => "abcdefghijklmnopqrstuvwxyz"],
        ["count" => 1, "characters" => "0123456789"]
    ];
    $temp_array = array();
    foreach ($character_sets as $character_set) {
        for ($i = 0; $i < $character_set["count"]; $i++) {
            $random = random_int(0, strlen($character_set["characters"]) - 1);
            $temp_array[] = $character_set["characters"][$random];
        }
    }
    shuffle($temp_array);
    return implode("", $temp_array);
}

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

I know it's a bit of a late answer for this post, but for reference...

CSS

ul {
    color: red;
}

li {
    color: black;
}

The bullet colour is defined on the ul tag and then we switch the li colour back.

Android: Changing Background-Color of the Activity (Main View)

I just want to add my 2 cents. I had the same goal (to change the background color from the .java class). But none of the above methods worked for me.

Issue was, that I set the background color inside the layout .xml file with android:background="@color/colorGray":

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/colorGray">

So I just deleted particular line:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

Now I (you) can set the color from the code with:

getWindow().getDecorView().setBackgroundColor(Color.GRAY);

set font size in jquery

You can try another way like that:

<div class="content">
        Australia
    </div>

jQuery code:

$(".content").css({
    background: "#d1d1d1",
    fontSize: "30px"
})

Now you can add more css property as you want.

Single Page Application: advantages and disadvantages

I understand this is an older question, but I would like to add another disadvantage of Single Page Applications:

If you build an API that returns results in a data language (such as XML or JSON) rather than a formatting language (like HTML), you are enabling greater application interoperability, for example, in business-to-business (B2B) applications. Such interoperability has great benefits but does allow people to write software to "mine" (or steal) your data. This particular disadvantage is common to all APIs that use a data language, and not to SPAs in general (indeed, an SPA that asks the server for pre-rendered HTML avoids this, but at the expense of poor model/view separation). This risk exposed by this disadvantage can be mitigated by various means, such as request limiting and connection blocking, etc.

How to manually include external aar package using new Gradle Android Build System

The below approach works with latest Android studio (> v0.8.x):

  • Save the aar file under app module's libs folder (eg: <project>/<app>/libs/myaar.aar)

  • Add the below to build.gradle of your "app" module folder (not your project root build.gradle). Note the name in compile line, it is myaar@aar not myaar.aar.

    dependencies {
        compile 'package.name.of.your.aar:myaar@aar'
    }
    
    repositories{
        flatDir{
            dirs 'libs'
        }
    }
    
  • Click Tools -> Android -> Sync Project with Gradle Files

How can git be installed on CENTOS 5.5?

This worked for me on CentOS:

  1. Install dependencies:

    yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel
    
  2. Get Git

    cd /usr/local/src
    wget http://code.google.com/p/git-core/downloads/detail?name=git-1.7.8.3.tar.gz
    tar xvzf git-1.7.8.3.tar.gz
    cd git-1.7.8.3
    
  3. Build Git

    ./configure
    make
    make install
    

How to add a href link in PHP?

Just do it in HTML

<a href="https://www.google.com">Google</a>

How to iterate over a column vector in Matlab?

for i=1:length(list)
  elm = list(i);
  //do something with elm.

I need to round a float to two decimal places in Java

You can make use of DecimalFormat to give you the style you wish.

DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number));  // prints 1.30E7

Since it's in scientific notation, you won't be able to get the number any smaller than 107 without losing that many orders of magnitude of accuracy.

Form Google Maps URL that searches for a specific places near specific coordinates

You can use the new URL for Google Maps: https://www.google.com/maps/@39.774769,-74.86084,18z equivalent to http://maps.google.com/?ll=39.774769,-74.86084.

39.774769 is the latitude and -74.86084 is longitude and 18z is 18 zoom level.

Replacing blank values (white space) with NaN in pandas

How about:

d = d.applymap(lambda x: np.nan if isinstance(x, basestring) and x.isspace() else x)

The applymap function applies a function to every cell of the dataframe.

Handling identity columns in an "Insert Into TABLE Values()" statement?

The best practice is to explicitly list the columns:

Insert Into TableName(col1, col2,col2) Values(?, ?, ?)

Otherwise, your original insert will break if you add another column to your table.

Validating parameters to a Bash script

I would use bash's [[:

if [[ ! ("$#" == 1 && $1 =~ ^[0-9]+$ && -d $1) ]]; then 
    echo 'Please pass a number that corresponds to a directory'
    exit 1
fi

I found this faq to be a good source of information.

double free or corruption (!prev) error in c program

double *ptr = malloc(sizeof(double *) * TIME);
/* ... */
for(tcount = 0; tcount <= TIME; tcount++)
                         ^^
  • You're overstepping the array. Either change <= to < or alloc SIZE + 1 elements
  • Your malloc is wrong, you'll want sizeof(double) instead of sizeof(double *)
  • As ouah comments, although not directly linked to your corruption problem, you're using *(ptr+tcount) without initializing it

  • Just as a style note, you might want to use ptr[tcount] instead of *(ptr + tcount)
  • You don't really need to malloc + free since you already know SIZE

How can I use jQuery to make an input readonly?

simply add the following attribute

// for disabled i.e. cannot highlight value or change
disabled="disabled"

// for readonly i.e. can highlight value but not change
readonly="readonly"

jQuery to make the change to the element (substitute disabled for readonly in the following for setting readonly attribute).

$('#fieldName').attr("disabled","disabled") 

or

$('#fieldName').attr("disabled", true) 

NOTE: As of jQuery 1.6, it is recommended to use .prop() instead of .attr(). The above code will work exactly the same except substitute .attr() for .prop().

Do you have to put Task.Run in a method to make it async?

First, let's clear up some terminology: "asynchronous" (async) means that it may yield control back to the calling thread before it starts. In an async method, those "yield" points are await expressions.

This is very different than the term "asynchronous", as (mis)used by the MSDN documentation for years to mean "executes on a background thread".

To futher confuse the issue, async is very different than "awaitable"; there are some async methods whose return types are not awaitable, and many methods returning awaitable types that are not async.

Enough about what they aren't; here's what they are:

  • The async keyword allows an asynchronous method (that is, it allows await expressions). async methods may return Task, Task<T>, or (if you must) void.
  • Any type that follows a certain pattern can be awaitable. The most common awaitable types are Task and Task<T>.

So, if we reformulate your question to "how can I run an operation on a background thread in a way that it's awaitable", the answer is to use Task.Run:

private Task<int> DoWorkAsync() // No async because the method does not need await
{
  return Task.Run(() =>
  {
    return 1 + 2;
  });
}

(But this pattern is a poor approach; see below).

But if your question is "how do I create an async method that can yield back to its caller instead of blocking", the answer is to declare the method async and use await for its "yielding" points:

private async Task<int> GetWebPageHtmlSizeAsync()
{
  var client = new HttpClient();
  var html = await client.GetAsync("http://www.example.com/");
  return html.Length;
}

So, the basic pattern of things is to have async code depend on "awaitables" in its await expressions. These "awaitables" can be other async methods or just regular methods returning awaitables. Regular methods returning Task/Task<T> can use Task.Run to execute code on a background thread, or (more commonly) they can use TaskCompletionSource<T> or one of its shortcuts (TaskFactory.FromAsync, Task.FromResult, etc). I don't recommend wrapping an entire method in Task.Run; synchronous methods should have synchronous signatures, and it should be left up to the consumer whether it should be wrapped in a Task.Run:

private int DoWork()
{
  return 1 + 2;
}

private void MoreSynchronousProcessing()
{
  // Execute it directly (synchronously), since we are also a synchronous method.
  var result = DoWork();
  ...
}

private async Task DoVariousThingsFromTheUIThreadAsync()
{
  // I have a bunch of async work to do, and I am executed on the UI thread.
  var result = await Task.Run(() => DoWork());
  ...
}

I have an async/await intro on my blog; at the end are some good followup resources. The MSDN docs for async are unusually good, too.

Where are SQL Server connection attempts logged?

Another way to check on connection attempts is to look at the server's event log. On my Windows 2008 R2 Enterprise machine I opened the server manager (right-click on Computer and select Manage. Then choose Diagnostics -> Event Viewer -> Windows Logs -> Applcation. You can filter the log to isolate the MSSQLSERVER events. I found a number that looked like this

Login failed for user 'bogus'. The user is not associated with a trusted SQL Server connection. [CLIENT: 10.12.3.126]

CKEditor instance already exists

Try this:

for (name in CKEDITOR.instances)
{
    CKEDITOR.instances[name].destroy(true);
}

rsync copy over only certain types of files using include option

If someone looks for this… I wanted to rsync only specific files and folders and managed to do it with this command: rsync --include-from=rsync-files

With rsync-files:

my-dir/
my-file.txt

- /*

Getting RAW Soap Data from a Web Reference Client running in ASP.net

Here's a simplified version of the top answer. Add this to the <configuration> element of your web.config or App.config file. It will create a trace.log file in your project's bin/Debug folder. Or, you can specify an absolute path for the log file using the initializeData attribute.

  <system.diagnostics>
    <trace autoflush="true"/>
    <sources>
      <source name="System.Net" maxdatasize="9999" tracemode="protocolonly">
        <listeners>
          <add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener" initializeData="trace.log"/>
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="System.Net" value="Verbose"/>
    </switches>
  </system.diagnostics>

It warns that the maxdatasize and tracemode attributes are not allowed, but they increase the amount of data that can be logged, and avoid logging everything in hex.

Convert array into csv

Add some improvements based on accepted answer.

  1. PHP 7.0 Strict typing
  2. PHP 7.0 Type declaration and Return type declaration
  3. Enclosure \r, \n, \t
  4. Don't enclosure empty string even $encloseAll is TRUE
/**
  * Formats a line (passed as a fields array) as CSV and returns the CSV as a string.
  * Adapted from https://www.php.net/manual/en/function.fputcsv.php#87120
  */
function arrayToCsv(array $fields, string $delimiter = ';', string $enclosure = '"', bool $encloseAll = false, bool $nullToMysqlNull = false): string {

    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $output = [];
    foreach ($fields as $field) {
        if ($field === null && $nullToMysqlNull) {
            $output[] = 'NULL';
            continue;
        }
        // Enclose fields containing $delimiter, $enclosure or whitespace, newline
        $field = strval($field);
        if (strlen($field) && ($encloseAll || preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s|\r|\n|\t)/", $field))) {
            $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
        } else {
            $output[] = $field;
        }
    }

    return implode($delimiter, $output);

}

Shell equality operators (=, ==, -eq)

Several answers show dangerous examples. OP's example [ $a == $b ] specifically used unquoted variable substitution (as of Oct '17 edit). For [...] that is safe for string equality.

But if you're going to enumerate alternatives like [[...]], you must inform also that the right-hand-side must be quoted. If not quoted, it is a pattern match! (From bash man page: "Any part of the pattern may be quoted to force it to be matched as a string.").

Here in bash, the two statements yielding "yes" are pattern matching, other three are string equality:

$ rht="A*"
$ lft="AB"
$ [ $lft = $rht ] && echo yes
$ [ $lft == $rht ] && echo yes
$ [[ $lft = $rht ]] && echo yes
yes
$ [[ $lft == $rht ]] && echo yes
yes
$ [[ $lft == "$rht" ]] && echo yes
$

Oracle date difference to get number of years

Need to find difference in year, if leap year the a year is of 366 days.

I dont work in oracle much, please make this better. Here is how I did:

SELECT CASE
          WHEN    ( (fromisleapyear = 'Y') AND (frommonth < 3))
               OR ( (toisleapyear = 'Y') AND (tomonth > 2)) THEN
             datedif / 366
          ELSE
             datedif / 365
       END
          yeardifference
  FROM (SELECT datedif,
               frommonth,
               tomonth,
               CASE
                  WHEN (       (MOD (fromyear, 4) = 0)
                           AND (MOD (fromyear, 100) <> 0)
                        OR (MOD (fromyear, 400) = 0)) THEN
                     'Y'
               END
                  fromisleapyear,
               CASE
                  WHEN (   (MOD (toyear, 4) = 0) AND (MOD (toyear, 100) <> 0)
                        OR (MOD (toyear, 400) = 0)) THEN
                     'Y'
               END
                  toisleapyear
          FROM (SELECT (:todate - :fromdate) AS datedif,
                       TO_CHAR (:fromdate, 'YYYY') AS fromyear,
                       TO_CHAR (:fromdate, 'MM') AS frommonth,
                       TO_CHAR (:todate, 'YYYY') AS toyear,
                       TO_CHAR (:todate, 'MM') AS tomonth
                  FROM DUAL))

Android soft keyboard covers EditText field

I had same issues. Try following code:

android:windowSoftInputMode="adjustPan"

add it to your manifest.xml in the activity tag of the activity that holds the input. example:

<activity
            android:name=".Activities.InputsActivity"
            ...
            android:windowSoftInputMode="adjustPan"
            />

Selecting a row of pandas series/dataframe by integer index

To index-based access to the pandas table, one can also consider numpy.as_array option to convert the table to Numpy array as

np_df = df.as_matrix()

and then

np_df[i] 

would work.

Unable to install pyodbc on Linux

I resolved my issue by following correct directions on pyodbc - Building wiki which states:

On Linux, pyodbc is typically built using the unixODBC headers, so you will need unixODBC and its headers installed. On a RedHat/CentOS/Fedora box, this means you would need to install unixODBC-devel:

yum install unixODBC-devel

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

How to run JUnit tests with Gradle?

testCompile is deprecated. Gradle 7 compatible:

dependencies {
...
   testImplementation 'junit:junit:4.13'
}

and if you use the default folder structure (src/test/java/...) the test section is simply:

test {
    useJUnit()
}

Finally:

gradlew clean test

Alos see: https://docs.gradle.org/current/userguide/java_testing.html

Click a button programmatically - JS

Though this question is rather old, here's a answer :)

What you are asking for can be achieved by using jQuery's .click() event method and .on() event method

So this could be the code:

// Set the global variables
var userImage = $("#img-giLkojRpuK");
var hangoutButton = $("#hangout-giLkojRpuK");

$(document).ready(function() {
    // When the document is ready/loaded, execute function

    // Hide hangoutButton
    hangoutButton.hide();

    // Assign "click"-event-method to userImage
    userImage.on("click", function() {
        console.log("in onclick");
        hangoutButton.click();
    });
});

How to make div go behind another div?

To answer the question in a general manner:

Using z-index will allow you to control this. see z-index at csstricks.

The element of higher z-index will be displayed on top of elements of lower z-index.

For instance, take the following HTML:

<div id="first">first</div>
<div id="second">second</div>

If I have the following CSS:

#first {
    position: fixed;
    z-index: 2;
}

#second {
    position: fixed;
    z-index: 1;
}

#first wil be on top of #second.

But specifically in your case:

The div element is a child of the div that you wish to put in front. This is not logically possible.

.war vs .ear file

Ear files provide more options to configure the interaction with the application server.

For example: if the hibernate version of the application server is older than the one provided by your dependencies, you can add the following to ear-deployer-jboss-beans.xml for JBOSS to isolate classloaders and avoid conflicts:

<bean name="EARClassLoaderDeployer" class="org.jboss.deployment.EarClassLoaderDeployer">    
  <property name="isolated">true</property>
</bean>

or to src/main/application/META-INF/jboss-app.xml :

<?xml version="1.0"?>
<jboss-app>
<loader-repository>
    loader=nameofyourear.ear
<loader-repository-config>java2ParentDelegation=false</loader-repository-config>
</loader-repository>
</jboss-app> 

This will make sure that there is no classloader conflict between your application and the application server.

Normally the classloader mechanism works like this:

When a class loading request is presented to a class loader, it first asks its parent class loader to fulfill the request. The parent, in turn, asks its parent for the class until the request reaches the top of the hierarchy. If the class loader at the top of the hierarchy cannot fulfill the request, then the child class loader that called it is responsible for loading the class.

By isolating the classloaders, your ear classloader will not look in the parent (=JBoss / other AS classloader). As far is I know, this is not possible with war files.

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Non-numpy functions like math.abs() or math.log10() don't play nicely with numpy arrays. Just replace the line raising an error with:

m = np.log10(np.abs(x))

Apart from that the np.polyfit() call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).

Can someone explain how to append an element to an array in C programming?

Short answer is: You don't have any choice other than:

arr[4] = 5;

How to enable DataGridView sorting when user clicks on the column header?

One more way to do this is using "System.Linq.Dynamic" library. You can get this library from Nuget. No need of any custom implementations or sortable List :)

using System.Linq.Dynamic;
private bool sortAscending = false;

private void dataGridView_ColumnHeaderMouseClick ( object sender, DataGridViewCellMouseEventArgs e )
{
    if ( sortAscending )
        dataGridView.DataSource = list.OrderBy ( dataGridView.Columns [ e.ColumnIndex ].DataPropertyName ).ToList ( );
    else
        dataGridView.DataSource = list.OrderBy ( dataGridView.Columns [ e.ColumnIndex ].DataPropertyName ).Reverse ( ).ToList ( );
    sortAscending = !sortAscending;
}

Best way to convert IList or IEnumerable to Array

In case you don't have Linq, I solved it the following way:

    private T[] GetArray<T>(IList<T> iList) where T: new()
    {
        var result = new T[iList.Count];

        iList.CopyTo(result, 0);

        return result;
    }

Hope it helps

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

In .Net 1.1 and earlier, Application.Exit was not a wise choice and the MSDN docs specifically recommended against it because all message processing stopped immediately.

In later versions however, calling Application.Exit will result in Form.Close being called on all open forms in the application, thus giving you a chance to clean up after yourself, or even cancel the operation all together.

What does .shape[] do in "for i in range(Y.shape[0])"?

In Python shape() is use in pandas to give number of row/column:

Number of rows is given by:

train = pd.read_csv('fine_name') //load the data
train.shape[0]

Number of columns is given by

train.shape[1]

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

In my case. I had the error because I forgot to make a commit after create a repository on github into an existing project. So I solved:

git add .
git commit -m"commentary"

Then I was able to type:

git push -u origin master

Are list-comprehensions and functional functions faster than "for loops"?

The following are rough guidelines and educated guesses based on experience. You should timeit or profile your concrete use case to get hard numbers, and those numbers may occasionally disagree with the below.

A list comprehension is usually a tiny bit faster than the precisely equivalent for loop (that actually builds a list), most likely because it doesn't have to look up the list and its append method on every iteration. However, a list comprehension still does a bytecode-level loop:

>>> dis.dis(<the code object for `[x for x in range(10)]`>)
 1           0 BUILD_LIST               0
             3 LOAD_FAST                0 (.0)
       >>    6 FOR_ITER                12 (to 21)
             9 STORE_FAST               1 (x)
            12 LOAD_FAST                1 (x)
            15 LIST_APPEND              2
            18 JUMP_ABSOLUTE            6
       >>   21 RETURN_VALUE

Using a list comprehension in place of a loop that doesn't build a list, nonsensically accumulating a list of meaningless values and then throwing the list away, is often slower because of the overhead of creating and extending the list. List comprehensions aren't magic that is inherently faster than a good old loop.

As for functional list processing functions: While these are written in C and probably outperform equivalent functions written in Python, they are not necessarily the fastest option. Some speed up is expected if the function is written in C too. But most cases using a lambda (or other Python function), the overhead of repeatedly setting up Python stack frames etc. eats up any savings. Simply doing the same work in-line, without function calls (e.g. a list comprehension instead of map or filter) is often slightly faster.

Suppose that in a game that I'm developing I need to draw complex and huge maps using for loops. This question would be definitely relevant, for if a list-comprehension, for example, is indeed faster, it would be a much better option in order to avoid lags (Despite the visual complexity of the code).

Chances are, if code like this isn't already fast enough when written in good non-"optimized" Python, no amount of Python level micro optimization is going to make it fast enough and you should start thinking about dropping to C. While extensive micro optimizations can often speed up Python code considerably, there is a low (in absolute terms) limit to this. Moreover, even before you hit that ceiling, it becomes simply more cost efficient (15% speedup vs. 300% speed up with the same effort) to bite the bullet and write some C.

Chrome Extension: Make it run every page load

You can put your script into a content-script, see

Removing index column in pandas when reading a csv

One thing that i do is df=df.reset_index() then df=df.drop(['index'],axis=1)

Up, Down, Left and Right arrow keys do not trigger KeyDown event

I'm using PreviewKeyDown

    private void _calendar_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e){
        switch (e.KeyCode){
            case Keys.Down:
            case Keys.Right:
                //action
                break;
            case Keys.Up:
            case Keys.Left:
                //action
                break;
        }
    }

Gradle failed to resolve library in Android Studio

To be able to use a lib project you need to include it in your application's settings.gradle add:

include '..:ExpandableButtonMenu:library'

and then in your build.gradle add:

compile project(':..:ExpandableButtonMenu:library') 

place ExpandableButtonMenu project along side your own (same folder)

see this How to build an android library with Android Studio and gradle? for more details.

How do I set the default Java installation/runtime (Windows)?

an alterable way to run an .jar app is create an .bat cmd for it. for example, you have jre10 and jre8 installed on your pc,and jre10 is your default jre. but your jar is specified to work with jre8,following cmd will work:

"C:\Program Files\Java\jre1.8.0_181\bin\java.exe" -jar JabRef-4.3.1.jar

Accessing an SQLite Database in Swift

You can use this library in Swift for SQLite https://github.com/pmurphyjam/SQLiteDemo

SQLiteDemo

SQLite Demo using Swift with SQLDataAccess class written in Swift

Adding to Your Project

You only need three files to add to your project * SQLDataAccess.swift * DataConstants.swift * Bridging-Header.h Bridging-Header must be set in your Xcode's project 'Objective-C Bridging Header' under 'Swift Compiler - General'

Examples for Use

Just follow the code in ViewController.swift to see how to write simple SQL with SQLDataAccess.swift First you need to open the SQLite Database your dealing with

    let db = SQLDataAccess.shared
    db.setDBName(name:"SQLite.db")
    let opened = db.openConnection(copyFile:true)

If openConnection succeeded, now you can do a simple insert into Table AppInfo

    //Insert into Table AppInfo
    let status = db.executeStatement("insert into AppInfo (name,value,descrip,date) values(?,?,?,?)",
    ”SQLiteDemo","1.0.2","unencrypted",Date())
    if(status)
    {
        //Read Table AppInfo into an Array of Dictionaries
        let results = db.getRecordsForQuery("select * from AppInfo ")
        NSLog("Results = \(results)")
    }

See how simple that was!

The first term in db.executeStatement is your SQL as String, all the terms that follow are a variadic argument list of type Any, and are your parameters in an Array. All these terms are separated by commas in your list of SQL arguments. You can enter Strings, Integers, Date’s, and Blobs right after the sequel statement since all of these terms are considered to be parameters for the sequel. The variadic argument array just makes it convenient to enter all your sequel in just one executeStatement or getRecordsForQuery call. If you don’t have any parameters, don’t enter anything after your SQL.

The results array is an Array of Dictionary’s where the ‘key’ is your tables column name, and the ‘value’ is your data obtained from SQLite. You can easily iterate through this array with a for loop or print it out directly or assign these Dictionary elements to custom data object Classes that you use in your View Controllers for model consumption.

    for dic in results as! [[String:AnyObject]] {
       print(“result = \(dic)”)
    }

SQLDataAccess will store, text, double, float, blob, Date, integer and long long integers. For Blobs you can store binary, varbinary, blob.

For Text you can store char, character, clob, national varying character, native character, nchar, nvarchar, varchar, variant, varying character, text.

For Dates you can store datetime, time, timestamp, date.

For Integers you can store bigint, bit, bool, boolean, int2, int8, integer, mediumint, smallint, tinyint, int.

For Doubles you can store decimal, double precision, float, numeric, real, double. Double has the most precision.

You can even store Nulls of type Null.

In ViewController.swift a more complex example is done showing how to insert a Dictionary as a 'Blob'. In addition SQLDataAccess understands native Swift Date() so you can insert these objects with out converting, and it will convert them to text and store them, and when retrieved convert them back from text to Date.

Of course the real power of SQLite is it's Transaction capability. Here you can literally queue up 400 SQL statements with parameters and insert them all at once which is really powerful since it's so fast. ViewController.swift also shows you an example of how to do this. All you're really doing is creating an Array of Dictionaries called 'sqlAndParams', in this Array your storing Dictionaries with two keys 'SQL' for the String sequel statement or query, and 'PARAMS' which is just an Array of native objects SQLite understands for that query. Each 'sqlParams' which is an individual Dictionary of sequel query plus parameters is then stored in the 'sqlAndParams' Array. Once you've created this array, you just call.

    let status = db.executeTransaction(sqlAndParams)
    if(status)
    {
        //Read Table AppInfo into an Array of Dictionaries for the above Transactions
        let results = db.getRecordsForQuery("select * from AppInfo ")
        NSLog("Results = \(results)")
    }

In addition all executeStatement and getRecordsForQuery methods can be done with simple String for SQL query and an Array for the parameters needed by the query.

    let sql : String = "insert into AppInfo (name,value,descrip) values(?,?,?)"
    let params : Array = ["SQLiteDemo","1.0.0","unencrypted"]
    let status = db.executeStatement(sql, withParameters: params)
    if(status)
    {
        //Read Table AppInfo into an Array of Dictionaries for the above Transactions
        let results = db.getRecordsForQuery("select * from AppInfo ")
        NSLog("Results = \(results)")
    }

An Objective-C version also exists and is called the same SQLDataAccess, so now you can choose to write your sequel in Objective-C or Swift. In addition SQLDataAccess will also work with SQLCipher, the present code isn't setup yet to work with it, but it's pretty easy to do, and an example of how to do this is actually in the Objective-C version of SQLDataAccess.

SQLDataAccess is a very fast and efficient class, and can be used in place of CoreData which really just uses SQLite as it's underlying data store without all the CoreData core data integrity fault crashes that come with CoreData.

MySQL CREATE FUNCTION Syntax

MySQL create function syntax:

DELIMITER //

CREATE FUNCTION GETFULLNAME(fname CHAR(250),lname CHAR(250))
    RETURNS CHAR(250)
    BEGIN
        DECLARE fullname CHAR(250);
        SET fullname=CONCAT(fname,' ',lname);
        RETURN fullname;
    END //

DELIMITER ;

Use This Function In Your Query

SELECT a.*,GETFULLNAME(a.fname,a.lname) FROM namedbtbl as a


SELECT GETFULLNAME("Biswarup","Adhikari") as myname;

Watch this Video how to create mysql function and how to use in your query

Create Mysql Function Video Tutorial

TypeScript for ... of with index / key?

"Old school javascript" to the rescue (for those who aren't familiar/in love of functional programming)

for (let i = 0; i < someArray.length ; i++) {
  let item = someArray[i];
}

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

I found a solution to this. It's bloody witchcraft, but it works.

When you install the client, open Control Panel > Network Connections.

You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).

Right Click it, click Enable.

The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.

HTML for the Pause symbol in audio and video control

Unicode Standard for Media Control Symbols

Pause: ??

The Unicode Standard 13.0 (update 2020) provides the Miscellaneous Technical glyphs in the HEX range 2300–23FF

Miscellaneous Technical

Given the extensive Unicode 13.0 documentation, some of the glyphs we can associate to common Media control symbols would be as following:

Keyboard and UI symbols

23CF ⏏︎ Eject media

User interface symbols

23E9 ⏩︎ fast forward
23EA ⏪︎ rewind, fast backwards
23EB ⏫︎ fast increase
23EC ⏬︎ fast decrease
23ED ⏭︎ skip to end, next
23EE ⏮︎ skip to start, previous
23EF ⏯︎ play/pause toggle
23F1 ⏱︎ stopwatch
23F2 ⏲︎ timer clock
23F3 ⏳︎ hourglass
23F4 ⏴︎ reverse, back
23F5 ⏵︎ forward, next, play
23F6 ⏶︎ increase
23F7 ⏷︎ decrease
23F8 ⏸︎ pause
23F9 ⏹︎ stop
23FA ⏺︎ record

Power symbols from ISO 7000:2012

23FB ?︎ standby/power
23FC ?︎ power on/off
23FD ?︎ power on
2B58 ?︎ power off

Power symbol from IEEE 1621-2004

23FE ?︎ power sleep

Use on the Web:

A file must be saved using UTF-8 encoding without BOM (which in most development environments is set by default) in order to instruct the parser how to transform the bytes into characters correctly. <meta charset="utf-8"/> should be used immediately after <head> in a HTML file, and make sure the correct HTTP headers Content-Type: text/html; charset=utf-8 are set.

Examples:

HTML
&#x23E9; Pictograph 
&#x23E9;&#xFE0E; Standardized Variant
CSS
.icon-ff:before { content: "\23E9" }
.icon-ff--standard:before { content: "\23E9\FE0E" }
JavaScript
EL_iconFF.textContent = "\u23E9";
EL_iconFF_standard.textContent = "\u23E9\uFE0E"

Standardized variant

To prevent a glyph from being "color-emojified" ⏩︎ / ⏩ append the code U+FE0E Text Presentation Selector to request a Standardized variant: (example: &#x23e9;&#xfe0e;)

Inconsistencies

Characters in the Unicode range are susceptible to the font-family environment they are used, application, browser, OS, platform.
When unknown or missing - we might see symbols like � or ▯ instead, or even inconsistent behavior due to differences in HTML parser implementations by different vendors.
For example, on Windows Chromium browsers the Standardized Variant suffix U+FE0E is buggy, and such symbols are still better accompanied by CSS i.e: font-family: "Segoe UI Symbol" to force that specific Font over the Colored Emoji (usually recognized as "Segoe UI Emoji") - which defies the purpose of U+FE0E in the first place - time will tell…


Scalable icon fonts

To circumvent problems related to unsupported characters - a viable solution is to use scalable icon font-sets like i.e:

Font Awesome

Player icons - scalable - font awesome

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">_x000D_
<i class="fa fa-arrows-alt"></i>_x000D_
<i class="fa fa-backward"></i>_x000D_
<i class="fa fa-compress"></i>_x000D_
<i class="fa fa-eject"></i>_x000D_
<i class="fa fa-expand"></i>_x000D_
<i class="fa fa-fast-backward"></i>_x000D_
<i class="fa fa-fast-forward"></i>_x000D_
<i class="fa fa-forward"></i>_x000D_
<i class="fa fa-pause"></i>_x000D_
<i class="fa fa-play"></i>_x000D_
<i class="fa fa-play-circle"></i>_x000D_
<i class="fa fa-play-circle-o"></i>_x000D_
<i class="fa fa-step-backward"></i>_x000D_
<i class="fa fa-step-forward"></i>_x000D_
<i class="fa fa-stop"></i>_x000D_
<i class="fa fa-youtube-play"></i>
_x000D_
_x000D_
_x000D_

Google Icons

enter image description here

_x000D_
_x000D_
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">_x000D_
<i class="material-icons">pause</i>_x000D_
<i class="material-icons">pause_circle_filled</i>_x000D_
<i class="material-icons">pause_circle_outline</i>_x000D_
<i class="material-icons">fast_forward</i>_x000D_
<i class="material-icons">fast_rewind</i>_x000D_
<i class="material-icons">fiber_manual_record</i>_x000D_
<i class="material-icons">play_arrow</i>_x000D_
<i class="material-icons">play_circle_filled</i>_x000D_
<i class="material-icons">play_circle_outline</i>_x000D_
<i class="material-icons">skip_next</i>_x000D_
<i class="material-icons">skip_previous</i>_x000D_
<i class="material-icons">replay</i>_x000D_
<i class="material-icons">repeat</i>_x000D_
<i class="material-icons">stop</i>_x000D_
<i class="material-icons">loop</i>_x000D_
<i class="material-icons">mic</i>_x000D_
<i class="material-icons">volume_up</i>_x000D_
<i class="material-icons">volume_down</i>_x000D_
<i class="material-icons">volume_mute</i>_x000D_
<i class="material-icons">volume_off</i>
_x000D_
_x000D_
_x000D_

and many other you can find in the wild; and last but not least, this really useful online tool: font-icons generator, Icomoon.io.


What's the best way to cancel event propagation between nested ng-click calls?

You can register another directive on top of ng-click which amends the default behaviour of ng-click and stops the event propagation. This way you wouldn't have to add $event.stopPropagation by hand.

app.directive('ngClick', function() {
    return {
        restrict: 'A',
        compile: function($element, attr) {
            return function(scope, element, attr) {
                element.on('click', function(event) {
                    event.stopPropagation();
                });
            };
        }
    }
});

Gather multiple sets of columns

In case you are like me, and cannot work out how to use "regular expression with capturing groups" for extract, the following code replicates the extract(...) line in Hadleys' answer:

df %>% 
    gather(question_number, value, starts_with("Q3.")) %>%
    mutate(loop_number = str_sub(question_number,-2,-2), question_number = str_sub(question_number,1,4)) %>%
    select(id, time, loop_number, question_number, value) %>% 
    spread(key = question_number, value = value)

The problem here is that the initial gather forms a key column that is actually a combination of two keys. I chose to use mutate in my original solution in the comments to split this column into two columns with equivalent info, a loop_number column and a question_number column. spread can then be used to transform the long form data, which are key value pairs (question_number, value) to wide form data.

Print the stack trace of an exception

If you are interested in a more compact stack trace with more information (package detail) that looks like:

  java.net.SocketTimeoutException:Receive timed out
    at j.n.PlainDatagramSocketImpl.receive0(Native Method)[na:1.8.0_151]
    at j.n.AbstractPlainDatagramSocketImpl.receive(AbstractPlainDatagramSocketImpl.java:143)[^]
    at j.n.DatagramSocket.receive(DatagramSocket.java:812)[^]
    at o.s.n.SntpClient.requestTime(SntpClient.java:213)[classes/]
    at o.s.n.SntpClient$1.call(^:145)[^]
    at ^.call(^:134)[^]
    at o.s.f.SyncRetryExecutor.call(SyncRetryExecutor.java:124)[^]
    at o.s.f.RetryPolicy.call(RetryPolicy.java:105)[^]
    at o.s.f.SyncRetryExecutor.call(SyncRetryExecutor.java:59)[^]
    at o.s.n.SntpClient.requestTimeHA(SntpClient.java:134)[^]
    at ^.requestTimeHA(^:122)[^]
    at o.s.n.SntpClientTest.test2h(SntpClientTest.java:89)[test-classes/]
    at s.r.NativeMethodAccessorImpl.invoke0(Native Method)[na:1.8.0_151]

you can try to use Throwables.writeTo from the spf4j lib.

SQL Insert into table only if record doesn't exist

Assuming you cannot modify DDL (to create a unique constraint) or are limited to only being able to write DML then check for a null on filtered result of your values against the whole table

FIDDLE

insert into funds (ID, date, price) 
select 
    T.* 
from 
    (select 23 ID,  '2013-02-12' date,  22.43 price) T  
        left join 
    funds on funds.ID = T.ID and funds.date = T.date
where 
    funds.ID is null

I get exception when using Thread.sleep(x) or wait()

Use the following coding construct to handle exceptions

try {
  Thread.sleep(1000);
} catch (InterruptedException ie) {
    //Handle exception
}

How to check for null in a single statement in scala?

Option(getObject) foreach (QueueManager add)