Programs & Examples On #Netstream

The NetStream class opens a one-way streaming channel over a NetConnection.

Accessing SQL Database in Excel-VBA

I've added the Initial Catalog to your connection string. I've also abandonded the ADODB.Command syntax in favor of simply creating my own SQL statement and open the recordset on that variable.

Hope this helps.

Sub GetDataFromADO()
    'Declare variables'
        Set objMyConn = New ADODB.Connection
        Set objMyRecordset = New ADODB.Recordset
        Dim strSQL As String

    'Open Connection'
        objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=MyDatabase;User ID=abc;Password=abc;"
        objMyConn.Open

    'Set and Excecute SQL Command'
        strSQL = "select * from myTable"

    'Open Recordset'
        Set objMyRecordset.ActiveConnection = objMyConn
        objMyRecordset.Open strSQL            

    'Copy Data to Excel'
        ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)

End Sub

How to add a class to body tag?

$('body').toggleClass("className");

perfectly works

Why does datetime.datetime.utcnow() not contain timezone information?

from datetime import datetime 
from dateutil.relativedelta import relativedelta
d = datetime.now()
date = datetime.isoformat(d).split('.')[0]
d_month = datetime.today() + relativedelta(months=1)
next_month = datetime.isoformat(d_month).split('.')[0]

How to Completely Uninstall Xcode and Clear All Settings

  1. Open Storage Management

    • Go to ? > About This Mac > Window > Storage Management
    • Or, hit ? + Space to open Spotlight and search for Storage Management.
  2. Select Applications on left pane.

  3. Right click on Xcode on the right pane and select delete.

This will remove XCode from the installed applications list of your Mac's App Store.

Update: This worked for me on macOS Sierra 10.12.1.

Git: Merge a Remote branch locally

Maybe you want to track the remote branch with a local branch:

  1. Create a new local branch: git branch new-local-branch
  2. Set this newly created branch to track the remote branch: git branch --set-upstream-to=origin/remote-branch new-local-branch
  3. Enter into this branch: git checkout new-local-branch
  4. Pull all the contents of the remote branch into the local branch: git pull

How do I disable and re-enable a button in with javascript?

<script>
function checkusers()
{
   var shouldEnable = document.getElementById('checkbox').value == 0;
   document.getElementById('add_button').disabled = shouldEnable;
}
</script>

What is LD_LIBRARY_PATH and how to use it?

My error was also related to not finding the required .so file by a service. I used LD_LIBRARY_PATH variable to priorities the path picked up by the linker to search the required lib.

I copied both service and .so file in a folder and fed it to LD_LIBRARY_PATH variable as

LD_LIBRARY_PATH=. ./service

being in the same folder I have given the above command and it worked.

Find object by its property in array of objects with AngularJS way

For complete M B answer, if you want to access to an specific attribute of this object already filtered from the array in your HTML, you will have to do it in this way:

{{ (myArray | filter : {'id':73})[0].name }}

So, in this case, it will print john in the HTML.

Regards!

Webpack not excluding node_modules

If you ran into this issue when using TypeScript, you may need to add skipLibCheck: true in your tsconfig.json file.

How to highlight text using javascript

Here's my regexp pure JavaScript solution:

function highlight(text) {
    document.body.innerHTML = document.body.innerHTML.replace(
        new RegExp(text + '(?!([^<]+)?<)', 'gi'),
        '<b style="background-color:#ff0;font-size:100%">$&</b>'
    );
}

How to set the timezone in Django?

  1. download latest pytz file (pytz-2019.3.tar.gz) from:

    https://pypi.org/simple/pytz/
    
  2. copy and extract it to site_packages directory on yor project

  3. in cmd go to the extracted folder and run:

    python setup.py install
    
  4. TIME_ZONE = 'Etc/GMT+2' or country name

How to format number of decimal places in wpf using style/template?

    void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
    {
        TextBox txt = (TextBox)sender;
        var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
        string str = txt.Text + e.Text.ToString();
        int cntPrc = 0;
        if (str.Contains('.'))
        {
            string[] tokens = str.Split('.');
            if (tokens.Count() > 0)
            {
                string result = tokens[1];
                char[] prc = result.ToCharArray();
                cntPrc = prc.Count();
            }
        }
        if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }

.bashrc: Permission denied

.bashrc is not meant to be executed but sourced. Try this instead:

. ~/.bashrc

Cheers!

Execute a command line binary with Node.js

Since version 4 the closest alternative is child_process.execSync method:

const {execSync} = require('child_process');

let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');

?? Note that execSync call blocks event loop.

Change drive in git bash for windows

TL;DR; for Windows users:

(Quotation marks not needed if path has no blank spaces)

Git Bash: cd "/C/Program Files (x86)/Android" // macOS/Linux syntax

Cmd.exe: cd "C:\Program Files (x86)\Android" // windows syntax


When using git bash on windows, you have to:

  • remove the colon after the drive letter
  • replace your back-slashes with forward-slashes
  • If you have blank spaces in your path: Put quotation marks at beginning and end of the path

Git Bash: cd "/C/Program Files (x86)/Android" // macOS/Linux syntax

Cmd.exe: cd "C:\Program Files (x86)\Android" // windows syntax

Get String in YYYYMMDD format from JS date object?

Use padStart:

Date.prototype.yyyymmdd = function() {
    return [
        this.getFullYear(),
        (this.getMonth()+1).toString().padStart(2, '0'), // getMonth() is zero-based
        this.getDate().toString().padStart(2, '0')
    ].join('-');
};

To the power of in C?

#include <math.h>


printf ("%d", (int) pow (3, 4));

How to build a query string for a URL in C#?

public string UrlQueryStr(object data)
{
    if (data == null)
        return string.Empty;

    object val;
    StringBuilder sb = new StringBuilder();

    foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(data))
    {
        if ((val = prop.GetValue(data)) != null)
        {
            sb.AppendFormat("{0}{1}={2}", sb.Length == 0 ? '?' : '&',
                HttpUtility.UrlEncode(prop.Name), HttpUtility.UrlEncode(val.ToString()));
        }
    }
    return sb.ToString();
}

Format date as dd/MM/yyyy using pipes

Import DatePipe from angular/common and then use the below code:

var datePipe = new DatePipe();
    this.setDob = datePipe.transform(userdate, 'dd/MM/yyyy');

where userdate will be your date string. See if this helps.

Make note of the lowercase for date and year :

d- date
M- month
y-year

EDIT

You have to pass locale string as an argument to DatePipe, in latest angular. I have tested in angular 4.x

For Example:

var datePipe = new DatePipe('en-US');

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

An invalid XML character (Unicode: 0xc) was found

There are a few characters that are dissallowed in XML documents, even when you encapsulate data in CDATA-blocks.

If you generated the document you will need to entity encode it or strip it out. If you have an errorneous document, you should strip away these characters before trying to parse it.

See dolmens answer in this thread: Invalid Characters in XML

Where he links to this article: http://www.w3.org/TR/xml/#charsets

Basically, all characters below 0x20 is disallowed, except 0x9 (TAB), 0xA (CR?), 0xD (LF?)

How to get address of a pointer in c/c++?

In C++ you can do:

// Declaration and assign variable a
int a = 7;
// Declaration pointer b
int* b;
// Assign address of variable a to pointer b
b = &a;

// Declaration pointer c
int** c;
// Assign address of pointer b to pointer c
c = &b;

std::cout << "a: " << a << "\n";       // Print value of variable a
std::cout << "&a: " << &a << "\n";     // Print address of variable a

std::cout << "" << "" << "\n";

std::cout << "b: " << b << "\n";       // Print address of variable a
std::cout << "*b: " << *b << "\n";     // Print value of variable a
std::cout << "&b: " << &b << "\n";     // Print address of pointer b

std::cout << "" << "" << "\n";

std::cout << "c: " << c << "\n";       // Print address of pointer b
std::cout << "**c: " << **c << "\n";   // Print value of variable a
std::cout << "*c: " << *c << "\n";     // Print address of variable a
std::cout << "&c: " << &c << "\n";     // Print address of pointer c

Input type number "only numeric value" validation

You need to use regular expressions in your custom validator. For example, here's the code that allows only 9 digits in the input fields:

function ssnValidator(control: FormControl): {[key: string]: any} {
  const value: string = control.value || '';
  const valid = value.match(/^\d{9}$/);
  return valid ? null : {ssn: true};
}

Take a look at a sample app here:

https://github.com/Farata/angular2typescript/tree/master/Angular4/form-samples/src/app/reactive-validator

What is the best way to implement a "timer"?

Use the Timer class.

public static void Main()
{
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Interval = 5000;
    aTimer.Enabled = true;

    Console.WriteLine("Press \'q\' to quit the sample.");
    while(Console.Read() != 'q');
}

 // Specify what you want to happen when the Elapsed event is raised.
 private static void OnTimedEvent(object source, ElapsedEventArgs e)
 {
     Console.WriteLine("Hello World!");
 }

The Elapsed event will be raised every X amount of milliseconds, specified by the Interval property on the Timer object. It will call the Event Handler method you specify. In the example above, it is OnTimedEvent.

Git Push error: refusing to update checked out branch

I has this error because the git repo was (accidentally) initialised twice on the same location : first as a non-bare repo and shortly after as a bare repo. Because the .git folder remains, git assumes the repository is non-bare. Removing the .git folder and working directory data solved the issue.

Session state can only be used when enableSessionState is set to true either in a configuration

Following answer from below given path worked fine.

I found a solution that worked perfectly! Add the following to web.config:

<system.webServer>
<modules>
<!-- UrlRewriter code here -->
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition="" />
</modules>
</system.webServer>

Hope this helps someone else!

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

Excerpt from PostgreSQL documentation:

Restricting and cascading deletes are the two most common options. [...] CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well.

This means that if you delete a category – referenced by books – the referencing book will also be deleted by ON DELETE CASCADE.

Example:

CREATE SCHEMA shire;

CREATE TABLE shire.clans (
    id serial PRIMARY KEY,
    clan varchar
);

CREATE TABLE shire.hobbits (
    id serial PRIMARY KEY,
    hobbit varchar,
    clan_id integer REFERENCES shire.clans (id) ON DELETE CASCADE
);

DELETE FROM clans will CASCADE to hobbits by REFERENCES.

sauron@mordor> psql
sauron=# SELECT * FROM shire.clans;
 id |    clan    
----+------------
  1 | Baggins
  2 | Gamgi
(2 rows)

sauron=# SELECT * FROM shire.hobbits;
 id |  hobbit  | clan_id 
----+----------+---------
  1 | Bilbo    |       1
  2 | Frodo    |       1
  3 | Samwise  |       2
(3 rows)

sauron=# DELETE FROM shire.clans WHERE id = 1 RETURNING *;
 id |  clan   
----+---------
  1 | Baggins
(1 row)

DELETE 1
sauron=# SELECT * FROM shire.hobbits;
 id |  hobbit  | clan_id 
----+----------+---------
  3 | Samwise  |       2
(1 row)

If you really need the opposite (checked by the database), you will have to write a trigger!

How can I test that a variable is more than eight characters in PowerShell?

You can also use -match against a Regular expression. Ex:

if ($dbUserName -match ".{8}" )
{
    Write-Output " Please enter more than 8 characters "
    $dbUserName=read-host " Re-enter database user name"
}

Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.

How can I echo the whole content of a .html file in PHP?

If you want to make sure the HTML file doesn't contain any PHP code and will not be executed as PHP, do not use include or require. Simply do:

echo file_get_contents("/path/to/file.html");

How to insert values in two dimensional array programmatically?

In case you don't know in advance how many elements you will have to handle it might be a better solution to use collections instead (https://en.wikipedia.org/wiki/Java_collections_framework). It would be possible also to create a new bigger 2-dimensional array, copy the old data over and insert the new items there, but the collection framework handles this for you automatically.

In this case you could use a Map of Strings to Lists of Strings:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyClass {
    public static void main(String args[]) {
        Map<String, List<String>> shades = new HashMap<>();

        ArrayList<String> shadesOfGrey = new ArrayList<>();
        shadesOfGrey.add("lightgrey");
        shadesOfGrey.add("dimgray");
        shadesOfGrey.add("sgi gray 92");

        ArrayList<String> shadesOfBlue = new ArrayList<>();
        shadesOfBlue.add("dodgerblue 2");
        shadesOfBlue.add("steelblue 2");
        shadesOfBlue.add("powderblue");

        ArrayList<String> shadesOfYellow = new ArrayList<>();
        shadesOfYellow.add("yellow 1");
        shadesOfYellow.add("gold 1");
        shadesOfYellow.add("darkgoldenrod 1");

        ArrayList<String> shadesOfRed = new ArrayList<>();
        shadesOfRed.add("indianred 1");
        shadesOfRed.add("firebrick 1");
        shadesOfRed.add("maroon 1");

        shades.put("greys", shadesOfGrey);
        shades.put("blues", shadesOfBlue);
        shades.put("yellows", shadesOfYellow);
        shades.put("reds", shadesOfRed);

        System.out.println(shades.get("greys").get(0)); // prints "lightgrey"
    }
}

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

In my case, at some point I set my global config to use a cert that was meant for a project.

npm config list

/path/to/global/.npmrc
NODE_EXTRA_CA_CERTS = "./certs/chain.pem"

I opened the file, removed the line and npm install worked again.

jQuery exclude elements with certain class in selector

You can use the .not() method:

$(".content_box a").not(".button")

Alternatively, you can also use the :not() selector:

$(".content_box a:not('.button')")

There is little difference between the two approaches, except .not() is more readable (especially when chained) and :not() is very marginally faster. See this Stack Overflow answer for more info on the differences.

"relocation R_X86_64_32S against " linking Error

I've got a similar error when installing FCL that needs CCD lib(libccd) like this:

/usr/bin/ld: /usr/local/lib/libccd.a(ccd.o): relocation R_X86_64_32S against `a local symbol' can not be used when making a shared object; recompile with -fPIC

I find that there is two different files named "libccd.a" :

  1. /usr/local/lib/libccd.a
  2. /usr/local/lib/x86_64-linux-gnu/libccd.a

I solved the problem by removing the first file.

How to keep environment variables when using sudo

The trick is to add environment variables to sudoers file via sudo visudo command and add these lines:

Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy"

taken from ArchLinux wiki.

For Ubuntu 14, you need to specify in separate lines as it returns the errors for multi-variable lines:

Defaults  env_keep += "http_proxy"
Defaults  env_keep += "https_proxy"
Defaults  env_keep += "HTTP_PROXY"
Defaults  env_keep += "HTTPS_PROXY"

Display Parameter(Multi-value) in Report

You can use the "Join" function to create a single string out of the array of labels, like this:

=Join(Parameters!Product.Label, ",")

How do DATETIME values work in SQLite?

Store it in a field of type long. See Date.getTime() and new Date(long)

Sort a two dimensional array based on one column

  1. install java8 jdk+jre

  2. use lamda expression to sort 2D array.

code:

import java.util.Arrays;
import java.util.Comparator;

class SortString {

    public static void main(final String[] args) {
        final String[][] data = new String[][] {
                new String[] { "2009.07.25 20:24", "Message A" },
                new String[] { "2009.07.25 20:17", "Message G" },
                new String[] { "2009.07.25 20:25", "Message B" },
                new String[] { "2009.07.25 20:30", "Message D" },
                new String[] { "2009.07.25 20:01", "Message F" },
                new String[] { "2009.07.25 21:08", "Message E" },
                new String[] { "2009.07.25 19:54", "Message R" } 
        };
        // this is applicable only in java 8 version.
        Arrays.sort(data, (String[] s1, String[] s2) -> s1[0].compareTo(s2[0]));

        // we can also use Comparator.comparing and point to Comparable value we want to use        
        // Arrays.sort(data, Comparator.comparing(row->row[0]));

        for (final String[] s : data) {
            System.out.println(s[0] + " " + s[1]);
        }
    }
}

output

2009.07.25 19:54 Message R
2009.07.25 20:01 Message F
2009.07.25 20:17 Message G
2009.07.25 20:24 Message A
2009.07.25 20:25 Message B
2009.07.25 20:30 Message D
2009.07.25 21:08 Message E

How do you handle a "cannot instantiate abstract class" error in C++?

An abstract class cannot be instantiated by definition. In order to use this class, you must create a concrete subclass which implements all virtual functions of the class. In this case, you most likely have not implemented all the virtual functions declared in Light. This means that AmbientOccluder defaults to an abstract class. For us to further help you, you should include the details of the Light class.

Java Date vs Calendar

Date is a simpler class and is mainly there for backward compatibility reasons. If you need to set particular dates or do date arithmetic, use a Calendar. Calendars also handle localization. The previous date manipulation functions of Date have since been deprecated.

Personally I tend to use either time in milliseconds as a long (or Long, as appropriate) or Calendar when there is a choice.

Both Date and Calendar are mutable, which tends to present issues when using either in an API.

Java String import

Java compiler imports 3 packages by default. 1. The package without name 2. The java.lang package(That's why you can declare String, Integer, System classes without import) 3. The current package (current file's package)

That's why you don't need to declare import statement for the java.lang package.

How do I cast a JSON Object to a TypeScript class?

An old question with mostly correct, but not very efficient answers. This what I propose:

Create a base class that contains init() method and static cast methods (for a single object and an array). The static methods could be anywhere; the version with the base class and init() allows easy extensions afterwards.

export class ContentItem {
    // parameters: doc - plain JS object, proto - class we want to cast to (subclass of ContentItem)
    static castAs<T extends ContentItem>(doc: T, proto: typeof ContentItem): T {
        // if we already have the correct class skip the cast
        if (doc instanceof proto) { return doc; }
        // create a new object (create), and copy over all properties (assign)
        const d: T = Object.create(proto.prototype);
        Object.assign(d, doc);
        // reason to extend the base class - we want to be able to call init() after cast
        d.init(); 
        return d;
    }
    // another method casts an array
    static castAllAs<T extends ContentItem>(docs: T[], proto: typeof ContentItem): T[] {
        return docs.map(d => ContentItem.castAs(d, proto));
    }
    init() { }
}

Similar mechanics (with assign()) have been mentioned in @Adam111p post. Just another (more complete) way to do it. @Timothy Perez is critical of assign(), but imho it is fully appropriate here.

Implement a derived (the real) class:

import { ContentItem } from './content-item';

export class SubjectArea extends ContentItem {
    id: number;
    title: string;
    areas: SubjectArea[]; // contains embedded objects
    depth: number;

    // method will be unavailable unless we use cast
    lead(): string {
        return '. '.repeat(this.depth);
    }

    // in case we have embedded objects, call cast on them here
    init() {
        if (this.areas) {
            this.areas = ContentItem.castAllAs(this.areas, SubjectArea);
        }
    }
}

Now we can cast an object retrieved from service:

const area = ContentItem.castAs<SubjectArea>(docFromREST, SubjectArea);

All hierarchy of SubjectArea objects will have correct class.

A use case/example; create an Angular service (abstract base class again):

export abstract class BaseService<T extends ContentItem> {
  BASE_URL = 'http://host:port/';
  protected abstract http: Http;
  abstract path: string;
  abstract subClass: typeof ContentItem;

  cast(source: T): T {
    return ContentItem.castAs(source, this.subClass);
  }
  castAll(source: T[]): T[] {
    return ContentItem.castAllAs(source, this.subClass);
  }

  constructor() { }

  get(): Promise<T[]> {
    const value = this.http.get(`${this.BASE_URL}${this.path}`)
      .toPromise()
      .then(response => {
        const items: T[] = this.castAll(response.json());
        return items;
      });
    return value;
  }
}

The usage becomes very simple; create an Area service:

@Injectable()
export class SubjectAreaService extends BaseService<SubjectArea> {
  path = 'area';
  subClass = SubjectArea;

  constructor(protected http: Http) { super(); }
}

get() method of the service will return a Promise of an array already cast as SubjectArea objects (whole hierarchy)

Now say, we have another class:

export class OtherItem extends ContentItem {...}

Creating a service that retrieves data and casts to the correct class is as simple as:

@Injectable()
export class OtherItemService extends BaseService<OtherItem> {
  path = 'other';
  subClass = OtherItem;

  constructor(protected http: Http) { super(); }
}

How to make correct date format when writing data to Excel

Try using

DateTime.ToOADate()

And putting that as a double in the cell. There could be issues with Excel on Mac Systems (it uses a different datetime-->double conversion), but it should work well for most cases.

Hope this helps.

How do I serialize a Python dictionary into a string, and then back to a dictionary?

One thing json cannot do is dict indexed with numerals. The following snippet

import json
dictionary = dict({0:0, 1:5, 2:10})
serialized = json.dumps(dictionary)
unpacked   = json.loads(serialized)
print(unpacked[0])

will throw

KeyError: 0

Because keys are converted to strings. cPickle preserves the numeric type and the unpacked dict can be used right away.

Angular 2 How to redirect to 404 or other path if the path does not exist

For version v2.2.2 and newer

In version v2.2.2 and up, name property no longer exists and it shouldn't be used to define the route. path should be used instead of name and no leading slash is needed on the path. In this case use path: '404' instead of path: '/404':

 {path: '404', component: NotFoundComponent},
 {path: '**', redirectTo: '/404'}

For versions older than v2.2.2

you can use {path: '/*path', redirectTo: ['redirectPathName']}:

{path: '/home/...', name: 'Home', component: HomeComponent}
{path: '/', redirectTo: ['Home']},
{path: '/user/...', name: 'User', component: UserComponent},
{path: '/404', name: 'NotFound', component: NotFoundComponent},

{path: '/*path', redirectTo: ['NotFound']}

if no path matches then redirect to NotFound path

Select all DIV text with single mouse click

For content editable stuff (not regular inputs, you need to use selectNodeContents (rather than just selectNode).

NOTE: All the references to "document.selection" and "createTextRange()" are for IE 8 and lower... You'll not likely need to support that monster if you're attempting to do tricky stuff like this.

function selectElemText(elem) {

    //Create a range (a range is a like the selection but invisible)
    var range = document.createRange();

    // Select the entire contents of the element
    range.selectNodeContents(elem);

    // Don't select, just positioning caret:
    // In front 
    // range.collapse();
    // Behind:
    // range.collapse(false);

    // Get the selection object
    var selection = window.getSelection();

    // Remove any current selections
    selection.removeAllRanges();

    // Make the range you have just created the visible selection
    selection.addRange(range);

}

Android Gradle Apache HttpClient does not exist?

copy org.apache.http.legacy.jar which is in Android/Sdk/platforms/android-23/optional folder to to app/libs

and also added this line to app.gradle file

compile files('libs/org.apache.http.legacy.jar')

But if you're using more jar libraries, you can use this way

compile fileTree(dir: 'libs', include: ['*.jar'])

How do I get the information from a meta tag with JavaScript?

Here's a function that will return the content of any meta tag and will memoize the result, avoiding unnecessary querying of the DOM.

var getMetaContent = (function(){
        var metas = {};
        var metaGetter = function(metaName){
            var theMetaContent, wasDOMQueried = true;;
            if (metas[metaName]) {
                theMetaContent = metas[metaName];
                wasDOMQueried = false;
            }
            else {
                 Array.prototype.forEach.call(document.getElementsByTagName("meta"), function(el) {
                    if (el.name === metaName) theMetaContent = el.content;
                    metas[metaName] = theMetaContent;
                });
            }
            console.log("Q:wasDOMQueried? A:" + wasDOMQueried);
            return theMetaContent;
        }
        return metaGetter;
    })();

getMetaContent("description"); /* getMetaContent console.logs the content of the description metatag. If invoked a second time it confirms that the DOM  was only queried once */

And here's an extended version that also queries for open graph tags, and uses Array#some:

var getMetaContent = (function(){
        var metas = {};
        var metaGetter = function(metaName){
            wasDOMQueried = true;
            if (metas[metaName]) {
                wasDOMQueried = false;
            }
            else {
                 Array.prototype.some.call(document.getElementsByTagName("meta"), function(el) {
                        if(el.name === metaName){
                           metas[metaName] = el.content;
                           return true;
                        }
                        if(el.getAttribute("property") === metaName){
                           metas[metaName] = el.content;
                           return true;
                        }
                        else{
                          metas[metaName] = "meta tag not found";
                        }  
                    });
            }
            console.info("Q:wasDOMQueried? A:" + wasDOMQueried);
            console.info(metas);
            return metas[metaName];
        }
        return metaGetter;
    })();

getMetaContent("video"); // "http://video.com/video33353.mp4"

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

How to set image name in Dockerfile?

Tagging of the image isn't supported inside the Dockerfile. This needs to be done in your build command. As a workaround, you can do the build with a docker-compose.yml that identifies the target image name and then run a docker-compose build. A sample docker-compose.yml would look like

version: '2'

services:
  man:
    build: .
    image: dude/man:v2

That said, there's a push against doing the build with compose since that doesn't work with swarm mode deploys. So you're back to running the command as you've given in your question:

docker build -t dude/man:v2 .

Personally, I tend to build with a small shell script in my folder (build.sh) which passes any args and includes the name of the image there to save typing. And for production, the build is handled by a ci/cd server that has the image name inside the pipeline script.

Insert Data Into Temp Table with Query

use as at end of query

Select * into #temp (select * from table1,table2) as temp_table

Split Spark Dataframe string column into multiple columns

Here's another approach, in case you want split a string with a delimiter.

import pyspark.sql.functions as f

df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
|   value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+

df_split = df.select(f.split(df.value,":")).rdd.flatMap(
              lambda x: x).toDF(schema=["col1","col2","col3"])

df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   a|2001|
|   2|   b|2002|
|   3|   c|2003|
+----+----+----+

I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.

How do I make XAML DataGridColumns fill the entire DataGrid?

My 2 Cent ->

Very late to party

DataGrid -> Column -> Width="*" only work if DataGrid parent container has fix width.

example : i put the DataGrid in Grid -> Column whose width="Auto" then Width="*" in DataGrid does not work but if you set Grid -> Column Width="450" mean fixed then it work fine

What does Include() do in LINQ?

Think of it as enforcing Eager-Loading in a scenario where you sub-items would otherwise be lazy-loading.

The Query EF is sending to the database will yield a larger result at first, but on access no follow-up queries will be made when accessing the included items.

On the other hand, without it, EF would execute separte queries later, when you first access the sub-items.

Is there a way to set background-image as a base64 encoded image?

In my case, it was just because I didn't set the height and width.

But there is another issue.

The background image could be removed using

element.style.backgroundImage=""

but couldn't be set using

element.style.backgroundImage="some base64 data"

Jquery works fine.

How can I declare enums using java

public enum MyEnum {
   ONE(1),
   TWO(2);
   private int value;
   private MyEnum(int value) {
      this.value = value;
   }
   public int getValue() {
      return value;
   }
}

In short - you can define any number of parameters for the enum as long as you provide constructor arguments (and set the values to the respective fields)

As Scott noted - the official enum documentation gives you the answer. Always start from the official documentation of language features and constructs.

Update: For strings the only difference is that your constructor argument is String, and you declare enums with TEST("test")

Should a function have only one return statement?

I've worked with terrible coding standards that forced a single exit path on you and the result is nearly always unstructured spaghetti if the function is anything but trivial -- you end up with lots of breaks and continues that just get in the way.

SQL providerName in web.config

System.Data.SqlClient is the .NET Framework Data Provider for SQL Server. ie .NET library for SQL Server.

I don't know where providerName=SqlServer comes from. Could you be getting this confused with the provider keyword in your connection string? (I know I was :) )

In the web.config you should have the System.Data.SqlClient as the value of the providerName attribute. It is the .NET Framework Data Provider you are using.

<connectionStrings>
   <add 
      name="LocalSqlServer" 
      connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" 
      providerName="System.Data.SqlClient"
   />
</connectionStrings>

See http://msdn.microsoft.com/en-US/library/htw9h4z3(v=VS.80).aspx

Error when using scp command "bash: scp: command not found"

Check if scp is installed or not on from where you want want to copy check using which scp

If it's already installed, it will print you a path like /usr/bin/scp Else, install scp using:

yum -y install openssh-clients

Then copy command

scp -r [email protected]:/var/www/html/database_backup/restore_fullbackup/backup_20140308-023002.sql  /var/www/html/db_bkp/

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

The profiler trace puts it into perspective.

  • Query A: 1.3 secs CPU, 1.4 secs duration
  • Query B: 2.3 secs CPU, 1.2 secs duration

Query B is using parallelism: CPU > duration eg the query uses 2 CPUs, average 1.15 secs each

Query A is probably not: CPU < duration

This explains cost relative to batch: 17% of the for the simpler, non-parallel query plan.

The optimiser works out that query B is more expensive and will benefit from parallelism, even though it takes extra effort to do so.

Remember though, that query B uses 100% of 2 CPUS (so 50% for 4 CPUs) for one second or so. Query A uses 100% of a single CPU for 1.5 seconds.

The peak for query A is lower, at the expense of increased duration. With one user, who cares? With 100, perhaps it makes a difference...

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

if (x) 

coerces x using JavaScript's internal toBoolean (http://es5.github.com/#x9.2)

x == false

coerces both sides using internal toNumber coercion (http://es5.github.com/#x9.3) or toPrimitive for objects (http://es5.github.com/#x9.1)

For full details see http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/

ToList()-- does it create a new list?

From the Reflector'd source:

public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    return new List<TSource>(source);
}

So yes, your original list won't be updated (i.e. additions or removals) however the referenced objects will.

How to pass arguments to a Button command in Tkinter?

Building on Matt Thompsons answer : a class can be made callable so it can be used instead of a function:

import tkinter as tk

class Callback:
    def __init__(self, func, *args, **kwargs):
        self.func = func
        self.args = args
        self.kwargs = kwargs
    def __call__(self):
        self.func(*self.args, **self.kwargs)

def default_callback(t):
    print("Button '{}' pressed.".format(t))

root = tk.Tk()

buttons = ["A", "B", "C"]

for i, b in enumerate(buttons):
    tk.Button(root, text=b, command=Callback(default_callback, b)).grid(row=i, column=0)

tk.mainloop()

Indent List in HTML and CSS

I solved the same problem by adding text-indent to the nested list.

<h4>A nested List:</h4>
<ul>
  <li>Coffee</li>
  <li>Tea
    <ul id="list2">
    <li>Black tea</li>
    <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

#list2
{
 text-indent:50px;
}

why is plotting with Matplotlib so slow?

To start, Joe Kington's answer provides very good advice using a gui-neutral approach, and you should definitely take his advice (especially about Blitting) and put it into practice. More info on this approach, read the Matplotlib Cookbook

However, the non-GUI-neutral (GUI-biased?) approach is key to speeding up the plotting. In other words, the backend is extremely important to plot speed.

Put these two lines before you import anything else from matplotlib:

import matplotlib
matplotlib.use('GTKAgg') 

Of course, there are various options to use instead of GTKAgg, but according to the cookbook mentioned before, this was the fastest. See the link about backends for more options.

Excel 2007 - Compare 2 columns, find matching values

=VLOOKUP(lookup_value,table_array,col_index_num,range_lookup) will solve this issue.

This will search for a value in the first column to the left and return the value in the same row from a specific column.

Foreign keys in mongo?

How to design table like this in mongodb?

First, to clarify some naming conventions. MongoDB uses collections instead of tables.

I think there are no foreign keys!

Take the following model:

student
{ 
  _id: ObjectId(...),
  name: 'Jane',
  courses: [
    { course: 'bio101', mark: 85 },
    { course: 'chem101', mark: 89 }
  ]
}

course
{
  _id: 'bio101',
  name: 'Biology 101',
  description: 'Introduction to biology'
}

Clearly Jane's course list points to some specific courses. The database does not apply any constraints to the system (i.e.: foreign key constraints), so there are no "cascading deletes" or "cascading updates". However, the database does contain the correct information.

In addition, MongoDB has a DBRef standard that helps standardize the creation of these references. In fact, if you take a look at that link, it has a similar example.

How can I solve this task?

To be clear, MongoDB is not relational. There is no standard "normal form". You should model your database appropriate to the data you store and the queries you intend to run.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

As the error message is trying very hard to tell you, you can't deserialize a single object into a collection (List<>).

You want to deserialize into a single RootObject.

Check if a row exists using old mysql_* API

This ought to do the trick: just limit the result to 1 row; if a row comes back the $lectureName is Assigned, otherwise it's Available.

function checkLectureStatus($lectureName)
{
    $con = connectvar();
    mysql_select_db("mydatabase", $con);
    $result = mysql_query(
        "SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");

    if(mysql_fetch_array($result) !== false)
        return 'Assigned';
    return 'Available';
}

Remove last character from string. Swift language

Use the function advance(startIndex, endIndex):

var str = "45+22"
str = str.substringToIndex(advance(str.startIndex, countElements(str) - 1))

python encoding utf-8

You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode before it can encode it back to UTF-8. That is what is failing here:

>>> data = u'\u00c3'            # Unicode data
>>> data = data.encode('utf8')  # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8')         # Try to *re*-encode it
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Just write your data directly to the file, there is no need to encode already-encoded data.

If you instead build up unicode values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open() instead, which returns a file object that will encode unicode values to UTF-8 for you.

You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).

For your MySQL insert problem, you need to do two things:

  • Add charset='utf8' to your MySQLdb.connect() call.

  • Use unicode objects, not str objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:

    artiste = artiste.decode('utf8')  # it is already UTF8, decode to unicode
    
    c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    
    # ...
    
    c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
    

It may actually work better if you used codecs.open() to decode the contents automatically instead:

import codecs

sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')

with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
    for line in findex:
        if u'#artiste' not in line:
            continue

        artiste=line.split(u'[:::]')[1].strip()

    cursor = sql.cursor()
    cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    if not cursor.fetchone()[0]:
        cursor = sql.cursor()
        cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
        artists_inserted += 1

You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:

Microsoft SQL Server 2005 service fails to start

While that error message is on the screen (before the rollback begins) go to Control Panel -> Administrative Tools -> Services and see if the service is actually installed. Also check what account it is using to run as. If it's not using Local System, then double and triple check that the account it's using has rights to the program directory where MS SQL installed to.

Difference between binary semaphore and mutex

You can clearly remember difference by this:

  1. Mutex lock : is for protecting critical region, Mutex can't be used across processes, only used in single process

  2. Semaphore: is for signalling availability of a resource. Semaphore can be used both across processes and across processes.

How to capture no file for fs.readFileSync()?

I use an immediately invoked lambda for these scenarios:

const config = (() => {
  try {
    return JSON.parse(fs.readFileSync('config.json'));
  } catch (error) {
    return {};
  }
})();

async version:

const config = await (async () => {
  try {
    return JSON.parse(await fs.readFileAsync('config.json'));
  } catch (error) {
    return {};
  }
})();

How to drop a PostgreSQL database if there are active connections to it?

Here's my hack... =D

# Make sure no one can connect to this database except you!
sudo -u postgres /usr/pgsql-9.4/bin/psql -c "UPDATE pg_database SET datallowconn=false WHERE datname='<DATABASE_NAME>';"

# Drop all existing connections except for yours!
sudo -u postgres /usr/pgsql-9.4/bin/psql -c "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '<DATABASE_NAME>' AND pid <> pg_backend_pid();"

# Drop database! =D
sudo -u postgres /usr/pgsql-9.4/bin/psql -c "DROP DATABASE <DATABASE_NAME>;"

I put this answer because include a command (above) to block new connections and because any attempt with the command...

REVOKE CONNECT ON DATABASE <DATABASE_NAME> FROM PUBLIC, <USERS_ETC>;

... do not works to block new connections!

Thanks to @araqnid @GoatWalker ! =D

https://stackoverflow.com/a/3185413/3223785

jQuery function to get all unique elements from an array?

Just use this code as the basis of a simple JQuery plugin.

$.extend({
    distinct : function(anArray) {
       var result = [];
       $.each(anArray, function(i,v){
           if ($.inArray(v, result) == -1) result.push(v);
       });
       return result;
    }
});

Use as so:

$.distinct([0,1,2,2,3]);

Check date between two other dates spring data jpa

Maybe you could try

List<Article> findAllByPublicationDate(Date publicationDate);

The detail could be checked in this article:

https://www.baeldung.com/spring-data-jpa-query-by-date

Padding is invalid and cannot be removed?

I came across this error while attempting to pass an un-encrypted file path to the Decrypt method.The solution was to check if the passed file is encrypted first before attempting to decrypt

if (Sec.IsFileEncrypted(e.File.FullName))
{
    var stream = Sec.Decrypt(e.File.FullName);
} 
else
{
    // non-encrypted scenario  
}

Creating a BAT file for python script

Open a command line (? Win+R, cmd, ? Enter) and type python -V, ? Enter.

You should get a response back, something like Python 2.7.1.

If you do not, you may not have Python installed. Fix this first.

Once you have Python, your batch file should look like

@echo off
python c:\somescript.py %*
pause

This will keep the command window open after the script finishes, so you can see any errors or messages. Once you are happy with it you can remove the 'pause' line and the command window will close automatically when finished.

Is there a regular expression to detect a valid regular expression?

The following example by Paul McGuire, originally from the pyparsing wiki, but now available only through the Wayback Machine, gives a grammar for parsing some regexes, for the purposes of returning the set of matching strings. As such, it rejects those re's that include unbounded repetition terms, like '+' and '*'. But it should give you an idea about how to structure a parser that would process re's.

# 
# invRegex.py
#
# Copyright 2008, Paul McGuire
#
# pyparsing script to expand a regular expression into all possible matching strings
# Supports:
# - {n} and {m,n} repetition, but not unbounded + or * repetition
# - ? optional elements
# - [] character ranges
# - () grouping
# - | alternation
#
__all__ = ["count","invert"]

from pyparsing import (Literal, oneOf, printables, ParserElement, Combine, 
    SkipTo, operatorPrecedence, ParseFatalException, Word, nums, opAssoc,
    Suppress, ParseResults, srange)

class CharacterRangeEmitter(object):
    def __init__(self,chars):
        # remove duplicate chars in character range, but preserve original order
        seen = set()
        self.charset = "".join( seen.add(c) or c for c in chars if c not in seen )
    def __str__(self):
        return '['+self.charset+']'
    def __repr__(self):
        return '['+self.charset+']'
    def makeGenerator(self):
        def genChars():
            for s in self.charset:
                yield s
        return genChars

class OptionalEmitter(object):
    def __init__(self,expr):
        self.expr = expr
    def makeGenerator(self):
        def optionalGen():
            yield ""
            for s in self.expr.makeGenerator()():
                yield s
        return optionalGen

class DotEmitter(object):
    def makeGenerator(self):
        def dotGen():
            for c in printables:
                yield c
        return dotGen

class GroupEmitter(object):
    def __init__(self,exprs):
        self.exprs = ParseResults(exprs)
    def makeGenerator(self):
        def groupGen():
            def recurseList(elist):
                if len(elist)==1:
                    for s in elist[0].makeGenerator()():
                        yield s
                else:
                    for s in elist[0].makeGenerator()():
                        for s2 in recurseList(elist[1:]):
                            yield s + s2
            if self.exprs:
                for s in recurseList(self.exprs):
                    yield s
        return groupGen

class AlternativeEmitter(object):
    def __init__(self,exprs):
        self.exprs = exprs
    def makeGenerator(self):
        def altGen():
            for e in self.exprs:
                for s in e.makeGenerator()():
                    yield s
        return altGen

class LiteralEmitter(object):
    def __init__(self,lit):
        self.lit = lit
    def __str__(self):
        return "Lit:"+self.lit
    def __repr__(self):
        return "Lit:"+self.lit
    def makeGenerator(self):
        def litGen():
            yield self.lit
        return litGen

def handleRange(toks):
    return CharacterRangeEmitter(srange(toks[0]))

def handleRepetition(toks):
    toks=toks[0]
    if toks[1] in "*+":
        raise ParseFatalException("",0,"unbounded repetition operators not supported")
    if toks[1] == "?":
        return OptionalEmitter(toks[0])
    if "count" in toks:
        return GroupEmitter([toks[0]] * int(toks.count))
    if "minCount" in toks:
        mincount = int(toks.minCount)
        maxcount = int(toks.maxCount)
        optcount = maxcount - mincount
        if optcount:
            opt = OptionalEmitter(toks[0])
            for i in range(1,optcount):
                opt = OptionalEmitter(GroupEmitter([toks[0],opt]))
            return GroupEmitter([toks[0]] * mincount + [opt])
        else:
            return [toks[0]] * mincount

def handleLiteral(toks):
    lit = ""
    for t in toks:
        if t[0] == "\\":
            if t[1] == "t":
                lit += '\t'
            else:
                lit += t[1]
        else:
            lit += t
    return LiteralEmitter(lit)    

def handleMacro(toks):
    macroChar = toks[0][1]
    if macroChar == "d":
        return CharacterRangeEmitter("0123456789")
    elif macroChar == "w":
        return CharacterRangeEmitter(srange("[A-Za-z0-9_]"))
    elif macroChar == "s":
        return LiteralEmitter(" ")
    else:
        raise ParseFatalException("",0,"unsupported macro character (" + macroChar + ")")

def handleSequence(toks):
    return GroupEmitter(toks[0])

def handleDot():
    return CharacterRangeEmitter(printables)

def handleAlternative(toks):
    return AlternativeEmitter(toks[0])


_parser = None
def parser():
    global _parser
    if _parser is None:
        ParserElement.setDefaultWhitespaceChars("")
        lbrack,rbrack,lbrace,rbrace,lparen,rparen = map(Literal,"[]{}()")

        reMacro = Combine("\\" + oneOf(list("dws")))
        escapedChar = ~reMacro + Combine("\\" + oneOf(list(printables)))
        reLiteralChar = "".join(c for c in printables if c not in r"\[]{}().*?+|") + " \t"

        reRange = Combine(lbrack + SkipTo(rbrack,ignore=escapedChar) + rbrack)
        reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) )
        reDot = Literal(".")
        repetition = (
            ( lbrace + Word(nums).setResultsName("count") + rbrace ) |
            ( lbrace + Word(nums).setResultsName("minCount")+","+ Word(nums).setResultsName("maxCount") + rbrace ) |
            oneOf(list("*+?")) 
            )

        reRange.setParseAction(handleRange)
        reLiteral.setParseAction(handleLiteral)
        reMacro.setParseAction(handleMacro)
        reDot.setParseAction(handleDot)

        reTerm = ( reLiteral | reRange | reMacro | reDot )
        reExpr = operatorPrecedence( reTerm,
            [
            (repetition, 1, opAssoc.LEFT, handleRepetition),
            (None, 2, opAssoc.LEFT, handleSequence),
            (Suppress('|'), 2, opAssoc.LEFT, handleAlternative),
            ]
            )
        _parser = reExpr

    return _parser

def count(gen):
    """Simple function to count the number of elements returned by a generator."""
    i = 0
    for s in gen:
        i += 1
    return i

def invert(regex):
    """Call this routine as a generator to return all the strings that
       match the input regular expression.
           for s in invert("[A-Z]{3}\d{3}"):
               print s
    """
    invReGenerator = GroupEmitter(parser().parseString(regex)).makeGenerator()
    return invReGenerator()

def main():
    tests = r"""
    [A-EA]
    [A-D]*
    [A-D]{3}
    X[A-C]{3}Y
    X[A-C]{3}\(
    X\d
    foobar\d\d
    foobar{2}
    foobar{2,9}
    fooba[rz]{2}
    (foobar){2}
    ([01]\d)|(2[0-5])
    ([01]\d\d)|(2[0-4]\d)|(25[0-5])
    [A-C]{1,2}
    [A-C]{0,3}
    [A-C]\s[A-C]\s[A-C]
    [A-C]\s?[A-C][A-C]
    [A-C]\s([A-C][A-C])
    [A-C]\s([A-C][A-C])?
    [A-C]{2}\d{2}
    @|TH[12]
    @(@|TH[12])?
    @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?
    @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?|30?|[4-9]))?
    (([ECMP]|HA|AK)[SD]|HS)T
    [A-CV]{2}
    A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]
    (a|b)|(x|y)
    (a|b) (x|y)
    """.split('\n')

    for t in tests:
        t = t.strip()
        if not t: continue
        print '-'*50
        print t
        try:
            print count(invert(t))
            for s in invert(t):
                print s
        except ParseFatalException,pfe:
            print pfe.msg
            print
            continue
        print

if __name__ == "__main__":
    main()

How can I disable ARC for a single file in a project?

Note: if you want to disable ARC for many files, you have to:

  1. open "Build phases" -> "Compile sources"
  2. select files with "left_mouse" + "cmd" (for separated files) or + "shift" (for grouped files - select first and last)
  3. press "enter"
  4. paste -fno-objc-arc
  5. press "enter" again
  6. profit!

What are the options for (keyup) in Angular2?

One like with events

(keydown)="$event.keyCode != 32 ? $event:$event.preventDefault()"

Show "loading" animation on button click

If you are using ajax then (making it as simple as possible)

  1. Add your loading gif image to html and make it hidden (using style in html itself now, you can add it to separate CSS):

    <img src="path\to\loading\gif" id="img" style="display:none"/ >
    
  2. Show the image when button is clicked and hide it again on success function

    $('#buttonID').click(function(){
      $('#img').show(); //<----here
      $.ajax({
        ....
       success:function(result){
           $('#img').hide();  //<--- hide again
       }
    }
    

Make sure you hide the image on ajax error callbacks too to make sure the gif hides even if the ajax fails.

What is the difference between docker-compose ports vs expose

According to the docker-compose reference,

Ports is defined as:

Expose ports. Either specify both ports (HOST:CONTAINER), or just the container port (a random host port will be chosen).

  • Ports mentioned in docker-compose.yml will be shared among different services started by the docker-compose.
  • Ports will be exposed to the host machine to a random port or a given port.

My docker-compose.yml looks like:

mysql:
  image: mysql:5.7
  ports:
    - "3306"

If I do docker-compose ps, it will look like:

  Name                     Command               State            Ports
-------------------------------------------------------------------------------------
  mysql_1       docker-entrypoint.sh mysqld      Up      0.0.0.0:32769->3306/tcp

Expose is defined as:

Expose ports without publishing them to the host machine - they’ll only be accessible to linked services. Only the internal port can be specified.

Ports are not exposed to host machines, only exposed to other services.

mysql:
  image: mysql:5.7
  expose:
    - "3306"

If I do docker-compose ps, it will look like:

  Name                  Command             State    Ports
---------------------------------------------------------------
 mysql_1      docker-entrypoint.sh mysqld   Up      3306/tcp

Edit

In recent versions of Docker, expose doesn't have any operational impact anymore, it is just informative. (see also)

What does Visual Studio mean by normalize inconsistent line endings?

What that usually means is that you have lines ending with something other than a carriage return/line feed pair. It often happens when you copy and paste from a web page into the code editor.

Normalizing the line endings is just making sure that all of the line ending characters are consistent. It prevents one line from ending in \r\n and another ending with \r or \n; the first is the Windows line end pair, while the others are typically used for Mac or Linux files.

Since you're developing in Visual Studio, you'll obviously want to choose "Windows" from the drop down. :-)

How to force a checkbox and text on the same line?

It wont break if you wrap each item in a div. Check out my fiddle with the link below. I made the width of the fieldset 125px and made each item 50px wide. You'll see the label and checkbox remain side by side on a new line and don't break.

<fieldset>
<div class="item">
    <input type="checkbox" id="a">
    <label for="a">a</label>
</div>
<div class="item">
   <input type="checkbox" id="b">
<!-- depending on width, a linebreak can occur here. -->
    <label for="b">bgf bh fhg fdg hg dg gfh dfgh</label>
</div>
<div class="item">
    <input type="checkbox" id="c">
    <label for="c">c</label>
</div>
</fieldset>

http://jsfiddle.net/t5dwp7pg/1/

How can I get the username of the logged-in user in Django?

For classed based views use self.request.user.id

How to find the foreach index?

foreach(array_keys($array) as $key) {
//  do stuff
}

How do I use installed packages in PyCharm?

DON'T change the interpreter path.

Change the project structure instead:

File -> Settings -> Project -> Project structure -> Add content root

Targeting both 32bit and 64bit with Visual Studio in same solution/project

If you use Custom Actions written in .NET as part of your MSI installer then you have another problem.

The 'shim' that runs these custom actions is always 32bit then your custom action will run 32bit as well, despite what target you specify.

More info & some ninja moves to get around (basically change the MSI to use the 64 bit version of this shim)

Building an MSI in Visual Studio 2005/2008 to work on a SharePoint 64

64-bit Managed Custom Actions with Visual Studio

Force table column widths to always be fixed regardless of contents

You can add a div to the td, then style that. It should work as you expected.

<td><div>AAAAAAAAAAAAAAAAAAA</div></td>

Then the css.

td div { width: 50px; overflow: hidden; }

405 method not allowed Web API

Old question but none of the answers worked for me.

This article solved my problem by adding the following lines to web.config:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
  </modules>
</system.webServer>

How do I save a stream to a file in C#?

//If you don't have .Net 4.0  :)

public void SaveStreamToFile(Stream stream, string filename)
{  
   using(Stream destination = File.Create(filename))
      Write(stream, destination);
}

//Typically I implement this Write method as a Stream extension method. 
//The framework handles buffering.

public void Write(Stream from, Stream to)
{
   for(int a = from.ReadByte(); a != -1; a = from.ReadByte())
      to.WriteByte( (byte) a );
}

/*
Note, StreamReader is an IEnumerable<Char> while Stream is an IEnumbable<byte>.
The distinction is significant such as in multiple byte character encodings 
like Unicode used in .Net where Char is one or more bytes (byte[n]). Also, the
resulting translation from IEnumerable<byte> to IEnumerable<Char> can loose bytes
or insert them (for example, "\n" vs. "\r\n") depending on the StreamReader instance
CurrentEncoding.
*/

How to write URLs in Latex?

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

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

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

Hide a EditText & make it visible by clicking a menu

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.waist2height); {
        final EditText edit = (EditText)findViewById(R.id.editText);          
        final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
        final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);                       
        if(rb1.isChecked()){    
            edit.setVisibility(View.VISIBLE);              
        }
        else if(rb2.isChecked()){               
            edit.setVisibility(View.INVISIBLE);
        }
}

Delete column from pandas DataFrame

We can Remove or Delete a specified column or sprcified columns by drop() method.

Suppose df is a dataframe.

Column to be removed = column0

Code:

df = df.drop(column0, axis=1)

To remove multiple columns col1, col2, . . . , coln, we have to insert all the columns that needed to be removed in a list. Then remove them by drop() method.

Code:

df = df.drop([col1, col2, . . . , coln], axis=1)

I hope it would be helpful.

How to save LogCat contents to file?

To save the Log cat content to the file, you need to redirect to the android sdk's platform tools folder and hit the below command

adb logcat > logcat.txt

In Android Studio, version 3.6RC1, file will be created of the name "logcat.txt" in respective project folder. you can change the name according to your interest. enjoy

Default values and initialization in Java

Local variables do not get default values. Their initial values are undefined without assigning values by some means. Before you can use local variables they must be initialized.

There is a big difference when you declare a variable at class level (as a member, i.e., as a field) and at the method level.

If you declare a field at the class level they get default values according to their type. If you declare a variable at the method level or as a block (means any code inside {}) do not get any values and remain undefined until somehow they get some starting values, i.e., some values assigned to them.

Select row on click react-table

I am not familiar with, react-table, so I do not know it has direct support for selecting and deselecting (it would be nice if it had).

If it does not, with the piece of code you already have you can install the onCLick handler. Now instead of trying to attach style directly to row, you can modify state, by for instance adding selected: true to row data. That would trigger rerender. Now you only have to override how are rows with selected === true rendered. Something along lines of:

// Any Tr element will be green if its (row.age > 20) 
<ReactTable
  getTrProps={(state, rowInfo, column) => {
    return {
      style: {
        background: rowInfo.row.selected ? 'green' : 'red'
      }
    }
  }}
/>

nginx upload client_max_body_size issue

From the documentation:

It is necessary to keep in mind that the browsers do not know how to correctly show this error.

I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.

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

Adding androidTestImplementation 'androidx.test:runner:1.2.0-alpha05' works for me.

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

You can automatically encode into Json, your complex entity with:

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new 
JsonEncoder()));
$json = $serializer->serialize($entity, 'json');

Convert text into number in MySQL query

one simple way SELECT '123'+ 0

HTML form action and onsubmit issues

You should stop the submit procedure by returning false on the onsubmit callback.

<script>
    function checkRegistration(){
        if(!form_valid){
            alert('Given data is not correct');
            return false;
        }
        return true;
    }
</script>

<form onsubmit="return checkRegistration()"...

Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:

<script>
    function checkRegistration(){
        var form_valid = (document.getElementById('some_input').value == 'google');
        if(!form_valid){
            alert('Given data is incorrect');
            return false;
        }
        return true;
    }
</script>

<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
    Write google to go to google...<br/>
    <input type="text" id="some_input" value=""/>
    <input type="submit" value="google it"/>
</form>

Why do I have ORA-00904 even when the column is present?

I use Toad for Oracle and if the table is owned by another username than the one you logged in as and you have access to read the table, you still may need to add the original table owner to the table name.

For example, lets say the table owner's name is 'OWNER1' and you are logged in as 'USER1'. This query may give you a ORA-00904 error:

select * from table_name where x='test';

Prefixing the table_name with the table owner eliminated the error and gives results:

select * from 

Pass props in Link react-router

there is a way you can pass more than one parameter. You can pass "to" as object instead of string.

// your route setup
<Route path="/category/:catId" component={Category} / >

// your link creation
const newTo = { 
  pathname: "/category/595212758daa6810cbba4104", 
  param1: "Par1" 
};
// link to the "location"
// see (https://reacttraining.com/react-router/web/api/location)
<Link to={newTo}> </Link>

// In your Category Component, you can access the data like this
this.props.match.params.catId // this is 595212758daa6810cbba4104 
this.props.location.param1 // this is Par1

Pagination using MySQL LIMIT, OFFSET

First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:

http://yoursite.com/itempage.php?page=2

You can access the requested page number via $_GET['page'].

This makes your SQL formulation really easy:

// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
    if(false === $page) {
        $page = 1;
    }
}

// set the number of items to display per page
$items_per_page = 4;

// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;

So for example if input here was page=2, with 4 rows per page, your query would be"

SELECT * FROM menuitem LIMIT 4,4

So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).

In order to do this, you must understand the number of rows in the table.

You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).

This is actually quite simple:

$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
if(false === $result) {
   throw new Exception('Query failed with: ' . mysqli_error());
} else {
   $row_count = mysqli_num_rows($result);
   // free the result set as you don't need it anymore
   mysqli_free_result($result);
}

$page_count = 0;
if (0 === $row_count) {  
    // maybe show some error since there is nothing in your table
} else {
   // determine page_count
   $page_count = (int)ceil($row_count / $items_per_page);
   // double check that request page is in range
   if($page > $page_count) {
        // error to user, maybe set page to 1
        $page = 1;
   }
}

// make your LIMIT query here as shown above


// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
   if ($i === $page) { // this is current page
       echo 'Page ' . $i . '<br>';
   } else { // show link to other page   
       echo '<a href="/menuitem.php?page=' . $i . '">Page ' . $i . '</a><br>';
   }
}

oracle diff: how to compare two tables?

You can try using set operations: MINUS and INTERSECT

See here for more details:
O'Reilly - Mastering Oracle SQL - Chapter 7 - Set Operations

How to run python script with elevated privilege on windows

It worth mentioning that if you intend to package your application with PyInstaller and wise to avoid supporting that feature by yourself, you can pass the --uac-admin or --uac-uiaccess argument in order to request UAC elevation on start.

How to develop or migrate apps for iPhone 5 screen resolution?

Here you can find a nice tutorial (for MonoTouch, but you can use the information for Non-MonoTouch-projects, too):
http://redth.info/get-your-monotouch-apps-ready-for-iphone-5-ios-6-today/

  1. Create a new image for your splash/default screen (640 x 1136 pixel) with the name "[email protected]"

  2. In the iOS Simulator, go to the Hardware -> Device menu, and select "iPhone (Retina 4-inch)"

  3. Create other images, e.g. background images

  4. Detect iPhone 5 to load your new images:

public static bool IsTall
{
    get {
        return UIDevice.currentDevice.userInterfaceIdiom
                    == UIUserInterfaceIdiomPhone
                && UIScreen.mainScreen.bounds.size.height
                    * UIScreen.mainScreen.scale >= 1136;
    }
}

private static string tallMagic = "-568h@2x";
public static UIImage FromBundle16x9(string path)
{
    //adopt the -568h@2x naming convention
    if(IsTall())
    {
        var imagePath = Path.GetDirectoryName(path.ToString());
        var imageFile = Path.GetFileNameWithoutExtension(path.ToString());
        var imageExt = Path.GetExtension(path.ToString());
        imageFile = imageFile + tallMagic + imageExt;
        return UIImage.FromFile(Path.Combine(imagePath,imageFile));
    }
    else
    {
        return UIImage.FromBundle(path.ToString());
    }
}

Use of contains in Java ArrayList<String>

Your question is not very clear.

  • What's your code exactly doing? Give more code.
  • What's the error you're getting?

You say you get a null-pointer. You cannot get a null pointer as a value returned by contains().

However you can get a NullPointerException if your list has not been initialized. By reading your question now, I'd say that what you show here is correct, but maybe you just didn't instantiate the list.

For this to work (to add a feed URL if it isn't already in the list):

if (!this.rssFeedURLs.contains(rssFeedURL)) {
    this.rssFeedURLs.add(rssFeedUrl);
}

then this declaration would do:

private ArrayList<String> rssFeedURLs = new ArrayList<String>();

or initialize your list later on, but before trying to access its methods:

rssFeedUrls = new ArrayList<String>();

Finally... Do you really need a List? Maybe a Set would be better if you don't want duplicates. Use a LinkedHashSet if preserving the ordering matters.

Where to find Application Loader app in Mac?

For anyone finding this now (23/09/2019) Application Loader has been removed from Xcode.

If you have built the application in Xcode you should be able to follow these instructions to upload your and distribute your project Upload an app

I am not sure what to do if you have been given a .ipa file, for example when building an Expo project, I'll update this post when i have an answer.

In the mean time more info can be found here. Developer Apple - Whats new

Setting Windows PowerShell environment variables

You can also modify user/system environment variables permanently (i.e. will be persistent across shell restarts) with the following:

Modify a system environment variable

[Environment]::SetEnvironmentVariable
     ("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine)

Modify a user environment variable

[Environment]::SetEnvironmentVariable
     ("INCLUDE", $env:INCLUDE, [System.EnvironmentVariableTarget]::User)

Usage from comments - add to the system environment variable

[Environment]::SetEnvironmentVariable(
    "Path",
    [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::Machine) + ";C:\bin",
    [EnvironmentVariableTarget]::Machine)

String based solution is also possible if you don't want to write types

[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\bin", "Machine")

Cannot attach the file *.mdf as database

Strangely, for the exact same issue, what helped me was changing the ' to 'v11.0' in the following section of the config.

<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v11.0" />
      </parameters>

What is the difference between String.slice and String.substring?

Ben Nadel has written a good article about this, he points out the difference in the parameters to these functions:

String.slice( begin [, end ] )
String.substring( from [, to ] )
String.substr( start [, length ] )

He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn't.

Here is his article about this.

How to drop SQL default constraint without knowing its name?

To drop constraint for multiple columns:

declare @table_name nvarchar(256)

declare @Command nvarchar(max) = ''

set @table_name = N'ATableName'

select @Command = @Command + 'ALTER TABLE ' + @table_name + ' drop constraint ' + d.name + CHAR(10)+ CHAR(13)
from sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
     and c.column_id = d.parent_column_id
where t.name = @table_name and c.name in ('column1','column2','column3')

--print @Command

execute (@Command)

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

You can take advantage of the placeholder and use:

input:not(:placeholder-shown) {
  border: 1px solid red;
}

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I came across the same problem using a Wordpress page and plugin. This didn't work for the iframe plugin

[iframe src="https://itunes.apple.com/gb/app/witch-hunt/id896152730#?platform=iphone"]

but this does:

[iframe src="https://itunes.apple.com/gb/app/witch-hunt/id896152730"  width="100%" height="480" ]

As you see, I just left off the #?platform=iphone part in the end.

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

I've been using matlab for many years in my research. It's great for linear algebra and has a large set of well-written toolboxes. The most recent versions are starting to push it into being closer to a general-purpose language (better optimizers, a much better object model, richer scoping rules, etc.).

This past summer, I had a job where I used Python + numpy instead of Matlab. I enjoyed the change of pace. It's a "real" language (and all that entails), and it has some great numeric features like broadcasting arrays. I also really like the ipython environment.

Here are some things that I prefer about Matlab:

  • consistency: MathWorks has spent a lot of effort making the toolboxes look and work like each other. They haven't done a perfect job, but it's one of the best I've seen for a codebase that's decades old.
  • documentation: I find it very frustrating to figure out some things in numpy and/or python because the documentation quality is spotty: some things are documented very well, some not at all. It's often most frustrating when I see things that appear to mimic Matlab, but don't quite work the same. Being able to grab the source is invaluable (to be fair, most of the Matlab toolboxes ship with source too)
  • compactness: for what I do, Matlab's syntax is often more compact (but not always)
  • momentum: I have too much Matlab code to change now

If I didn't have such a large existing codebase, I'd seriously consider switching to Python + numpy.

Remove an element from a Bash array

To expand on the above answers, the following can be used to remove multiple elements from an array, without partial matching:

ARRAY=(one two onetwo three four threefour "one six")
TO_REMOVE=(one four)

TEMP_ARRAY=()
for pkg in "${ARRAY[@]}"; do
    for remove in "${TO_REMOVE[@]}"; do
        KEEP=true
        if [[ ${pkg} == ${remove} ]]; then
            KEEP=false
            break
        fi
    done
    if ${KEEP}; then
        TEMP_ARRAY+=(${pkg})
    fi
done
ARRAY=("${TEMP_ARRAY[@]}")
unset TEMP_ARRAY

This will result in an array containing: (two onetwo three threefour "one six")

downcast and upcast

  • Upcasting is an operation that creates a base class reference from a subclass reference. (subclass -> superclass) (i.e. Manager -> Employee)
  • Downcasting is an operation that creates a subclass reference from a base class reference. (superclass -> subclass) (i.e. Employee -> Manager)

In your case

Employee emp = (Employee)mgr; //mgr is Manager

you are doing an upcasting.

An upcast always succeeds unlike a downcast that requires an explicit cast because it can potentially fail at runtime.(InvalidCastException).

C# offers two operators to avoid this exception to be thrown:

Starting from:

Employee e = new Employee();

First:

Manager m = e as Manager; // if downcast fails m is null; no exception thrown

Second:

if (e is Manager){...} // the predicate is false if the downcast is not possible 

Warning: When you do an upcast you can only access to the superclass' methods, properties etc...

Double % formatting question for printf in Java

%d is for integers use %f instead, it works for both float and double types:

double d = 1.2;
float f = 1.2f;
System.out.printf("%f %f",d,f); // prints 1.200000 1.200000

How to read all of Inputstream in Server Socket JAVA

int c;
    String raw = "";
    do {
        c = inputstream.read();
        raw+=(char)c;
    } while(inputstream.available()>0);

InputStream.available() shows the available bytes only after one byte is read, hence do .. while

How to redirect and append both stdout and stderr to a file with Bash?

This should work fine:

your_command 2>&1 | tee -a file.txt

It will store all logs in file.txt as well as dump them on terminal.

How to get access to HTTP header information in Spring MVC REST controller?

When you annotate a parameter with @RequestHeader, the parameter retrieves the header information. So you can just do something like this:

@RequestHeader("Accept")

to get the Accept header.

So from the documentation:

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                              @RequestHeader("Keep-Alive") long keepAlive)  {

}

The Accept-Encoding and Keep-Alive header values are provided in the encoding and keepAlive parameters respectively.

And no worries. We are all noobs with something.

Laravel: Using try...catch with DB::transaction()

I've decided to give an answer to this question because I think it can be solved using a simpler syntax than the convoluted try-catch block. The Laravel documentation is pretty brief on this subject.

Instead of using try-catch, you can just use the DB::transaction(){...} wrapper like this:

// MyController.php
public function store(Request $request) {
    return DB::transaction(function() use ($request) {
        $user = User::create([
            'username' => $request->post('username')
        ]);

        // Add some sort of "log" record for the sake of transaction:
        $log = Log::create([
            'message' => 'User Foobar created'
        ]);

        // Lets add some custom validation that will prohibit the transaction:
        if($user->id > 1) {
            throw AnyException('Please rollback this transaction');
        }

        return response()->json(['message' => 'User saved!']);
    });
};

You should then see that the User and the Log record cannot exist without eachother.

Some notes on the implementation above:

  • Make sure to return the transaction, so that you can use the response() you return within its callback.
  • Make sure to throw an exception if you want the transaction to be rollbacked (or have a nested function that throws the exception for you automatically, like an SQL exception from within Eloquent).
  • The id, updated_at, created_at and any other fields are AVAILABLE AFTER CREATION for the $user object (for the duration of this transaction). The transaction will run through any of the creation logic you have. HOWEVER, the whole record is discarded when the AnyException is thrown. This means that for instance an auto-increment column for id does get incremented on failed transactions.

Tested on Laravel 5.8

How to get first N elements of a list in C#?

In case anyone is interested (even if the question does not ask for this version), in C# 2 would be: (I have edited the answer, following some suggestions)

myList.Sort(CLASS_FOR_COMPARER);
List<string> fiveElements = myList.GetRange(0, 5);

Loop in react-native

render() {
var myloop = [];

for (let i = 0; i < 10; i++) {
  myloop.push(
    <View key={i}>
    <Text>{i}</Text>
    </View>
  );
}

 return (

        <View >
          <Text >Welcome to React Native!</Text>
           {myloop}
        </View>


    );
  }
}

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

I realize this is a rather late post but still a possible solution for the OP. I use IE9 on Win 7 and have been having Adobe Reader's grey screen issues for several months when trying to open pdf bank and credit card statements online. I could open everything in Firefox or Opera but not IE. I finally tried PDF-Viewer, set it as the default pdf viewer in its preferences and no more problems. I'm sure there are other free viewers out there, like Foxit, PDF-Xchange, etc., that will give better results than Reader with less headaches. Adobe is like some of the other big companies that develop software on a take it or leave it basis ... so I left it.

What is a method group in C#?

The ToString function has many overloads - the method group would be the group consisting of all the different overloads for that function.

Where are $_SESSION variables stored?

On Debian (isn't this the case for most Linux distros?), it's saved in /var/lib/php5/. As mentioned above, it's configured in your php.ini.

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

If you are using PHPMyAdmin You can be solved this issue by doing this:

CAUTION: Don't use this solution if you want to maintain existing records in your table.

Step 1: Select database export method to custom:

enter image description here

Step 2: Please make sure to check truncate table before insert in data creation options:

enter image description here

Now you are able to import this database successfully.

Writing sqlplus output to a file

You may use the SPOOL command to write the information to a file.

Before executing any command type the following:

SPOOL <output file path>

All commands output following will be written to the output file.

To stop command output writing type

SPOOL OFF

How do you create a static class in C++?

If you're looking for a way of applying the "static" keyword to a class, like you can in C# for example, then you won't be able to without using Managed C++.

But the looks of your sample, you just need to create a public static method on your BitParser object. Like so:

BitParser.h

class BitParser
{
 public:
  static bool getBitAt(int buffer, int bitIndex);

  // ...lots of great stuff

 private:
  // Disallow creating an instance of this object
  BitParser() {}
};

BitParser.cpp

bool BitParser::getBitAt(int buffer, int bitIndex)
{
  bool isBitSet = false;
  // .. determine if bit is set
  return isBitSet;
}

You can use this code to call the method in the same way as your example code.

Hope that helps! Cheers.

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Hey here is the solution for windows 7+.

You need admin rights to make changes to the hosts file

Right click on your favorit text-editor and select "run as administrator" before opening the file

Open the following file "c:/windows/system32/driver/etc/hosts"

Enter the line:

127.0.0.1 localhost 

Next: Define a virtual host in /xampfolder/apache/conf/extra/httpd-vhosts.conf

<VirtualHost  127.0.0.1>
  DocumentRoot "c:\your\document\root"
  ServerName localhost
    <Directory "c:\your\document\root">
      Options Indexes FollowSymLinks Includes ExecCGI
      Options All 
      AllowOverride All
      Require all granted
    </Directory>
</VirtualHost>

Restart your apache! Now you can enter http://localhost in your browser and access your page.

Pro-Tip: You can use other names as localhost or have multiple localhosts this way. Just enter the names in the hosts file and define your virtual hosts.

How can I switch my git repository to a particular commit

Just checkout the commit you wants your new branch start from and create a new branch

git checkout -b newbranch 6e559cb95

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

I should add: You should not be putting your dll's into \system32\ anyway! Modify your code, modify your installer... find a home for your bits that is NOT anywhere under c:\windows\

For example, your installer puts your dlls into:

\program files\<your app dir>\

or

\program files\common files\<your app name>\

(Note: The way you actually do this is to use the environment var: %ProgramFiles% or %ProgramFiles(x86)% to find where Program Files is.... you do not assume it is c:\program files\ ....)

and then sets a registry tag :

HKLM\software\<your app name>
-- dllLocation

The code that uses your dlls reads the registry, then dynamically links to the dlls in that location.

The above is the smart way to go.

You do not ever install your dlls, or third party dlls into \system32\ or \syswow64. If you have to statically load, you put your dlls in your exe dir (where they will be found). If you cannot predict the exe dir (e.g. some other exe is going to call your dll), you may have to put your dll dir into the search path (avoid this if at all poss!)

system32 and syswow64 are for Windows provided files... not for anyone elses files. The only reason folks got into the bad habit of putting stuff there is because it is always in the search path, and many apps/modules use static linking. (So, if you really get down to it, the real sin is static linking -- this is a sin in native code and managed code -- always always always dynamically link!)

Please initialize the log4j system properly warning

This work for me:

public static void main(String[] args) {

        Properties props = new Properties();
        props.load(new FileInputStream("src/log4j.properties"));
        PropertyConfigurator.configure(props);

Recursive file search using PowerShell

Here is the method that I finally came up with after struggling:

Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*

To make the output cleaner (only path), use:

(Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*).fullname

To get only the first result, use:

(Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*).fullname | Select -First 1

Now for the important stuff:

To search only for files/directories do not use -File or -Directory (see below why). Instead use this for files:

Get-ChildItem -Recurse -Path ./path*/ -Include name* | where {$_.PSIsContainer -eq $false}

and remove the -eq $false for directories. Do not leave a trailing wildcard like bin/*.

Why not use the built in switches? They are terrible and remove features randomly. For example, in order to use -Include with a file, you must end the path with a wildcard. However, this disables the -Recurse switch without telling you:

Get-ChildItem -File -Recurse -Path ./bin/* -Include *.lib

You'd think that would give you all *.libs in all subdirectories, but it only will search top level of bin.

In order to search for directories, you can use -Directory, but then you must remove the trailing wildcard. For whatever reason, this will not deactivate -Recurse. It is for these reasons that I recommend not using the builtin flags.

You can shorten this command considerably:

Get-ChildItem -Recurse -Path ./path*/ -Include name* | where {$_.PSIsContainer -eq $false}

becomes

gci './path*/' -s -Include 'name*' | where {$_.PSIsContainer -eq $false}
  • Get-ChildItem is aliased to gci
  • -Path is default to position 0, so you can just make first argument path
  • -Recurse is aliased to -s
  • -Include does not have a shorthand
  • Use single quotes for spaces in names/paths, so that you can surround the whole command with double quotes and use it in Command Prompt. Doing it the other way around (surround with single quotes) causes errors

React-Router External link

I had luck with this:

  <Route
    path="/example"
    component={() => {
    global.window && (global.window.location.href = 'https://example.com');
    return null;
    }}
/>

Configuration with name 'default' not found. Android Studio

I am facing same problem, I was fixed it by generating gradle project and then adding lib project to android studio

First, See build.gradle file is present in project root directory

if not then, Create gradle project,

  1. export your required lib project from eclipse then (File->Export->Android->generate Gradle build file
  2. Click on Next->Next->Select your lib project from project listing->Next->Next->Finish
  3. See build.gradle file present in your project root directory
  4. Move this project to Android Studio

Parsing JSON array into java.util.List with Gson

Below code is using com.google.gson.JsonArray. I have printed the number of element in list as well as the elements in List

import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class Test {

    static String str = "{ "+ 
            "\"client\":\"127.0.0.1\"," + 
            "\"servers\":[" + 
            "    \"8.8.8.8\"," + 
            "    \"8.8.4.4\"," + 
            "    \"156.154.70.1\"," + 
            "    \"156.154.71.1\" " + 
            "    ]" + 
            "}";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {

            JsonParser jsonParser = new JsonParser();
            JsonObject jo = (JsonObject)jsonParser.parse(str);
            JsonArray jsonArr = jo.getAsJsonArray("servers");
            //jsonArr.
            Gson googleJson = new Gson();
            ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
            System.out.println("List size is : "+jsonObjList.size());
                    System.out.println("List Elements are  : "+jsonObjList.toString());


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

OUTPUT

List size is : 4

List Elements are  : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]

Excel VBA Open workbook, perform actions, save as, close

After discussion posting updated answer:

Option Explicit
Sub test()

    Dim wk As String, yr As String
    Dim fname As String, fpath As String
    Dim owb As Workbook

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    wk = ComboBox1.Value
    yr = ComboBox2.Value
    fname = yr & "W" & wk
    fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"

    On Error GoTo ErrorHandler
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)

    'Do Some Stuff

    With owb
        .SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
        .Close
    End With

    With Application
        .DisplayAlerts = True
        .ScreenUpdating = True
        .EnableEvents = True
    End With

Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

Else: Call Clear

End Sub

Error Handling:

You could try something like this to catch a specific error:

    On Error Resume Next
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)
    If Err.Number = 1004 Then
    GoTo FileNotFound
    Else
    End If

    ...
    Exit Sub
    FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

    Else: Call Clear

Get viewport/window height in ReactJS

I just spent some serious time figuring some things out with React and scrolling events / positions - so for those still looking, here's what I found:

The viewport height can be found by using window.innerHeight or by using document.documentElement.clientHeight. (Current viewport height)

The height of the entire document (body) can be found using window.document.body.offsetHeight.

If you're attempting to find the height of the document and know when you've hit the bottom - here's what I came up with:

if (window.pageYOffset >= this.myRefII.current.clientHeight && Math.round((document.documentElement.scrollTop + window.innerHeight)) < document.documentElement.scrollHeight - 72) {
        this.setState({
            trueOrNot: true
        });
      } else {
        this.setState({
            trueOrNot: false
        });
      }
    }

(My navbar was 72px in fixed position, thus the -72 to get a better scroll-event trigger)

Lastly, here are a number of scroll commands to console.log(), which helped me figure out my math actively.

console.log('window inner height: ', window.innerHeight);

console.log('document Element client hieght: ', document.documentElement.clientHeight);

console.log('document Element scroll hieght: ', document.documentElement.scrollHeight);

console.log('document Element offset height: ', document.documentElement.offsetHeight);

console.log('document element scrolltop: ', document.documentElement.scrollTop);

console.log('window page Y Offset: ', window.pageYOffset);

console.log('window document body offsetheight: ', window.document.body.offsetHeight);

Whew! Hope it helps someone!

This Row already belongs to another table error when trying to add rows?

Try this:

DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = dt.Clone();

DataRow[] orderRows = dt.Select("CustomerID = 2");

foreach (DataRow dr in orderRows)
{
    dtSpecificOrders.ImportRow(dr);
}

How to read a file without newlines?

temp = open(filename,'r').read().split('\n')

Looping through JSON with node.js

If we are using nodeJS, we should definitely take advantage of different libraries it provides. Inbuilt functions like each(), map(), reduce() and many more from underscoreJS reduces our efforts. Here's a sample

    var _=require("underscore");
    var fs=require("fs");

    var jsonObject=JSON.parse(fs.readFileSync('YourJson.json', 'utf8'));


    _.map( jsonObject, function(content) {
        _.map(content,function(data){
           if(data.Timestamp)
              console.log(data.Timestamp)          
           })
      })

How does the getView() method work when creating your own custom adapter?

What is exactly the function of the LayoutInflater?

When you design using XML, all your UI elements are just tags and parameters. Before you can use these UI elements, (eg a TextView or LinearLayout), you need to create the actual objects corresponding to these xml elements. That is what the inflater is for. The inflater, uses these tags and their corresponding parameters to create the actual objects and set all the parameters. After this you can get a reference to the UI element using findViewById().

Why do all the articles that I've read check if convertview is null or not first? What does it mean when it is null and what does it mean when it isn't?

This is an interesting one. You see, getView() is called everytime an item in the list is drawn. Now, before the item can be drawn, it has to be created. Now convertView basically is the last used view to draw an item. In getView() you inflate the xml first and then use findByViewID() to get the various UI elements of the listitem. When we check for (convertView == null) what we do is check that if a view is null(for the first item) then create it, else, if it already exists, reuse it, no need to go through the inflate process again. Makes it a lot more efficient.

You must also have come across a concept of ViewHolder in getView(). This makes the list more efficient. What we do is create a viewholder and store the reference to all the UI elements that we got after inflating. This way, we can avoid calling the numerous findByViewId() and save on a lot of time. This ViewHolder is created in the (convertView == null) condition and is stored in the convertView using setTag(). In the else loop we just obtain it back using getView() and reuse it.

What is the parent parameter that this method accepts?

The parent is a ViewGroup to which your view created by getView() is finally attached. Now in your case this would be the ListView.

Hope this helps :)

Python: Total sum of a list of numbers with the for loop

l = [1,2,3,4,5]
sum = 0
for x in l:
    sum = sum + x

And you can change l for any list you want.

Delimiter must not be alphanumeric or backslash and preg_match

You need a delimiter for your pattern. It should be added at the start and end of the pattern like so:

$pattern = "/My name is '(.*)' and im fine/";  // With / as a delimeter 

How to get domain root url in Laravel 4?

use directly where you want controller or web.php

Request::getHost();

Code not running in IE 11, works fine in Chrome

String.prototype.startsWith is a standard method in the most recent version of JavaScript, ES6.

Looking at the compatibility table below, we can see that it is supported on all current major platforms, except versions of Internet Explorer.

+-------------------------------------------------------------------------------+
¦    Feature    ¦ Chrome ¦ Firefox ¦ Edge  ¦ Internet Explorer ¦ Opera ¦ Safari ¦
¦---------------+--------+---------+-------+-------------------+-------+--------¦
¦ Basic Support ¦    41+ ¦     17+ ¦ (Yes) ¦ No Support        ¦    28 ¦      9 ¦
+-------------------------------------------------------------------------------+

You'll need to implement .startsWith yourself. Here is the polyfill:

if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(searchString, position) {
    position = position || 0;
    return this.indexOf(searchString, position) === position;
  };
}

How do you clear the focus in javascript?

dummyElem.focus() where dummyElem is a hidden object (e.g. has negative zIndex)?

Where does linux store my syslog?

In addition to the accepted answer, it is useful to know the following ...

Each of those functions should have manual pages associated with them.

If you run man -k syslog (a keyword search of man pages) you will get a list of man pages that refer to, or are about syslog

$ man -k syslog
logger (1)           - a shell command interface to the syslog(3) system l...
rsyslog.conf (5)     - rsyslogd(8) configuration file
rsyslogd (8)         - reliable and extended syslogd
syslog (2)           - read and/or clear kernel message ring buffer; set c...
syslog (3)           - send messages to the system logger
vsyslog (3)          - send messages to the system logger

You need to understand the manual sections in order to delve further.

Here's an excerpt from the man page for man, that explains man page sections :

The table below shows the section numbers of the manual followed  by
the types of pages they contain.

   1   Executable programs or shell commands
   2   System calls (functions provided by the kernel)
   3   Library calls (functions within program libraries)
   4   Special files (usually found in /dev)
   5   File formats and conventions eg /etc/passwd
   6   Games
   7   Miscellaneous  (including  macro  packages and conven-
       tions), e.g. man(7), groff(7)
   8   System administration commands (usually only for root)
   9   Kernel routines [Non standard]

To read the above run

$man man 

So, if you run man 3 syslog you get a full manual page for the syslog function that you called in your code.

SYSLOG(3)                Linux Programmer's Manual                SYSLOG(3)

NAME
   closelog,  openlog,  syslog,  vsyslog  - send messages to the system
   logger

SYNOPSIS
   #include <syslog.h>

   void openlog(const char *ident, int option, int facility);
   void syslog(int priority, const char *format, ...);
   void closelog(void);

   #include <stdarg.h>

   void vsyslog(int priority, const char *format, va_list ap);

Not a direct answer but hopefully you will find this useful.

error: package javax.servlet does not exist

In my case, migrating a Spring 3.1 app up to 3.2.7, my solution was similar to Matthias's but a bit different -- thus why I'm documenting it here:

In my POM I found this dependency and changed it from 6.0 to 7.0:

    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>

Then later in the POM I upgraded this plugin from 6.0 to 7.0:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    ...
                    <configuration>
                        ...
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax</groupId>
                                <artifactId>javaee-endorsed-api</artifactId>
                                <version>7.0</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Disable future dates in jQuery UI Datepicker

http://stefangabos.ro/jquery/zebra-datepicker

use zebra date pickers:

$('#select_month1').Zebra_DatePicker({
  direction: false,
  format: 'Y-m-d',
  pair: $('#select_month2')
});

$('#select_month2').Zebra_DatePicker({
  direction: 1, format: 'Y-m-d',
});

Versioning SQL Server database

Here at Red Gate we offer a tool, SQL Source Control, which uses SQL Compare technology to link your database with a TFS or SVN repository. This tool integrates into SSMS and lets you work as you would normally, except it now lets you commit the objects.

For a migrations-based approach (more suited for automated deployments), we offer SQL Change Automation (formerly called ReadyRoll), which creates and manages a set of incremental scripts as a Visual Studio project.

In SQL Source Control it is possible to specify static data tables. These are stored in source control as INSERT statements.

If you're talking about test data, we'd recommend that you either generate test data with a tool or via a post-deployment script you define, or you simply restore a production backup to the dev environment.

Why do I get a SyntaxError for a Unicode escape in my file path?

f = open('C:\\Users\\Pooja\\Desktop\\trolldata.csv')

Use '\\' for python program in Python version 3 and above.. Error will be resolved..

How to parse JSON without JSON.NET library?

Have you tried using JavaScriptSerializer ? There's also DataContractJsonSerializer

Call Activity method from adapter

In Kotlin there is now a cleaner way by using lambda functions, no need for interfaces:

class MyAdapter(val adapterOnClick: (Any) -> Unit) {
    fun setItem(item: Any) {
        myButton.setOnClickListener { adapterOnClick(item) }
    }
}

class MyActivity {
    override fun onCreate(savedInstanceState: Bundle?) {
        var myAdapter = MyAdapter { item -> doOnClick(item) }
    }


    fun doOnClick(item: Any) {

    }
}

ls command: how can I get a recursive full-path listing, one line per file?

Using no external commands other than ls:

ls -R1 /path | 
  while read l; do case $l in *:) d=${l%:};; "") d=;; *) echo "$d/$l";; esac; done

CSS full screen div with text in the middle

text-align: center will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0; (you will probably also have to give the span a display: block property)

batch script - read line by line

For those with spaces in the path, you are going to want something like this: n.b. It expands out to an absolute path, rather than relative, so if your running directory path has spaces in, these count too.

set SOURCE=path\with spaces\to\my.log
FOR /F "usebackq delims=" %%A IN ("%SOURCE%") DO (
    ECHO %%A
)

To explain:

(path\with spaces\to\my.log)

Will not parse, because spaces. If it becomes:

("path\with spaces\to\my.log")

It will be handled as a string rather than a file path.

"usebackq delims=" 

See docs will allow the path to be used as a path (thanks to Stephan).

Python error: "IndexError: string index out of range"

This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like

so_far = " " * len(word)

?

Edit:

try something like

print "%d / %d" % (new, so_far)

before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you're not actually using the instance you think.

How can I get the current date and time in UTC or GMT in Java?

Here is another way to get GMT time in String format

String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z" ;
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateTimeString =  sdf.format(new Date());

Define an <img>'s src attribute in CSS

After trying these solutions I still wasn't satisfied but I found a solution in this article and it works in Chrome, Firefox, Opera, Safari, IE8+

#divId {

  display: block;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  background: url(http://notrealdomain2.com/newbanner.png) no-repeat;
  width: 180px; /* Width of new image */
  height: 236px; /* Height of new image */
  padding-left: 180px; /* Equal to width of new image */

}

Rails get index of "each" loop

<% @images.each_with_index do |page, index| %>

<% end %>

How to display Woocommerce product price by ID number on a custom page?

In woocommerce,

Get regular price :

$price = get_post_meta( get_the_ID(), '_regular_price', true);
// $price will return regular price

Get sale price:

$sale = get_post_meta( get_the_ID(), '_sale_price', true);
// $sale will return sale price

How to dismiss keyboard iOS programmatically when pressing return

To dismiss a keyboard after the keyboard has popped up, there are 2 cases,

  1. when the UITextField is inside a UIScrollView

  2. when the UITextField is outside a UIScrollView

2.when the UITextField is outside a UIScrollView override the method in your UIViewController subclass

you must also add delegate for all UITextView

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
  1. In a scroll view, Tapping outside will not fire any event, so in that case use a Tap Gesture Recognizer, Drag and drop a UITapGesture for the scroll view and create an IBAction for it.

to create a IBAction, press ctrl+ click the UITapGesture and drag it to the .h file of viewcontroller.

Here I have named tappedEvent as my action name

- (IBAction)tappedEvent:(id)sender {
      [self.view endEditing:YES];  }

the abouve given Information was derived from the following link, please refer for more information or contact me if you dont understand the abouve data.

http://samwize.com/2014/03/27/dismiss-keyboard-when-tap-outside-a-uitextfield-slash-uitextview/

Disabling the button after once click

If when you set disabled="disabled" immediately after the user clicks the button, and the form doesn't submit because of that, you could try two things:

//First choice [given myForm = your form]:
myInputButton.disabled = "disabled";
myForm.submit()

//Second choice:
setTimeout(disableFunction, 1);  
//so the form will submit and then almost instantly, the button will be disabled  

Although I honestly bet there will be a better way to do this, than that.

How to use zIndex in react-native

Use elevation instead of zIndex for android devices

elevatedElement: {
  zIndex: 3, // works on ios
  elevation: 3, // works on android
}

This worked fine for me!

Assigning the return value of new by reference is deprecated

Perhaps the constructor of MDB2 has some code that uses a $variable =& new ClassName();

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

I know this is an old question, but still unanswered. It took me a day of research, but I found the simplest solution, at least in my case (Oracle 11.2 on Windows 2008 R2) and wanted to share.

The error, if looked at directly, indicates that the listener does not recognize the service name. But where does it keep service names? In %ORACLE_HOME%\NETWORK\ADMIN\listener.ora

The "SID_LIST" is just that, a list of SIDs and service names paired up in a format you can copy or lookup.

I added the problem Service Name, then in Windows "Services" control panel, I did a "Restart" on the Oracle listener service. Now all is well.


For example, your listener.ora file might initially look like:

# listener.ora Network Configuration File: C:\app\oracle_user\product\12.1.0\dbhome_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:C:\app\oracle_user\product\12.1.0\dbhome_1\bin\oraclr12.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

... And to make it recognize a service name of orcl, you might change it to:

# listener.ora Network Configuration File: C:\app\oracle_user\product\12.1.0\dbhome_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:C:\app\oracle_user\product\12.1.0\dbhome_1\bin\oraclr12.dll")
    )
    (SID_DESC = 
        (GLOBAL_DBNAME = orcl)
        (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
        (SID_NAME = orcl)
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

Create numpy matrix filled with NaNs

You rarely need loops for vector operations in numpy. You can create an uninitialized array and assign to all entries at once:

>>> a = numpy.empty((3,3,))
>>> a[:] = numpy.nan
>>> a
array([[ NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN],
       [ NaN,  NaN,  NaN]])

I have timed the alternatives a[:] = numpy.nan here and a.fill(numpy.nan) as posted by Blaenk:

$ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a.fill(np.nan)"
10000 loops, best of 3: 54.3 usec per loop
$ python -mtimeit "import numpy as np; a = np.empty((100,100));" "a[:] = np.nan" 
10000 loops, best of 3: 88.8 usec per loop

The timings show a preference for ndarray.fill(..) as the faster alternative. OTOH, I like numpy's convenience implementation where you can assign values to whole slices at the time, the code's intention is very clear.

Note that ndarray.fill performs its operation in-place, so numpy.empty((3,3,)).fill(numpy.nan) will instead return None.

Get input type="file" value when it has multiple files selected

You use input.files property. It's a collection of File objects and each file has a name property:

onmouseout="for (var i = 0; i < this.files.length; i++) alert(this.files[i].name);"

What is the most efficient way to loop through dataframes with pandas?

I believe the most simple and efficient way to loop through DataFrames is using numpy and numba. In that case, looping can be approximately as fast as vectorized operations in many cases. If numba is not an option, plain numpy is likely to be the next best option. As has been noted many times, your default should be vectorization, but this answer merely considers efficient looping, given the decision to loop, for whatever reason.

For a test case, let's use the example from @DSM's answer of calculating a percentage change. This is a very simple situation and as a practical matter you would not write a loop to calculate it, but as such it provides a reasonable baseline for timing vectorized approaches vs loops.

Let's set up the 4 approaches with a small DataFrame, and we'll time them on a larger dataset below.

import pandas as pd
import numpy as np
import numba as nb

df = pd.DataFrame( { 'close':[100,105,95,105] } )

pandas_vectorized = df.close.pct_change()[1:]

x = df.close.to_numpy()
numpy_vectorized = ( x[1:] - x[:-1] ) / x[:-1]
        
def test_numpy(x):
    pct_chng = np.zeros(len(x))
    for i in range(1,len(x)):
        pct_chng[i] = ( x[i] - x[i-1] ) / x[i-1]
    return pct_chng

numpy_loop = test_numpy(df.close.to_numpy())[1:]

@nb.jit(nopython=True)
def test_numba(x):
    pct_chng = np.zeros(len(x))
    for i in range(1,len(x)):
        pct_chng[i] = ( x[i] - x[i-1] ) / x[i-1]
    return pct_chng
    
numba_loop = test_numba(df.close.to_numpy())[1:]

And here are the timings on a DataFrame with 100,000 rows (timings performed with Jupyter's %timeit function, collapsed to a summary table for readability):

pandas/vectorized   1,130 micro-seconds
numpy/vectorized      382 micro-seconds
numpy/looped       72,800 micro-seconds
numba/looped          455 micro-seconds

Summary: for simple cases, like this one, you would go with (vectorized) pandas for simplicity and readability, and (vectorized) numpy for speed. If you really need to use a loop, do it in numpy. If numba is available, combine it with numpy for additional speed. In this case, numpy + numba is almost as fast as vectorized numpy code.

Other details:

  • Not shown are various options like iterrows, itertuples, etc. which are orders of magnitude slower and really should never be used.
  • The timings here are fairly typical: numpy is faster than pandas and vectorized is faster than loops, but adding numba to numpy will often speed numpy up dramatically.
  • Everything except the pandas option requires converting the DataFrame column to a numpy array. That conversion is included in the timings.
  • The time to define/compile the numpy/numba functions was not included in the timings, but would generally be a negligible component of the timing for any large dataframe.

How to Install Windows Phone 8 SDK on Windows 7

You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

Charts for Android

To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:

Open Source:

Paid:

** - means I didn't try those so I can't really recommend it but other users suggested it..

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

MacPorts is another package manager for OS X:.

Installation instructions are at The MacPorts Project -- Download & Installation after which one issues sudo port install pythonXX, where XX is 27 or 35.

What are static factory methods?

If the constructor of a class is private then you cannot create an object for class from outside of it.

class Test{
 int x, y;
 private Test(){
  .......
  .......
  }
}

We cannot create an object for above class from outside of it. So you cannot access x, y from outside of the class. Then what is the use of this class?
Here is the Answer : FACTORY method.
Add the below method in above class

public static Test getObject(){
  return new Test();
}

So now you can create an object for this class from outside of it. Like the way...

Test t = Test.getObject();

Hence, a static method which returns the object of the class by executing its private constructor is called as FACTORY method
.

Display only date and no time

You can apply custom date time format using ToString like:

DateTime.Now.Date.ToString("MM/dd/yyyy");

Further reading on DateTime.ToString formats pattern can be found here and here.

Edit: After your question edit, Just like what other suggested you should apply the date format at your view:

model.Returndate = DateTime.Now.Date;

@Html.EditorFor(model => model.Returndate.Date.ToString("MM/dd/yyyy"))

Inversion of Control vs Dependency Injection

As for this question, I'd say the wiki has already provided detailed and easy-understanding explanations. I will just quote the most significant here.

Implementation of IoC

In object-oriented programming, there are several basic techniques to implement inversion of control. These are:

  1. Using a service locator pattern Using dependency injection, for example Constructor injection Parameter injection Setter injection Interface injection;
  2. Using a contextualized lookup;
  3. Using template method design pattern;
  4. Using strategy design pattern

As for Dependency Injection

dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.

git - Your branch is ahead of 'origin/master' by 1 commit

If you just want to throw away the changes and revert to the last commit (the one you wanted to share):

git reset --hard HEAD~

You may want to check to make absolutely sure you want this (git log), because you'll loose all changes.

A safer alternative is to run

git reset --soft HEAD~ # reset to the last commit
git stash              # stash all the changes in the working tree 
git push               # push changes 
git stash pop          # get your changes back 

Can I have multiple primary keys in a single table?

(Have been studying these, a lot)

Candidate keys - A minimal column combination required to uniquely identify a table row.
Compound keys - 2 or more columns.

  • Multiple Candidate keys can exist in a table.
    • Primary KEY - Only one of the candidate keys that is chosen by us
    • Alternate keys - All other candidate keys
      • Both Primary Key & Alternate keys can be Compound keys

Sources:
https://en.wikipedia.org/wiki/Superkey
https://en.wikipedia.org/wiki/Candidate_key
https://en.wikipedia.org/wiki/Primary_key
https://en.wikipedia.org/wiki/Compound_key

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

YOu can also rewrite it like this

FROM Resource r WHERE r.ResourceNo IN
        ( 
            SELECT m.ResourceNo FROM JobMember m
            JOIN Job j ON j.JobNo = m.JobNo
            WHERE j.ProjectManagerNo = @UserResourceNo 
            OR
            j.AlternateProjectManagerNo = @UserResourceNo

            Union All

            SELECT m.ResourceNo FROM JobMember m
            JOIN JobTask t ON t.JobTaskNo = m.JobTaskNo
            WHERE t.TaskManagerNo = @UserResourceNo
            OR
            t.AlternateTaskManagerNo = @UserResourceNo

        )

Also a return table is expected in your RETURN statement

grep for multiple strings in file on different lines (ie. whole file, not line based search)?

I had this problem today, and all one-liners here failed to me because the files contained spaces in the names.

This is what I came up with that worked:

grep -ril <WORD1> | sed 's/.*/"&"/' | xargs grep -il <WORD2>

Get absolute path of initially run script

`realpath(dirname(__FILE__))` 

it gives you current script(the script inside which you placed this code) directory without trailing slash. this is important if you want to include other files with the result

How to properly create composite primary keys - MYSQL

CREATE  TABLE `mom`.`sec_subsection` (

  `idsec_sub` INT(11) NOT NULL ,

  `idSubSections` INT(11) NOT NULL ,

  PRIMARY KEY (`idsec_sub`, `idSubSections`) 

);

jQuery events .load(), .ready(), .unload()

Also, I noticed one more difference between .load and .ready. I am opening a child window and I am performing some work when child window opens. .load is called only first time when I open the window and if I don't close the window then .load will not be called again. however, .ready is called every time irrespective of close the child window or not.

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

In an AngularJS directive the scope allows you to access the data in the attributes of the element to which the directive is applied.

This is illustrated best with an example:

<div my-customer name="Customer XYZ"></div>

and the directive definition:

angular.module('myModule', [])
.directive('myCustomer', function() {
  return {
    restrict: 'E',
    scope: {
      customerName: '@name'
    },
    controllerAs: 'vm',
    bindToController: true,
    controller: ['$http', function($http) {
      var vm = this;

      vm.doStuff = function(pane) {
        console.log(vm.customerName);
      };
    }],
    link: function(scope, element, attrs) {
      console.log(scope.customerName);
    }
  };
});

When the scope property is used the directive is in the so called "isolated scope" mode, meaning it can not directly access the scope of the parent controller.

In very simple terms, the meaning of the binding symbols is:

someObject: '=' (two-way data binding)

someString: '@' (passed directly or through interpolation with double curly braces notation {{}})

someExpression: '&' (e.g. hideDialog())

This information is present in the AngularJS directive documentation page, although somewhat spread throughout the page.

The symbol > is not part of the syntax.

However, < does exist as part of the AngularJS component bindings and means one way binding.

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

INSERT INTO KeyedTable(KeyField, Otherfield)
SELECT n.* FROM 
    (SELECT 'PossibleDupeLiteral' AS KeyField, 'OtherfieldValue' AS Otherfield
     UNION ALL
     SELECT 'PossibleDupeLiteral', 'OtherfieldValue2'
    )
LEFT JOIN KeyedTable k
    ON k.KeyField=n.KeyField
WHERE k.KeyField IS NULL

This tells the Server to look for the same data (hopefully the same speedy way it does to check for duplicate keys) and insert nothing if it finds it.

I like the IGNORE_DUP_KEY solution too, but then anyone who relies on errors to catch problems will be mystified when the server silently ignores their dupe-key errors.

The reason I choose this over Philip Kelley's solution is that you can provide several rows of data and only have the missing ones actually get in:

How do I set an absolute include path in PHP?

Not directly answering your question but something to remember:

When using includes with allow_url_include on in your ini beware that, when accessing sessions from included files, if from a script you include one file using an absolute file reference and then include a second file from on your local server using a url file reference that they have different variable scope and the same session will not be seen from both included files. The original session won't be seen from the url included file.

from: http://us2.php.net/manual/en/function.include.php#84052

What is the difference between json.dump() and json.dumps() in python?

One notable difference in Python 2 is that if you're using ensure_ascii=False, dump will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):

dumps on the other hand, with ensure_ascii=False can produce a str or unicode just depending on what types you used for strings:

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.

(emphasis mine). Note that it may still be a str instance as well.

Thus you cannot use its return value to save the structure into file without checking which format was returned and possibly playing with unicode.encode.

This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.


As for load vs loads, load considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.

Multiple bluetooth connection

Please take a look at the Android documentation.

Using the Bluetooth APIs, an Android application can perform the following:

  • Scan for other Bluetooth devices
  • Query the local Bluetooth adapter for paired Bluetooth devices
  • Establish RFCOMM channels
  • Connect to other devices through service discovery
  • Transfer data to and from other devices
  • Manage multiple connections

How do I convert a string to enum in TypeScript?

Try this

var color : Color = (Color as any)["Green];

That works fine for 3.5.3 version

Float vs Decimal in ActiveRecord

I remember my CompSci professor saying never to use floats for currency.

The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2). Because of that, it is impossible to store fractions and decimals in Float exactly.

That's why there is a Decimal format. If you do this:

irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!

whereas if you just do

irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you

So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10 is exactly 0.1.

However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:

require "benchmark" 
require "bigdecimal" 

d = BigDecimal.new(3) 
f = Float(3)

time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } } 
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }

puts time_decimal 
#=> 6.770960 seconds 
puts time_float 
#=> 0.988070 seconds

Answer

Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.

Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.

Get Return Value from Stored procedure in asp.net

you can try this.Add the parameter as output direction and after executing the query get the output parameter value.

  SqlParameter parmOUT = new SqlParameter("@return", SqlDbType.Int);
  parmOUT.Direction = ParameterDirection.Output;
  cmd.Parameters.Add(parmOUT);
  cmd.ExecuteNonQuery();
  int returnVALUE = (int)cmd.Parameters["@return"].Value;

What is the difference between require and require-dev sections in composer.json?

require section This section contains the packages/dependencies which are better candidates to be installed/required in the production environment.

require-dev section: This section contains the packages/dependencies which can be used by the developer to test her code (or to experiment on her local machine and she doesn't want these packages to be installed on the production environment).

The located assembly's manifest definition does not match the assembly reference

I got this error while building on Team Foundation Server's build-service. It turned out I had multiple projects in my solution using different versions of the same library added with NuGet. I removed all old versions with NuGet and added the new one as reference for all.

Team Foundation Server puts all DLL files in one directory, and there can only be one DLL file of a certain name at a time of course.