Programs & Examples On #Dpkg

dpkg is a tool to install, build, remove and manage Debian packages.

Package php5 have no installation candidate (Ubuntu 16.04)

You must use prefix "php5.6-" instead of "php5-" as in ubuntu 14.04 and olders:

sudo apt-get install php5.6 php5.6-mcrypt

How to check the version before installing a package using apt-get?

apt-cache policy <package-name>

$ apt-cache policy redis-server
redis-server:
  Installed: (none)
  Candidate: 2:2.8.4-2
  Version table:
     2:2.8.4-2 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages

apt-get install -s <package-name>

$ apt-get install -s redis-server
NOTE: This is only a simulation!
      apt-get needs root privileges for real execution.
      Keep also in mind that locking is deactivated,
      so don't depend on the relevance to the real current situation!
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  libjemalloc1 redis-tools
The following NEW packages will be installed:
  libjemalloc1 redis-server redis-tools
0 upgraded, 3 newly installed, 0 to remove and 3 not upgraded.
Inst libjemalloc1 (3.5.1-2 Ubuntu:14.04/trusty [amd64])
Inst redis-tools (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
Inst redis-server (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
Conf libjemalloc1 (3.5.1-2 Ubuntu:14.04/trusty [amd64])
Conf redis-tools (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
Conf redis-server (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])

apt-cache show <package-name>

$ apt-cache show redis-server
Package: redis-server
Priority: optional
Section: universe/misc
Installed-Size: 744
Maintainer: Ubuntu Developers <[email protected]>
Original-Maintainer: Chris Lamb <[email protected]>
Architecture: amd64
Source: redis
Version: 2:2.8.4-2
Depends: libc6 (>= 2.14), libjemalloc1 (>= 2.1.1), redis-tools (= 2:2.8.4-2), adduser
Filename: pool/universe/r/redis/redis-server_2.8.4-2_amd64.deb
Size: 267446
MD5sum: 066f3ce93331b876b691df69d11b7e36
SHA1: f7ffbf228cc10aa6ff23ecc16f8c744928d7782e
SHA256: 2d273574f134dc0d8d10d41b5eab54114dfcf8b716bad4e6d04ad8452fe1627d
Description-en: Persistent key-value database with network interface
 Redis is a key-value database in a similar vein to memcache but the dataset
 is non-volatile. Redis additionally provides native support for atomically
 manipulating and querying data structures such as lists and sets.
 .
 The dataset is stored entirely in memory and periodically flushed to disk.
Description-md5: 9160ed1405585ab844f8750a9305d33f
Homepage: http://redis.io/
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Origin: Ubunt

dpkg -l <package-name>

$ dpkg -l nginx
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                                     Version                   Architecture              Description
+++-========================================-=========================-=========================-=====================================================================================
ii  nginx                                    1.6.2-1~trusty            amd64                     high performance web server

PostgreSQL database service

If you don't want or can't install postgres again, you can install the server from the binary zip like this post explains it.

How to use CURL via a proxy?

root@APPLICATIOSERVER:/var/www/html# php connectiontest.php
61e23468-949e-4103-8e08-9db09249e8s1 OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 10.172.123.1:80 root@APPLICATIOSERVER:/var/www/html#

Post declaring the proxy settings in the php script file issue has been fixed.

$proxy = '10.172.123.1:80';
curl_setopt($cSession, CURLOPT_PROXY, $proxy); // PROXY details with port

Error: EACCES: permission denied

FWIW I had the same symptoms, but with a different package. Creating package.json and running npm init did NOT solve my issue.

On this system, apparently new folders in this location were being created with root permissions. During npm install, new folders are created. This caused npm install to fail partway, even with sudo.

The solution was to run npm install app in a different location with no root umask.

Converting Select results into Insert script - SQL Server

SSMS Toolpack (which is FREE as in beer) has a variety of great features - including generating INSERT statements from tables.

Update: for SQL Server Management Studio 2012 (and newer), SSMS Toolpack is no longer free, but requires a modest licensing fee.

Display a jpg image on a JPanel

I'd probably use an ImageIcon and set it on a JLabel which I'd add to the JPanel.

Here's Sun's docs on the subject matter.

Apache POI error loading XSSFWorkbook class

Please note that 4.0 is not sufficient since ListValuedMap, was introduced in version 4.1.

You need to use this maven repository link for version 4.1. Replicated below for convenience

 <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
 <dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-collections4</artifactId>
   <version>4.1</version>
</dependency>

How to check if a string contains a substring in Bash

grep -q is useful for this purpose.

The same using awk:

string="unix-bash 2389"
character="@"
printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'

Output:

Not Found

string="unix-bash 2389"
character="-"
printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'

Output:

Found

Original source: http://unstableme.blogspot.com/2008/06/bash-search-letter-in-string-awk.html

Running java with JAVA_OPTS env variable has no effect

You can setup _JAVA_OPTIONS instead of JAVA_OPTS. This should work without $_JAVA_OPTIONS.

How to check if element in groovy array/hash/collection/list?

.contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue()

[a:1,b:2,c:3].containsValue(3)
[a:1,b:2,c:3].containsKey('a')

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

Visual Studio debugger error: Unable to start program Specified file cannot be found

I think that what you have to check is:

  1. if the target EXE is correctly configured in the project settings ("command", in the debugging tab). Since all individual projects run when you start debugging it's well possible that only the debugging target for the "ALL" solution is missing, check which project is currently active (you can also select the debugger target by changing the active project).

  2. dependencies (DLLs) are also located at the target debugee directory or can be loaded (you can use the "depends.exe" tool for checking dependencies of an executable or DLL).

Can you require two form fields to match with HTML5?

JavaScript will be required, but the amount of code can be kept to a minimum by using an intermediary <output> element and an oninput form handler to perform the comparison (patterns and validation could augment this solution, but aren't shown here for sake of simplicity):

<form oninput="result.value=!!p2.value&&(p1.value==p2.value)?'Match!':'Nope!'">
  <input type="password" name="p1" value="" required />
  <input type="password" name="p2" value="" required />
  <output name="result"></output>
</form>

How to move all HTML element children to another parent using JavaScript?

This answer only really works if you don't need to do anything other than transferring the inner code (innerHTML) from one to the other:

// Define old parent
var oldParent = document.getElementById('old-parent');

// Define new parent
var newParent = document.getElementById('new-parent');

// Basically takes the inner code of the old, and places it into the new one
newParent.innerHTML = oldParent.innerHTML;

// Delete / Clear the innerHTML / code of the old Parent
oldParent.innerHTML = '';

Hope this helps!

How to use ArgumentCaptor for stubbing?

Assuming the following method to test:

public boolean doSomething(SomeClass arg);

Mockito documentation says that you should not use captor in this way:

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));

Because you can just use matcher during stubbing:

when(someObject.doSomething(eq(expected))).thenReturn(true);

But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

How to convert string representation of list to a list?

You may run into such problem while dealing with scraped data stored as Pandas DataFrame.

This solution works like charm if the list of values is present as text.

def textToList(hashtags):
    return hashtags.strip('[]').replace('\'', '').replace(' ', '').split(',')

hashtags = "[ 'A','B','C' , ' D']"
hashtags = textToList(hashtags)

Output: ['A', 'B', 'C', 'D']

No external library required.

How print out the contents of a HashMap<String, String> in ascending order based on its values?

You aren't going to be able to do this from the HashMap class alone.

I would take the Map<String, String> codes, construct a reverse map of TreeMap<String, String> reversedMap where you map the values of the codes Map to the keys (this would require your original Map to have a one-to-one mapping from key-to-value). Since the TreeMap provides Iterators which returns entries in ascending key order, this will give you the value/key combination of the first map in the order (sorted by values) you desire.

Map<String, String> reversedMap = new TreeMap<String, String>(codes);

//then you just access the reversedMap however you like...
for (Map.Entry entry : reversedMap.entrySet()) {
    System.out.println(entry.getKey() + ", " + entry.getValue());
}

There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.

How to pass a value from Vue data to href?

Or you can do that with ES6 template literal:

<a :href="`/job/${r.id}`"

Force sidebar height 100% using CSS (with a sticky bottom image)?

Flexbox (http://caniuse.com/#feat=flexbox)

First wrap the columns you want in a div or section, ex:

<div class="content">
    <div class="main"></div>
    <div class="sidebar"></div>
</div>

Then add the following CSS:

.content {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}

Adding new line of data to TextBox

I find this method saves a lot of typing, and prevents a lot of typos.

string nl = "\r\n";

txtOutput.Text = "First line" + nl + "Second line" + nl + "Third line";

How to set a border for an HTML div tag

Try being explicit about all the border properties. For example:

border:1px solid black;

See Border shorthand property. Although the other bits are optional some browsers don't set the width or colour to a default you'd expect. In your case I'd bet that it's the width that's zero unless specified.

python: get directory two levels up

The best solution (for python >= 3.4) when executing from any directory is:

from pathlib import Path
two_up = Path(__file__).resolve().parents[1]

How to put sshpass command inside a bash script?

Do which sshpass in your command line to get the absolute path to sshpass and replace it in the bash script.

You should also probably do the same with the command you are trying to run.

The problem might be that it is not finding it.

Can I apply the required attribute to <select> fields in HTML5?

You need to set the value attribute of option to the empty string:

<select name="status" required>
    <option selected disabled value="">what's your status?</option>
    <option value="code">coding</option>
    <option value="sleep">sleeping</option>
</select>

select will return the value of the selected option to the server when the user presses submit on the form. An empty value is the same as an empty text input -> raising the required message.


w3schools

The value attribute specifies the value to be sent to a server when a form is submitted.

Example

Using CSS in Laravel views?

Since Laravel 5 the HTML class is not included by default anymore.

If you're using Form or HTML helpers, you will see an error stating class 'Form' not found or class 'Html' not found. The Form and HTML helpers have been deprecated in Laravel 5.0; however, there are community-driven replacements such as those maintained by the Laravel Collective.

You can make use of the following line to include your CSS or JS files:

<link href="{{ URL::asset('css/base.css') }}" rel="stylesheet">
<link href="{{ URL::asset('js/project.js') }}" rel="script">

What's the best way to limit text length of EditText in Android

EditText editText = new EditText(this);
int maxLength = 3;    
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});

How can I increment a date by one day in Java?

Use the DateFormat API to convert the String into a Date object, then use the Calendar API to add one day. Let me know if you want specific code examples, and I can update my answer.

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

The solution is to put the scripts in an outside js file (lets called 'yourDynamic.js') and re-register de file everytime you refresh the updatepanel.

I use this in the updatepanel_prerender event:

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "UpdatePanel1_PreRender", _
                   "<script type='text/javascript' id='UpdatePanel1_PreRender'>" & _
                   "include('yourDynamic.js');" & _
                   "removeDuplicatedScript('UpdatePanel1_PreRender');</script>" _
                   , False)

In the page or in some other include you will need this javascript:

// Include a javascript file inside another one.
function include(filename)
{
    var head = document.getElementsByTagName('head')[0];

    var scripts = document.getElementsByTagName('script');
    for(var x=0;x<scripts.length;>    {
        if (scripts[x].getAttribute('src'))
        {
            if(scripts[x].getAttribute('src').indexOf(filename) != -1)
            {
                head.removeChild(scripts[x]);
                break;
            }
        }
    }

    script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';
    head.appendChild(script)
}

// Removes duplicated scripts.
function removeDuplicatedScript(id)
{
    var count = 0;
    var head = document.getElementsByTagName('head')[0];

    var scripts = document.getElementsByTagName('script');
    var firstScript;
    for(var x=0;x<scripts.length;>    {
        if (scripts[x].getAttribute('id'))
        {
            if(scripts[x].getAttribute('id').indexOf(id) != -1)
            {
                if (count == 0)
                {
                    firstScript = scripts[x];
                    count++;
                }
                else
                {
                    head.removeChild(firstScript);
                    firstScript = scripts[x];
                    count = 1;
                }
            }
        }
    }
    clearAjaxNetJunk();
}
// Evoids the update panel auto generated scripts to grow to inifity. X-(
function clearAjaxNetJunk()
{
    var knowJunk = 'Sys.Application.add_init(function() {';
    var count = 0;
    var head = document.getElementsByTagName('head')[0];

    var scripts = document.getElementsByTagName('script');
    var firstScript;
    for(var x=0;x<scripts.length;>    {
        if (scripts[x].textContent)
        {
            if(scripts[x].textContent.indexOf(knowJunk) != -1)
            {
                if (count == 0)
                {
                    firstScript = scripts[x];
                    count++;
                }
                else
                {
                    head.removeChild(firstScript);
                    firstScript = scripts[x];
                    count = 1;
                }
            }
        }
    }
}

Pretty cool, ah...jejeje This part of what i posted some time ago here.

Hope this help... :)

How to use RecyclerView inside NestedScrollView?

if you want to use RecyclerView in NestedScrollView this is a simple tricky, just set :

RecyclerView

  • recyclerView.setHasFixedSize(false) (java/kt)

  • android:nestedScrollingEnabled="false"

  • android:layout_height="wrap_content"

  • android:overScrollMode="never"

NestedScrollView

  • android:fillViewport="true"

this is work for me, and you can use many RecyclerView in NestedScrollView with this too.

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try details: use any option..

    MessageBox.Show("your message",
    "window title", 
    MessageBoxButtons.OK, 
    MessageBoxIcon.Warning // for Warning  
    //MessageBoxIcon.Error // for Error 
    //MessageBoxIcon.Information  // for Information
    //MessageBoxIcon.Question // for Question
   );

How to initialize var?

C# is a strictly/strongly typed language. var was introduced for compile-time type-binding for anonymous types yet you can use var for primitive and custom types that are already known at design time. At runtime there's nothing like var, it is replaced by an actual type that is either a reference type or value type.

When you say,

var x = null; 

the compiler cannot resolve this because there's no type bound to null. You can make it like this.

string y = null;
var x = y;

This will work because now x can know its type at compile time that is string in this case.

How do I determine whether my calculation of pi is accurate?

You could use multiple approaches and see if they converge to the same answer. Or grab some from the 'net. The Chudnovsky algorithm is usually used as a very fast method of calculating pi. http://www.craig-wood.com/nick/articles/pi-chudnovsky/

How to change Angular CLI favicon

For those needing a dynamically added favicon here is what I did with an app initializer:

import { APP_INITIALIZER, FactoryProvider } from '@angular/core'

export function faviconInitFactory () {

 return () => {
  const link: any = document.querySelector(`link[rel*='icon']`) || document.createElement('link')
  link.type = 'image/x-icon'
  link.rel = 'shortcut icon'

  if (someExpression) {
    link.href = 'url' || 'base64'
  } else {
    link.href = 'url' || 'base64'
  }

  document.getElementsByTagName('head')[ 0 ].appendChild(link)
}

}

export const FAVICON_INIT_PROVIDER: FactoryProvider = {
  provide: APP_INITIALIZER,
  multi: true,
  useFactory: faviconInitFactory,
  deps: []
}

Just remove fav.ico file under src/ and add this. The favicon will be added before app start

How to find keys of a hash?

There is function in modern JavaScript (ECMAScript 5) called Object.keys performing this operation:

var obj = { "a" : 1, "b" : 2, "c" : 3};
alert(Object.keys(obj)); // will output ["a", "b", "c"]

Compatibility details can be found here.

On the Mozilla site there is also a snippet for backward compatibility:

if(!Object.keys) Object.keys = function(o){
   if (o !== Object(o))
      throw new TypeError('Object.keys called on non-object');
   var ret=[],p;
   for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
   return ret;
}

Changing datagridview cell color based on condition

make it simple

private void dataGridView1_cellformatting(object sender,DataGridViewCellFormattingEventArgs e)
{
     var amount = (int)e.Value;

     // return if rowCount = 0
     if (this.dataGridView1.Rows.Count == 0)
         return;

     if (amount > 0)
         e.CellStyle.BackColor = Color.Green; 
     else
         e.CellStyle.BackColor = Color.Red;

}

take a look cell formatting

How to add bootstrap to an angular-cli project

Updated Aug-2020: Angular 10

"If you have an Angular = 9 CLI project, you could simply use our schematics to add ng-bootstrap library to it." Just run the following command inside your project folder. All the configurations will be automatically added.

ng add @ng-bootstrap/ng-bootstrap

ng s

Sample Snippets:

import {Component} from '@angular/core';

@Component({selector: 'ngbd-alert-basic', templateUrl: './alert-basic.html'})
export class NgbdAlertBasic {
}

_x000D_
_x000D_
<p>
  <ngb-alert [dismissible]="false">
    <strong>Warning!</strong> Better check yourself, you're not looking too good.
  </ngb-alert>
</p>
_x000D_
_x000D_
_x000D_

How to restart a node.js server

If it's just running (not a daemon) then just use Ctrl-C.

If it's daemonized then you could try:

$ ps aux | grep node
you   PID  1.5  0.2  44172  8260 pts/2    S    15:25   0:00 node app.js
$ kill -2 PID

Where PID is replaced by the number in the output of ps.

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

I guess the best way to do this is like this :

  1. Store all your changes in a separate branch.
  2. Then do a hard reset on the local master.
  3. Then merge back your changes from the locally created branch
  4. Then commit and push your changes.

That how I resolve mine, whenever it happens.

ORA-28001: The password has expired

I have fixed the problem, just need to check:

open_mode from v$database

and then check:

check account_status to get mode information

and then use:

alter user myuser identified by mynewpassword account unlock;

How do I raise an exception in Rails so it behaves like other Rails exceptions?

If you need an easier way to do it, and don't want much fuss, a simple execution could be:

raise Exception.new('something bad happened!')

This will raise an exception, say e with e.message = something bad happened!

and then you can rescue it as you are rescuing all other exceptions in general.

How to pause a YouTube player when hiding the iframe?

A more concise, elegant, and secure answer: add “?enablejsapi=1” to the end of the video URL, then construct and stringify an ordinary object representing the pause command:

const YouTube_pause_video_command_JSON = JSON.stringify(Object.create(null, {
    "event": {
        "value": "command",
        "enumerable": true
    },
    "func": {
        "value": "pauseVideo",
        "enumerable": true
    }
}));

Use the Window.postMessage method to send the resulting JSON string to the embedded video document:

// |iframe_element| is defined elsewhere.
const video_URL = iframe_element.getAttributeNS(null, "src");
iframe_element.contentWindow.postMessage(YouTube_pause_video_command_JSON, video_URL);

Make sure you specify the video URL for the Window.postMessage method’s targetOrigin argument to ensure that your messages won’t be sent to any unintended recipient.

How can I make a clickable link in an NSAttributedString?

The quick answer is using UITextView instead of UILabel. You need to enable Selectable and disable Editable.

Then disable scroll indicators and bounces.

Screen Shot

Screen Shot

My solution using NSMutableAttributedString from html string NSHTMLTextDocumentType

NSString *s = @"<p><a href='https://itunes.apple.com/us/app/xxxx/xxxx?mt=8'>https://itunes.apple.com/us/app/xxxx/xxxx?mt=8</a></p>";

NSMutableAttributedString *text = [[NSMutableAttributedString alloc]
                                           initWithData: [s dataUsingEncoding:NSUnicodeStringEncoding]
                                           options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                                           documentAttributes: nil
                                           error: nil
                                           ];

cell.content.attributedText = text;

iOS 7's blurred overlay effect using CSS?

You made me want to try, so I did, check out the example here:

http://codepen.io/Edo_B/pen/cLbrt

Using:

  1. HW Accelerated CSS filters
  2. JS for class assigning and arrow key events
  3. Images CSS Clip property

that's it.

I also believe this could be done dynamically for any screen if using canvas to copy the current dom and blurring it.

How to read numbers separated by space using scanf

I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases.

scanf("%d %d %d", &var1, &var2, &var3);

Similarly if you want to read comma separated values use :

scanf("%d,%d,%d", &var1, &var2, &var3);

Getting Data from Android Play Store

I've coded a small Node.js module to scrape app and list data from Google Play: google-play-scraper

var gplay = require('google-play-scrapper');

gplay.List({
    category: gplay.category.GAME_ACTION,
    collection: gplay.collection.TOP_FREE,
    num: 2
  }).then(console.log);

Results:

 [ { url: 'https://play.google.com/store/apps/details?id=com.playappking.busrush',
    appId: 'com.playappking.busrush',
    title: 'Bus Rush',
    developer: 'Play App King',
    icon: 'https://lh3.googleusercontent.com/R6hmyJ6ls6wskk5hHFoW02yEyJpSG36il4JBkVf-Aojb1q4ZJ9nrGsx6lwsRtnTqfA=w340',
    score: 3.9,
    price: '0',
    free: false },
  { url: 'https://play.google.com/store/apps/details?id=com.yodo1.crossyroad',
    appId: 'com.yodo1.crossyroad',
    title: 'Crossy Road',
    developer: 'Yodo1 Games',
    icon: 'https://lh3.googleusercontent.com/doHqbSPNekdR694M-4rAu9P2B3V6ivff76fqItheZGJiN4NBw6TrxhIxCEpqgO3jKVg=w340',
    score: 4.5,
    price: '0',
    free: false } ]

Array slices in C#

If you want IEnumerable<byte>, then just

IEnumerable<byte> data = foo.Take(x);

python tuple to dict

Even more concise if you are on python 2.7:

>>> t = ((1,'a'),(2,'b'))
>>> {y:x for x,y in t}
{'a':1, 'b':2}

jquery to validate phone number

Your code:

rules: {
    phoneNumber: {
        matches: "[0-9]+",  // <-- no such method called "matches"!
        minlength:10,
        maxlength:10
    }
}

There is no such callback function, option, method, or rule called matches anywhere within the jQuery Validate plugin. (EDIT: OP failed to mention that matches is his custom method.)

However, within the additional-methods.js file, there are several phone number validation methods you can use. The one called phoneUS should satisfy your pattern. Since the rule already validates the length, minlength and maxlength are redundantly unnecessary. It's also much more comprehensive in that area codes and prefixes can not start with a 1.

rules: {
    phoneNumber: {
        phoneUS: true
    }
}

DEMO: http://jsfiddle.net/eWhkv/


If, for whatever reason, you just need the regex for use in another method, you can take it from here...

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, "");
    return this.optional(element) || phone_number.length > 9 && 
    phone_number.match(/^(\+?1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");

Installing MySQL Python on Mac OS X

For Python 3+ the mysql-python library is broken. Instead, use the mysqlclient library. Install with: pip install mysqlclient

It is a fork of mysql-python (also known as MySQLdb) that supports Python 3+

This library talks to the MySQL client's C-interface, and is faster than the pure-python pymysql libray.

Note: you will need the mysql-developer tools installed. An easy way to do this on a Mac is to run

brew install mysql-connector-c

to delegate this task to homebrew. If you are on linux, you can install these via the instructions at the mysqlclient github page.

Composer: how can I install another dependency without updating old ones?

To install a new package and only that, you have two options:

  1. Using the require command, just run:

    composer require new/package
    

    Composer will guess the best version constraint to use, install the package, and add it to composer.lock.

    You can also specify an explicit version constraint by running:

    composer require new/package ~2.5
    

–OR–

  1. Using the update command, add the new package manually to composer.json, then run:

    composer update new/package
    

If Composer complains, stating "Your requirements could not be resolved to an installable set of packages.", you can resolve this by passing the flag --with-dependencies. This will whitelist all dependencies of the package you are trying to install/update (but none of your other dependencies).

Regarding the question asker's issues with Laravel and mcrypt: check that it's properly enabled in your CLI php.ini. If php -m doesn't list mcrypt then it's missing.

Important: Don't forget to specify new/package when using composer update! Omitting that argument will cause all dependencies, as well as composer.lock, to be updated.

How to show MessageBox on asp.net?

There is pretty concise and easy way:

Response.Write("<script>alert('Your text');</script>");

addEventListener for keydown on Canvas

Sometimes just setting canvas's tabindex to '1' (or '0') works. But sometimes - it doesn't, for some strange reason.

In my case (ReactJS app, dynamic canvas el creation and mount) I need to call canvasEl.focus() to fix it. Maybe this is somehow related to React (my old app based on KnockoutJS works without '..focus()' )

Send FormData and String Data Together Through JQuery AJAX?

For Multiple file input : Try this code :

 <form name="form" id="form" method="post" enctype="multipart/form-data">
    <input type="file" name="file[]">
    <input type="file" name="file[]" >
    <input type="text" name="name" id="name">
    <input type="text" name="name1" id="name1">
    <input type="button" name="submit" value="upload" id="upload">
 </form>


 $('#upload').on('click', function() {
  var fd = new FormData();
    var c=0;
    var file_data;
    $('input[type="file"]').each(function(){
        file_data = $('input[type="file"]')[c].files; // for multiple files

     for(var i = 0;i<file_data.length;i++){
         fd.append("file_"+c, file_data[i]);
     }
    c++;
 }); 
     var other_data = $('form').serializeArray();
     $.each(other_data,function(key,input){
         fd.append(input.name,input.value);
     });
     $.ajax({
         url: 'work.php',
         data: fd,
         contentType: false,
         processData: false,
         type: 'POST',
         success: function(data){
             console.log(data);
         }
     });
 });

How can I check if a command exists in a shell script?

Try using type:

type foobar

For example:

$ type ls
ls is aliased to `ls --color=auto'

$ type foobar
-bash: type: foobar: not found

This is preferable to which for a few reasons:

  1. The default which implementations only support the -a option that shows all options, so you have to find an alternative version to support aliases

  2. type will tell you exactly what you are looking at (be it a Bash function or an alias or a proper binary).

  3. type doesn't require a subprocess

  4. type cannot be masked by a binary (for example, on a Linux box, if you create a program called which which appears in path before the real which, things hit the fan. type, on the other hand, is a shell built-in (yes, a subordinate inadvertently did this once).

Can you use @Autowired with static fields?

You can achieve this using XML notation and the MethodInvokingFactoryBean. For an example look here.

private static StaticBean staticBean;

public void setStaticBean(StaticBean staticBean) {
   StaticBean.staticBean = staticBean;
}

You should aim to use spring injection where possible as this is the recommended approach but this is not always possible as I'm sure you can imagine as not everything can be pulled from the spring container or you maybe dealing with legacy systems.

Note testing can also be more difficult with this approach.

How to make a div have a fixed size?

<div>
  <img src="whatever it is" class="image-crop">
</div>

 /*mobile code*/
    .image-crop{
      width:100%;
      max-height: auto;
     }
    /*desktop code*/

  @media screen and (min-width: 640px) {
    .image-crop{
       width:100%;
       max-height: 140px;
      }

Force git stash to overwrite added files

To force git stash pop run this command

git stash show -p | git apply && git stash drop

Download image from the site in .NET/C#

There is no need to involve any image classes, you can simply call WebClient.DownloadFile:

string localFilename = @"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
    client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}

Update
Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:

private static void DownloadRemoteImageFile(string uri, string fileName)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // Check that the remote file was found. The ContentType
    // check is performed since a request for a non-existent
    // image file might be redirected to a 404-page, which would
    // yield the StatusCode "OK", even though the image was not
    // found.
    if ((response.StatusCode == HttpStatusCode.OK || 
        response.StatusCode == HttpStatusCode.Moved || 
        response.StatusCode == HttpStatusCode.Redirect) &&
        response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
    {

        // if the remote file was found, download oit
        using (Stream inputStream = response.GetResponseStream())
        using (Stream outputStream = File.OpenWrite(fileName))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            do
            {
                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                outputStream.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
        }
    }
}

In brief, it makes a request for the file, verifies that the response code is one of OK, Moved or Redirect and also that the ContentType is an image. If those conditions are true, the file is downloaded.

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

for anyone tunnelling with SSH; you can create a version of the gem command that uses SOCKS proxy:

  1. Install socksify with gem install socksify (you'll need to be able to do this step without proxy, at least)
  2. Copy your existing gem exe

    cp $(command which gem) /usr/local/bin/proxy_gem
    
  3. Open it in your favourite editor and add this at the top (after the shebang)

    require 'socksify'
    
    if ENV['SOCKS_PROXY']
      require 'socksify'
      host, port = ENV['SOCKS_PROXY'].split(':')
      TCPSocket.socks_server = host || 'localhost'
      TCPSocket.socks_port = port.to_i || 1080
    end
    
  4. Set up your tunnel

    ssh -D 8123 -f -C -q -N user@proxy
    
  5. Run your gem command with proxy_gem

    SOCKS_PROXY=localhost:8123 proxy_gem push mygem
    

PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>"> 

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

exit application when click button - iOS

exit(X), where X is a number (according to the doc) should work. But it is not recommended by Apple and won't be accepted by the AppStore. Why? Because of these guidelines (one of my app got rejected):

We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.

Please refer to the attached screenshot/s for reference.

The iOS Human Interface Guidelines specify,

"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:

Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.

Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."

> It would be appropriate to remove any mechanisms for quitting your app.

Plus, if you try to hide that function, it would be understood by the user as a crash.

Lists in ConfigParser

So another way, which I prefer, is to just split the values, for example:

#/path/to/config.cfg
[Numbers]
first_row = 1,2,4,8,12,24,36,48

Could be loaded like this into a list of strings or integers, as follows:

import configparser

config = configparser.ConfigParser()
config.read('/path/to/config.cfg')

# Load into a list of strings
first_row_strings = config.get('Numbers', 'first_row').split(',')

# Load into a list of integers
first_row_integers = [int(x) for x in config.get('Numbers', 'first_row').split(',')]

This method prevents you from needing to wrap your values in brackets to load as JSON.

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

Here is a complete example from your data that shows a bar of for each required value at each date:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

What is the best way to convert seconds into (Hour:Minutes:Seconds:Milliseconds) time?

This will return in hh:mm:ss format

 public static string ConvertTime(long secs)
    {
        TimeSpan ts = TimeSpan.FromSeconds(secs);
        string displayTime = $"{ts.Hours}:{ts.Minutes}:{ts.Seconds}";
        return displayTime;
    }

Unix ls command: show full path when using options

Use this command:

ls -ltr /mig/mthome/09/log/*

instead of:

ls -ltr /mig/mthome/09/log

to get the full path in the listing.

Plot different DataFrames in the same figure

If you a running Jupyter/Ipython notebook and having problems using;

ax = df1.plot()

df2.plot(ax=ax)

Run the command inside of the same cell!! It wont, for some reason, work when they are separated into sequential cells. For me at least.

How to list physical disks?

If you only need to look at the existing disks, this one will suffice:

powershell "get-physicaldisk"

C# - Making a Process.Start wait until the process has start-up

Do you mean wait until it's done? Then use Process.WaitForExit:

var process = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "popup.exe"
    }
};
process.Start();
process.WaitForExit();

Alternatively, if it's an application with a UI that you are waiting to enter into a message loop, you can say:

process.Start();
process.WaitForInputIdle();

Lastly, if neither of these apply, just Thread.Sleep for some reasonable amount of time:

process.Start();
Thread.Sleep(1000); // sleep for one second

Adding Jar files to IntellijIdea classpath

Go to File-> Project Structure-> Libraries and click green "+" to add the directory folder that has the JARs to CLASSPATH. Everything in that folder will be added to CLASSPATH.

Update:

It's 2018. It's a better idea to use a dependency manager like Maven and externalize your dependencies. Don't add JAR files to your project in a /lib folder anymore.

Screenshot

What's the difference between using "let" and "var"?

Scoping rules

Main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope).

function run() {
  var foo = "Foo";
  let bar = "Bar";

  console.log(foo, bar); // Foo Bar

  {
    var moo = "Mooo"
    let baz = "Bazz";
    console.log(moo, baz); // Mooo Bazz
  }

  console.log(moo); // Mooo
  console.log(baz); // ReferenceError
}

run();

The reason why let keyword was introduced to the language was function scope is confusing and was one of the main sources of bugs in JavaScript.

Take a look at this example from another stackoverflow question:

var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
  // and store them in funcs
  funcs[i] = function() {
    // each should log its value.
    console.log("My value: " + i);
  };
}
for (var j = 0; j < 3; j++) {
  // and now let's run each one to see
  funcs[j]();
}

My value: 3 was output to console each time funcs[j](); was invoked since anonymous functions were bound to the same variable.

People had to create immediately invoked functions to capture correct value from the loops but that was also hairy.

Hoisting

While variables declared with var keyword are hoisted (initialized with undefined before the code is run) which means they are accessible in their enclosing scope even before they are declared:

function run() {
  console.log(foo); // undefined
  var foo = "Foo";
  console.log(foo); // Foo
}

run();

let variables are not initialized until their definition is evaluated. Accessing them before the initialization results in a ReferenceError. Variable said to be in "temporal dead zone" from the start of the block until the initialization is processed.

function checkHoisting() {
  console.log(foo); // ReferenceError
  let foo = "Foo";
  console.log(foo); // Foo
}

checkHoisting();

Creating global object property

At the top level, let, unlike var, does not create a property on the global object:

var foo = "Foo";  // globally scoped
let bar = "Bar"; // globally scoped

console.log(window.foo); // Foo
console.log(window.bar); // undefined

Redeclaration

In strict mode, var will let you re-declare the same variable in the same scope while let raises a SyntaxError.

'use strict';
var foo = "foo1";
var foo = "foo2"; // No problem, 'foo' is replaced.

let bar = "bar1";
let bar = "bar2"; // SyntaxError: Identifier 'bar' has already been declared

How to find out which processes are using swap space in Linux?

It's not entirely clear if you mean you want to find the process who has most pages swapped out or process who caused most pages to be swapped out.

For the first you may run top and order by swap (press 'Op'), for the latter you can run vmstat and look for non-zero entries for 'so'.

How do you get a directory listing sorted by creation date in python?

Turns out os.listdir sorts by last modified but in reverse so you can do:

import os
last_modified=os.listdir()[::-1]

How to change the font size on a matplotlib plot

Based on the above stuff:

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

fontPath = "/usr/share/fonts/abc.ttf"
font = fm.FontProperties(fname=fontPath, size=10)
font2 = fm.FontProperties(fname=fontPath, size=24)

fig = plt.figure(figsize=(32, 24))
fig.text(0.5, 0.93, "This is my Title", horizontalalignment='center', fontproperties=font2)

plot = fig.add_subplot(1, 1, 1)

plot.xaxis.get_label().set_fontproperties(font)
plot.yaxis.get_label().set_fontproperties(font)
plot.legend(loc='upper right', prop=font)

for label in (plot.get_xticklabels() + plot.get_yticklabels()):
    label.set_fontproperties(font)

Difference between null and empty ("") Java String

In Java a reference type assigned null has no value at all. A string assigned "" has a value: an empty string, which is to say a string with no characters in it. When a variable is assigned null it means there is no underlying object of any kind, string or otherwise.

onchange event for input type="number"

<input type="number" id="n" value="0" step=".5" />
<input type="hidden" id="v" value = "0"/>

<script>
$("#n").bind('keyup mouseup', function () {
    var current = $("#n").val();
    var prevData = $("#v").val(); 
    if(current > prevData || current < prevData){
       $("#v").val(current);
       var newv = $("#v").val(); 
       alert(newv);
    } 
});  
</script>

http://jsfiddle.net/patrickrobles53/s10wLjL3/

I've used a hidden input type to be the container of the previous value that will be needed for the comparison on the next change.

SVN checkout the contents of a folder, not the folder itself

Just add the directory on the command line:

svn checkout svn://192.168.1.1/projectname/ target-directory/

How can I find the maximum value and its index in array in MATLAB?

3D case

Modifying Mohsen's answer for 3D array:

[M,I] = max (A(:));
[ind1, ind2, ind3] = ind2sub(size(A),I)

What's the equivalent of Java's Thread.sleep() in JavaScript?

You can either write a spin loop (a loop that just loops for a long period of time performing some sort of computation to delay the function) or use:

setTimeout("Func1()", 3000);

This will call 'Func1()' after 3 seconds.

Edit:

Credit goes to the commenters, but you can pass anonymous functions to setTimeout.

setTimeout(function() {
   //Do some stuff here
}, 3000);

This is much more efficient and does not invoke javascript's eval function.

How to get number of video views with YouTube API?

look at yt:statistics tag. It provides viewCount, videoWatchCount, favoriteCount etc.

Using "If cell contains #N/A" as a formula condition.

Input the following formula in C1:

=IF(ISNA(A1),B1,A1*B1)

Screenshots:

When #N/A:

enter image description here

When not #N/A:

enter image description here

Let us know if this helps.

Failed to instantiate module error in Angular js

Or the minified version of the file...

<script src="angular-route.min.js"></script>

More information about this here:

"This error occurs when a module fails to load due to some exception. The error message above should provide additional context."

"In AngularJS 1.2.0 and later, ngRoute has been moved to its own module. If you are getting this error after upgrading to 1.2.x, be sure that you've installed ngRoute."

Listed under section Error: $injector:modulerr Module Error in the Angularjs docs.

Select rows having 2 columns equal value

Select * from tablename t1, tablename t2, tablename t3 
where t1.C1 = t2.c2 and t2.c2 = t3.c3 

Seems like this will work. Though does not seems like an efficient way.

Laravel Pagination links not including other GET parameters

Be aware of the Input::all() , it will Include the previous ?page= values again and again in each page you open !
for example if you are in ?page=1 and you open the next page, it will open ?page=1&page=2
So the last value page takes will be the page you see ! not the page you want to see

Solution : use Input::except(array('page'))

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Hibernate Optional findTopByClientIdAndStatusOrderByCreateTimeDesc(Integer clientId, Integer status);

"findTop"!! The only one result!

How to check String in response body with mockMvc

@Sotirios Delimanolis answer do the job however I was looking for comparing strings within this mockMvc assertion

So here it is

.andExpect(content().string("\"Username already taken - please try with different username\""));

Of course my assertion fail:

java.lang.AssertionError: Response content expected:
<"Username already taken - please try with different username"> but was:<"Something gone wrong">

because:

  MockHttpServletResponse:
            Body = "Something gone wrong"

So this is proof that it works!

What is the difference between logical data model and conceptual data model?

Logical Database Model

Logical database modeling is required for compiling business requirements and representing the requirements as a model. It is mainly associated with the gathering of business needs rather than the database design. The information that needs to be gathered is about organizational units, business entities, and business processes.

Once the information is compiled, reports and diagrams are made, including these:

ERD–Entity relationship diagram shows the relationship between different categories of data and shows the different categories of data required for the development of a database. Business process diagram–It shows the activities of individuals within the company. It shows how the data moves within the organization based on which application interface can be designed. Feedback documentation by users.

Logical database models basically determine if all the requirements of the business have been gathered. It is reviewed by developers, management, and finally the end users to see if more information needs to be gathered before physical modeling starts.

Physical Database Model Physical database modeling deals with designing the actual database based on the requirements gathered during logical database modeling. All the information gathered is converted into relational models and business models. During physical modeling, objects are defined at a level called a schema level. A schema is considered a group of objects which are related to each other in a database. Tables and columns are made according to the information provided during logical modeling. Primary keys, unique keys, and foreign keys are defined in order to provide constraints. Indexes and snapshots are defined. Data can be summarized, and users are provided with an alternative perspective once the tables have been created.

Physical database modeling depends upon the software already being used in the organization. It is software specific. Physical modeling includes:

Server model diagram–It includes tables and columns and different relationships that exist within a database. Database design documentation. Feedback documentation of users.

Summary:

1.Logical database modeling is mainly for gathering information about business needs and does not involve designing a database; whereas physical database modeling is mainly required for actual designing of the database. 2.Logical database modeling does not include indexes and constraints; the logical database model for an application can be used across various database software and implementations; whereas physical database modeling is software and hardware specific and has indexes and constraints. 3.Logical database modeling includes; ERD, business process diagrams, and user feedback documentation; whereas physical database modeling includes; server model diagram, database design documentation, and user feedback documentation.

Read more: Difference Between Logical and Physical Database Model | Difference Between | Logical vs Physical Database Model http://www.differencebetween.net/technology/software-technology/difference-between-logical-and-physical-database-model/#ixzz3AxPVhTlg

Undefined reference to static class member

You need to actually define the static member somewhere (after the class definition). Try this:

class Foo { /* ... */ };

const int Foo::MEMBER;

int main() { /* ... */ }

That should get rid of the undefined reference.

Correct Semantic tag for copyright info - html5

it is better to include it in a <small> tag The HTML <small> tag is used for specifying small print.

Small print (also referred to as "fine print" or "mouseprint") usually refers to the part of a document that contains disclaimers, caveats, or legal restrictions, such as copyrights. And this tag is supported in all major browsers.

<footer>
 <small>&copy; Copyright 2058, Example Corporation</small>
</footer>

Can I recover a branch after its deletion in Git?

The top voted solution does actually more than requested:

git checkout <sha>
git checkout -b <branch>

or

git checkout -b <branch> <sha>

move you to the new branch together with all recent changes you might have forgot to commit. This may not be your intention, especially when in the "panic mode" after losing the branch.

A cleaner (and simpler) solution seems to be the one-liner (after you found the <sha> with git reflog):

git branch <branch> <sha>

Now neither your current branch nor uncommited changes are affected. Instead only a new branch will be created all the way up to the <sha>.

If it is not the tip, it'll still work and you get a shorter branch, then you can retry with new <sha> and new branch name until you get it right.

Finally you can rename the successfully restored branch into what it was named or anything else:

git branch -m <restored branch> <final branch>

Needless to say, the key to success was to find the right commit <sha>, so name your commits wisely :)

Java integer list

code that works, but output is:

10
20
30
40
50

so:

    List<Integer> myCoords = new ArrayList<Integer>();
    myCoords.add(10);
    myCoords.add(20);
    myCoords.add(30);
    myCoords.add(40);
    myCoords.add(50);
    for (Integer number : myCoords) {
        System.out.println(number);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

JPA CascadeType.ALL does not delete orphans

If you are using it with Hibernate, you'll have to explicitly define the annotation CascadeType.DELETE_ORPHAN, which can be used in conjunction with JPA CascadeType.ALL.

If you don't plan to use Hibernate, you'll have to explicitly first delete the child elements and then delete the main record to avoid any orphan records.

execution sequence

  1. fetch main row to be deleted
  2. fetch child elements
  3. delete all child elements
  4. delete main row
  5. close session

With JPA 2.0, you can now use the option orphanRemoval = true

@OneToMany(mappedBy="foo", orphanRemoval=true)

Reading an integer from user input

Try this it will not throw exception and user can try again:

        Console.WriteLine("1. Add account.");
        Console.WriteLine("Enter choice: ");
        int choice = 0;
        while (!Int32.TryParse(Console.ReadLine(), out choice))
        {
            Console.WriteLine("Wrong input! Enter choice number again:");
        }

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

You are calling:

JSON.parse(scatterSeries)

But when you defined scatterSeries, you said:

var scatterSeries = []; 

When you try to parse it as JSON it is converted to a string (""), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.

scatterSeries is not JSON. Do not try to parse it as JSON.

data is not JSON either (getJSON will parse it as JSON automatically).

ch is JSON … but shouldn't be. You should just create a plain object in the first place:

var ch = {
    "name": "graphe1",
    "items": data.results[1]
};

scatterSeries.push(ch);

In short, for what you are doing, you shouldn't have JSON.parse anywhere in your code. The only place it should be is in the jQuery library itself.

Most Useful Attributes

I always use attributes, [Serializable], [WebMethod], [DefaultValue], [Description("description here")].

but beside that there is a Global Attributes in c#.

[assembly: System.CLSCompliant(true)]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDescription("")]

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

Redirecting a page using Javascript, like PHP's Header->Location

The PHP code is executed on the server, so your redirect is executed before the browser even sees the JavaScript.

You need to do the redirect in JavaScript too

$('.entry a:first').click(function()
{
    window.location.replace("http://www.google.com");
});

Spring MVC: Complex object as GET @RequestParam

While answers that refer to @ModelAttribute, @RequestParam, @PathParam and the likes are valid, there is a small gotcha I ran into. The resulting method parameter is a proxy that Spring wraps around your DTO. So, if you attempt to use it in a context that requires your own custom type, you may get some unexpected results.

The following will not work:

@GetMapping(produces = APPLICATION_JSON_VALUE)
public ResponseEntity<CustomDto> request(@ModelAttribute CustomDto dto) {
    return ResponseEntity.ok(dto);
}

In my case, attempting to use it in Jackson binding resulted in a com.fasterxml.jackson.databind.exc.InvalidDefinitionException.

You will need to create a new object from the dto.

How to implement infinity in Java?

A generic solution is to introduce a new type. It may be more involved, but it has the advantage of working for any type that doesn't define its own infinity.

If T is a type for which lteq is defined, you can define InfiniteOr<T> with lteq something like this:

class InfiniteOr with type parameter T:
    field the_T of type null-or-an-actual-T
    isInfinite()
        return this.the_T == null
    getFinite():
        assert(!isInfinite());
        return this.the_T
    lteq(that)
        if that.isInfinite()
            return true
        if this.isInfinite()
            return false
        return this.getFinite().lteq(that.getFinite())

I'll leave it to you to translate this to exact Java syntax. I hope the ideas are clear; but let me spell them out anyways.

The idea is to create a new type which has all the same values as some already existing type, plus one special value which—as far as you can tell through public methods—acts exactly the way you want infinity to act, e.g. it's greater than anything else. I'm using null to represent infinity here, since that seems the most straightforward in Java.

If you want to add arithmetic operations, decide what they should do, then implement that. It's probably simplest if you handle the infinite cases first, then reuse the existing operations on finite values of the original type.

There might or might not be a general pattern to whether or not it's beneficial to adopt a convention of handling left-hand-side infinities before right-hand-side infinities or vice versa; I can't tell without trying it out, but for less-than-or-equal (lteq) I think it's simpler to look at right-hand-side infinity first. I note that lteq is not commutative, but add and mul are; maybe that is relevant.

Note: coming up with a good definition of what should happen on infinite values is not always easy. It is for comparison, addition and multiplication, but maybe not subtraction. Also, there is a distinction between infinite cardinal and ordinal numbers which you may want to pay attention to.

Java BigDecimal: Round to the nearest whole value

I don't think you can round it like that in a single command. Try

    ArrayList<BigDecimal> list = new ArrayList<BigDecimal>();
    list.add(new BigDecimal("100.12"));
    list.add(new BigDecimal("100.44"));
    list.add(new BigDecimal("100.50"));
    list.add(new BigDecimal("100.75"));

    for (BigDecimal bd : list){
        System.out.println(bd+" -> "+bd.setScale(0,RoundingMode.HALF_UP).setScale(2));
    }

Output:
100.12 -> 100.00
100.44 -> 100.00
100.50 -> 101.00
100.75 -> 101.00

I tested for the rest of your examples and it returns the wanted values, but I don't guarantee its correctness.

Find in Files: Search all code in Team Foundation Server

There is another alternative solution, that seems to be more attractive.

  1. Setup a search server - could be any windows machine/server
  2. Setup a TFS notification service* (Bissubscribe) to get, delete, update files everytime a checkin happens. So this is a web service that acts like a listener on the TFS server, and updates/syncs the files and folders on the Search server. - this will dramatically improve the accuracy (live search), and avoid the one-time load of making periodic gets
  3. Setup an indexing service/windows indexed search on the Search server for the root folder
  4. Expose a web service to return search results

Now with all the above setup, you have a few options for the client:

  1. Setup a web page to call the search service and format the results to show on the webpage - you can also integrate this webpage inside visual studio (through a macro or a add-in)
  2. Create a windows client interface(winforms/wpf) to call the search service and format the results and show them on the UI - you can also integrate this client tool inside visual studio via VSPackages or add-in

Update: I did go this route, and it has been working nicely. Just wanted to add to this.

Reference links:

  1. Use this tool instead of bissubscribe.exe
  2. Handling TFS events
  3. Team System Notifications

Android Center text on canvas

Use this in your paint properties:

 textPaint.setTextAlign(Paint.Align.CENTER);

Link to a section of a webpage

your jump link looks like this

<a href="#div_id">jump link</a>

Then make

<div id="div_id"></div>

the jump link will take you to that div

How to make 'submit' button disabled?

Form validation is very much straight forward in Angular 2

Here is an example,

<form (ngSubmit)="onSubmit()" #myForm="ngForm">

 <div class="form-group">
  <label for="firstname">First Name</label>
  <input type="text" class="form-control" id="firstname" 
   required [(ngModel)]="firstname" name="firstname">
 </div>

 <div class="form-group">
  <label for="middlename">Middle Name</label>
  <input type="text"  class="form-control" id="middlename" 
   [(ngModel)]="middlename" name="middlename">
 </div>

 <div class="form-group">
  <label for="lastname">Last Name</label>
  <input type="text"  class="form-control" id="lastname" 
   required minlength = '2' maxlength="6" [(ngModel)] = "lastname" name="lastname">
 </div>

 <div class="form-group">
  <label for="mobnumber">Mob Number</label>
  <input type="text"  class="form-control" id="mobnumber"  
   minlength = '2' maxlength="10" pattern="^[0-9()\-+\s]+$" 
   [(ngModel)] = "mobnumber" name="mobnumber">
 </div>

 <button type="submit" [disabled]="!myForm.form.valid">Submit</button>

</form>

Check this plunker for demo

More info

How to show full column content in a Spark Dataframe?

try this command :

df.show(df.count())

How to add Python to Windows registry

You can find the Python executable with this command:

C:\> where python.exe

It should return something like:

C:\Users\<user>\AppData\Local\enthought\Canopy32\User\python.exe

Open regedit, navigate to HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\<version>\PythonPath and add or edit the default key with this the value found in the first command. Logout, login and python should be found. SciKit can now be installed.

See Additional “application paths” in https://docs.python.org/2/using/windows.html#finding-modules for more details.

Console app arguments, how arguments are passed to Main method

All answers are awesome and explained everything very well

but I just want to point out different way for passing args to main method

in visual studio

  1. right click on Project then choose Properties
  2. go to Debug tab then on the Start Options section provide the app with your args

like this image

Properties window

and happy knowing secrets

What is the standard way to add N seconds to datetime.time in Python?

Try adding a datetime.datetime to a datetime.timedelta. If you only want the time portion, you can call the time() method on the resultant datetime.datetime object to get it.

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)

or

View -> Log

or by using mysql query

show errors;

Restore the mysql database from .frm files

Copy all file and replace to /var/lib/mysql , after that you must change owner of files to mysql this is so important if mariadb.service restart has been faild

chown -R mysql:mysql /var/lib/mysql/*

and

chmod -R 700 /var/lib/mysql/*

Leave out quotes when copying from cell

You can do this in an Excel macro via VBA, sending the results to a file:

Sub SimpleVBAWriteToFileWithoutQuotes()
    Open "c:\TEMP\Excel\out.txt" For Output As #1
    Print #1, Application.ActiveSheet.Cells(2, 3)
    Close #1
End Sub

And if you are wanting to get filenames and content into multiple files, here is a short snippet that avoids the double quotes around the output.

Sub DumpCellDataToTextFilesWithoutDoubleQuotes()
    ' this will work for filename and content in two different columns such as:
    ' filename column       data column
    ' 101                   this is some data
    ' 102                   this is more data

    Dim rngData As Range
    Dim strData As String
    Dim strTempFile As String
    Dim strFilename As String
    Dim i As Long
    Dim intFilenameColumn As Integer
    Dim intDataColumn As Integer
    Dim intStartingRow As Integer

    intFilenameColumn = 1     ' the column number containing the filenames
    intDataColumn = 3         ' the column number containing the data
    intStartingRow = 2        ' the row number to start gathering data


    For i = intStartingRow To Range("A1", Range("A1").End(xlDown)).Rows.Count

        ' copy the data cell's value
        Set rngData = Application.ActiveSheet.Cells(i, intDataColumn)

        ' get the base filename
        strFilename = Application.ActiveSheet.Cells(i, intFilenameColumn)

        ' assemble full filename and path
        strTempFile = "w:\TEMP\Excel\" & strFilename & ".txt"

        ' write to temp file
        Open strTempFile For Output As #1
        Print #1, rngData
        Close #1

    Next i

    ' goto home cell
    Application.ActiveSheet.Cells(1, 1).Select
    Range("A1").ClearOutline
End Sub

How to debug PDO database queries?

An old post but perhaps someone will find this useful;

function pdo_sql_debug($sql,$placeholders){
    foreach($placeholders as $k => $v){
        $sql = preg_replace('/:'.$k.'/',"'".$v."'",$sql);
    }
    return $sql;
}

What is the correct way to create a single-instance WPF application?

The following code is my WCF named pipes solution to register a single-instance application. It's nice because it also raises an event when another instance attempts to start, and receives the command line of the other instance.

It's geared toward WPF because it uses the System.Windows.StartupEventHandler class, but this could be easily modified.

This code requires a reference to PresentationFramework, and System.ServiceModel.

Usage:

class Program
{
    static void Main()
    {
        var applicationId = new Guid("b54f7b0d-87f9-4df9-9686-4d8fd76066dc");

        if (SingleInstanceManager.VerifySingleInstance(applicationId))
        {
            SingleInstanceManager.OtherInstanceStarted += OnOtherInstanceStarted;

            // Start the application
        }
    }

    static void OnOtherInstanceStarted(object sender, StartupEventArgs e)
    {
        // Do something in response to another instance starting up.
    }
}

Source Code:

/// <summary>
/// A class to use for single-instance applications.
/// </summary>
public static class SingleInstanceManager
{
  /// <summary>
  /// Raised when another instance attempts to start up.
  /// </summary>
  public static event StartupEventHandler OtherInstanceStarted;

  /// <summary>
  /// Checks to see if this instance is the first instance running on this machine.  If it is not, this method will
  /// send the main instance this instance's startup information.
  /// </summary>
  /// <param name="guid">The application's unique identifier.</param>
  /// <returns>True if this instance is the main instance.</returns>
  public static bool VerifySingleInstace(Guid guid)
  {
    if (!AttemptPublishService(guid))
    {
      NotifyMainInstance(guid);

      return false;
    }

    return true;
  }

  /// <summary>
  /// Attempts to publish the service.
  /// </summary>
  /// <param name="guid">The application's unique identifier.</param>
  /// <returns>True if the service was published successfully.</returns>
  private static bool AttemptPublishService(Guid guid)
  {
    try
    {
      ServiceHost serviceHost = new ServiceHost(typeof(SingleInstance));
      NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
      serviceHost.AddServiceEndpoint(typeof(ISingleInstance), binding, CreateAddress(guid));
      serviceHost.Open();

      return true;
    }
    catch
    {
      return false;
    }
  }

  /// <summary>
  /// Notifies the main instance that this instance is attempting to start up.
  /// </summary>
  /// <param name="guid">The application's unique identifier.</param>
  private static void NotifyMainInstance(Guid guid)
  {
    NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
    EndpointAddress remoteAddress = new EndpointAddress(CreateAddress(guid));
    using (ChannelFactory<ISingleInstance> factory = new ChannelFactory<ISingleInstance>(binding, remoteAddress))
    {
      ISingleInstance singleInstance = factory.CreateChannel();
      singleInstance.NotifyMainInstance(Environment.GetCommandLineArgs());
    }
  }

  /// <summary>
  /// Creates an address to publish/contact the service at based on a globally unique identifier.
  /// </summary>
  /// <param name="guid">The identifier for the application.</param>
  /// <returns>The address to publish/contact the service.</returns>
  private static string CreateAddress(Guid guid)
  {
    return string.Format(CultureInfo.CurrentCulture, "net.pipe://localhost/{0}", guid);
  }

  /// <summary>
  /// The interface that describes the single instance service.
  /// </summary>
  [ServiceContract]
  private interface ISingleInstance
  {
    /// <summary>
    /// Notifies the main instance that another instance of the application attempted to start.
    /// </summary>
    /// <param name="args">The other instance's command-line arguments.</param>
    [OperationContract]
    void NotifyMainInstance(string[] args);
  }

  /// <summary>
  /// The implementation of the single instance service interface.
  /// </summary>
  private class SingleInstance : ISingleInstance
  {
    /// <summary>
    /// Notifies the main instance that another instance of the application attempted to start.
    /// </summary>
    /// <param name="args">The other instance's command-line arguments.</param>
    public void NotifyMainInstance(string[] args)
    {
      if (OtherInstanceStarted != null)
      {
        Type type = typeof(StartupEventArgs);
        ConstructorInfo constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
        StartupEventArgs e = (StartupEventArgs)constructor.Invoke(null);
        FieldInfo argsField = type.GetField("_args", BindingFlags.Instance | BindingFlags.NonPublic);
        Debug.Assert(argsField != null);
        argsField.SetValue(e, args);

        OtherInstanceStarted(null, e);
      }
    }
  }
}

Why can't Python find shared objects that are in directories in sys.path?

For me what works here is to using a version manager such as pyenv, which I strongly recommend to get your project environments and package versions well managed and separate from that of the operative system.

I had this same error after an OS update, but was easily fixed with pyenv install 3.7-dev (the version I use).

Modulo operator with negative values

The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

That is all the language has to say, as far as C++03 is concerned.

Maximum number of rows in an MS Access database engine table?

It all depends. Theoretically using a single column with 4 byte data type. You could store 300 000 rows. But there is probably alot of overhead in the database even before you do anything. I read some where that you could have 1.000.000 rows but again, it all depends..

You can also link databases together. Limiting yourself to only disk space.

How to create an email form that can send email using html

you can use Simple Contact Form in HTML with PHP mailer. It's easy to implement in you website. You can try the demo from following link: Simple Contact/Feedback Form in HTML-PHP mailer

Otherwise you can watch the demo video in following link: Youtube: Simple Contact/Feedback Form in HTML-PHP mailer

When you are running in localhost, you may get following error:

Warning: mail(): Failed to connect to mailserver at "smtp.gmail.com" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in S:\wamp\www\sample\mailTo.php on line 10

You can check in this link for more detailed information: Simple Contact/Feedback Form in HTML with php (HTML-PHP mailer) And this is the screenshot of HTML form: Simple Form

And this is the main PHP coding:

<?php
if($_POST["submit"]) {
    $recipient="[email protected]"; //Enter your mail address
    $subject="Contact from Website"; //Subject 
    $sender=$_POST["name"];
    $senderEmail=$_POST["email"];
    $message=$_POST["comments"];
    $mailBody="Name: $sender\nEmail Address: $senderEmail\n\nMessage: $message";
    mail($recipient, $subject, $mailBody);
    sleep(1);
    header("Location:http://blog.antonyraphel.in/sample/"); // Set here redirect page or destination page
}
?>

AngularJS : How to watch service variables?

I have found a really great solution on the other thread with a similar problem but totally different approach. Source: AngularJS : $watch within directive is not working when $rootScope value is changed

Basically the solution there tells NOT TO use $watch as it is very heavy solution. Instead they propose to use $emit and $on.

My problem was to watch a variable in my service and react in directive. And with the above method it very easy!

My module/service example:

angular.module('xxx').factory('example', function ($rootScope) {
    var user;

    return {
        setUser: function (aUser) {
            user = aUser;
            $rootScope.$emit('user:change');
        },
        getUser: function () {
            return (user) ? user : false;
        },
        ...
    };
});

So basically I watch my user - whenever it is set to new value I $emit a user:change status.

Now in my case, in the directive I used:

angular.module('xxx').directive('directive', function (Auth, $rootScope) {
    return {
        ...
        link: function (scope, element, attrs) {
            ...
            $rootScope.$on('user:change', update);
        }
    };
});

Now in the directive I listen on the $rootScope and on the given change - I react respectively. Very easy and elegant!

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

How to add empty spaces into MD markdown readme on GitHub?

After different tries, I end up to a solution since most markdown interpreter support Math environment. The following adds one white space :

$~$

And here ten:

$~~~~~~~~~~~$

How to merge a transparent png image with another image using PIL

Image.paste does not work as expected when the background image also contains transparency. You need to use real Alpha Compositing.

Pillow 2.0 contains an alpha_composite function that does this.

background = Image.open("test1.png")
foreground = Image.open("test2.png")

Image.alpha_composite(background, foreground).save("test3.png")

EDIT: Both images need to be of the type RGBA. So you need to call convert('RGBA') if they are paletted, etc.. If the background does not have an alpha channel, then you can use the regular paste method (which should be faster).

How to pass data from 2nd activity to 1st activity when pressed back? - android

this is your first Activity1.

public class Activity1 extends Activity{
private int mRequestCode = 100;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = new Intent(this, Activity2.class);
    startActivityForResult(intent, mRequestCode);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == mRequestCode && resultCode == RESULT_OK){
        String editTextString = data.getStringExtra("editText");
    }
}
}

From here you are starting your Activity2.class by using startActivityForResult(mRequestCode, Activity2.class);

Now this is your second Activity, name is Activity2

public class Activity2 extends Activity {
private EditText mEditText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //mEditText = (EditText)findViewById(R.id.edit_text);

    Intent intent = new Intent();
    intent.putExtra("editText", mEditText.getText().toString());
    setResult(RESULT_OK, intent);
}

}

Now when you done with your second Activity then you call setResult() method, from onBackPress() or from any button click when your Activity2 will destroy then your Activity1's call back method onActivityResult() will call from there you can get your data from intent..

Hope it will help to you...:)

SQL Combine Two Columns in Select Statement

If your address1 = '123 Center St' and address2 = 'Apt 3B' then even if you combine and do a LIKE, you cannot search on searchstring as 'Center St 3B'. However, if your searchstring was 'Center St Apt', then you can do it using -

WHERE (address1 + ' ' + address2) LIKE '%searchstring%'

jQuery Mobile: Stick footer to bottom of page

The following lines work just fine...

var headerHeight = $( '#header' ).height();
var footerHeight = $( '#footer' ).height();
var footerTop = $( '#footer' ).offset().top;
var height = ( footerTop - ( headerHeight + footerHeight ) );
$( '#content' ).height( height );

inherit from two classes in C#

An common alternative to inheritance is delegation (also called composition): X "has a" Y rather than X "is a" Y. So if A has functionality for dealing with Foos, and B has functionality for dealing with Bars, and you want both in C, then something like this:

public class A() {
  private FooManager fooManager = new FooManager(); // (or inject, if you have IoC)

  public void handleFoo(Foo foo) {
    fooManager.handleFoo(foo);
  }
}

public class B() {
  private BarManager barManager = new BarManager(); // (or inject, if you have IoC)

  public void handleBar(Bar bar) {
    barManager.handleBar(bar);
  }
}

public class C() {
  private FooManager fooManager = new FooManager(); // (or inject, if you have IoC)
  private BarManager barManager = new BarManager(); // (or inject, if you have IoC)

  ... etc
}

Display more Text in fullcalendar

This code can help you :

$(document).ready(function() { 
    $('#calendar').fullCalendar({ 
        events: 
            [ 
                { 
                    id: 1, 
                    title: 'First Event', 
                    start: ..., 
                    end: ..., 
                    description: 'first description' 
                }, 
                { 
                    id: 2, 
                    title: 'Second Event', 
                    start: ..., 
                    end: ..., 
                    description: 'second description'
                }
            ], 
        eventRender: function(event, element) { 
            element.find('.fc-title').append("<br/>" + event.description); 
        } 
    });
}   

How to add calendar events in Android?

if you have a given Date string with date and time .

for e.g String givenDateString = pojoModel.getDate()/* Format dd-MMM-yyyy hh:mm:ss */

use the following code to add an event with date and time to the calendar

Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss").parse(givenDateString));
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime",cal.getTimeInMillis() + 60 * 60 * 1000);
intent.putExtra("title", " Test Title");
startActivity(intent);

Violation Long running JavaScript task took xx ms

Adding my insights here as this thread was the "go to" stackoverflow question on the topic.

My problem was in a Material-UI app (early stages)

  • placement of custom Theme provider was the cause

when I did some calculations forcing rendering of the page (one component, "display results", depends on what is set in others, "input sections").

Everything was fine until I updated the "state" that forces the "results component" to rerender. The main issue here was that I had a material-ui theme (https://material-ui.com/customization/theming/#a-note-on-performance) in the same renderer (App.js / return.. ) as the "results component", SummaryAppBarPure

Solution was to lift the ThemeProvider one level up (Index.js), and wrapping the App component here, thus not forcing the ThemeProvider to recalculate and draw / layout / reflow.

before

in App.js:

  return (
    <>
      <MyThemeProvider>
      <Container className={classes.appMaxWidth}>

        <SummaryAppBarPure
//...

in index.js

ReactDOM.render(
  <React.StrictMode>
      <App />
//...

after

in App.js:

return (
    <>
      {/* move theme to index. made reflow problem go away */}
      {/* <MyThemeProvider> */}
      <Container className={classes.appMaxWidth}>

        <SummaryAppBarPure
//...

in index.js

ReactDOM.render(
  <React.StrictMode>
    <MyThemeProvider>
      <App />
//...

Insert Data Into Tables Linked by Foreign Key

Not with a regular statement, no.

What you can do is wrap the functionality in a PL/pgsql function (or another language, but PL/pgsql seems to be the most appropriate for this), and then just call that function. That means it'll still be a single statement to your app.

PowerShell script to check the status of a URL

You can try this:

function Get-UrlStatusCode([string] $Url)
{
    try
    {
        (Invoke-WebRequest -Uri $Url -UseBasicParsing -DisableKeepAlive).StatusCode
    }
    catch [Net.WebException]
    {
        [int]$_.Exception.Response.StatusCode
    }
}

$statusCode = Get-UrlStatusCode 'httpstat.us/500'

Is a view faster than a simple query?

The purpose of a view is to use the query over and over again. To that end, SQL Server, Oracle, etc. will typically provide a "cached" or "compiled" version of your view, thus improving its performance. In general, this should perform better than a "simple" query, though if the query is truly very simple, the benefits may be negligible.

Now, if you're doing a complex query, create the view.

How do I check two or more conditions in one <c:if>?

Recommendation:

when you have more than one condition with and and or is better separate with () to avoid verification problems

<c:if test="${(not validID) and (addressIso == 'US' or addressIso == 'BR')}">

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

From MYSQL I solved the problem like this:

SUM(CASE WHEN used = 1 THEN 1 ELSE 0 END) as amount_one,

Hope this helps :D

What's the proper way to install pip, virtualenv, and distribute for Python?

On Ubuntu:

sudo apt-get install python-virtualenv

The package python-pip is a dependency, so it will be installed as well.

how to resolve DTS_E_OLEDBERROR. in ssis

I had this same problem and it seemed to be related to using the same database connection for concurrent tasks. There might be some alternative solutions (maybe better), but I solved it by setting MaxConcurrentExecutables to 1.

Access to file download dialog in Firefox

I didnt unserstood your objective, Do you wanted your test to automatically download file when test is getting executed, if yes, then You need to use custom Firefox profile in your test execution.

In the custom profile, for first time execute test manually and if download dialog comes, the set it Save it to Disk, also check Always perform this action checkbox which will ensure that file automatically get downloaded next time you run your test.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Further to the accepted answer, I ran into issues with code elsewhere on my site requiring jQuery along with the Migrate Plugin.

When the required mapping is added to Global.asax, when loading a page requiring unobtrusive validation (for example a page with the ChangePassword ASP control), the mapped script resource conflicts with the already-loaded jQuery and migrate scripts.

Adding the migrate plugin as a second mapping solves the issue:

// required for UnobtrusiveValidationMode introduced since ASP.NET 4.5
var jQueryScriptDefinition = new ScriptResourceDefinition
{
    Path = "~/Plugins/Common/jquery-3.3.1.min.js", DebugPath = "~/Plugins/Common/jquery-3.3.1.js", LoadSuccessExpression = "typeof(window.jQuery) !== 'undefined'"
};
var jQueryMigrateScriptDefinition = new ScriptResourceDefinition
{
    Path = "~/Plugins/Common/jquery-migrate-3.0.1.min.js", DebugPath = "~/Plugins/Common/jquery-migrate-3.0.1.js", LoadSuccessExpression = "typeof(window.jQuery) !== 'undefined'"
};
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", jQueryScriptDefinition);
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", jQueryMigrateScriptDefinition);

Laravel 5 - How to access image uploaded in storage within View?

If disk 'local' is not working for you then try this :

  1. Change local to public in 'default' => env('FILESYSTEM_DRIVER', 'public'), from project_folder/config/filesystem.php
  2. Clear config cache php artisan config:clear
  3. Then create sym link php artisan storage:link

To get url of uploaded image you can use this Storage::url('iamge_name.jpg');

Tomcat won't stop or restart

The catalina.pid is missing in your case.

This file is located under {your_jira_dir}/work/catalina.pid and it contains the pid of the current instance of jira.

so

ps aux | grep jira
  • find the correct entry
  • Copy the PID of the output and create a file that only contains this PID. - Make sure it can be read and written by the user which runs jira.
  • Try to shutdown jira again.

Oracle SQL: Use sequence in insert with Select Statement

Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like

INSERT INTO HISTORICAL_CAR_STATS (
    HISTORICAL_CAR_STATS_ID, 
    YEAR,
    MONTH, 
    MAKE,
    MODEL,
    REGION,
    AVG_MSRP,
    CNT) 
SELECT MY_SEQ.nextval,
       year,
       month,
       make,
       model,
       region,
       avg_msrp,
       cnt
  FROM (SELECT '2010' year,
               '12' month,
               'ALL' make,
               'ALL' model,
               REGION,
               sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
               sum(cnt) cnt
          FROM HISTORICAL_CAR_STATS
         WHERE YEAR = '2010' 
           AND MONTH = '12'
           AND MAKE != 'ALL' 
         GROUP BY REGION)

How to avoid Number Format Exception in java?

Just catch your exception and do proper exception handling:

if (cost !=null && !"".equals(cost) ){
        try {
           Integer intCost = Integer.parseInt(cost);
           List<Book> books = bookService . findBooksCheaperThan(intCost);  
        } catch (NumberFormatException e) {
           System.out.println("This is not a number");
           System.out.println(e.getMessage());
        }
    }

ActionController::UnknownFormat

This problem happened with me and sovled by just add

 respond_to :html, :json

to ApplicationController file

You can Check Devise issues on Github: https://github.com/plataformatec/devise/issues/2667

Fastest way to update 120 Million records

If the table has an index which you can iterate over I would put update top(10000) statement in a while loop moving over the data. That would keep the transaction log slim and won't have such a huge impact on the disk system. Also, I would recommend to play with maxdop option (setting it closer to 1).

TypeScript getting error TS2304: cannot find name ' require'

Just in addition to cgatian's answer, for TypeScript 1.x

If you are still seeing errors, please specifically provide index.d.ts in your compiler options.

"files": [
    "typings/index.d.ts"
]

Excel VBA Loop on columns

Yes, let's use Select as an example

sample code: Columns("A").select

How to loop through Columns:

Method 1: (You can use index to replace the Excel Address)

For i = 1 to 100
    Columns(i).Select
next i

Method 2: (Using the address)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

EDIT: Strip the Column for OP

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

e.g. you want to get the 27th Column --> AA, you can get it this way

jQuery: Get the cursor position of text in input without browser specific code?

Using the syntax text_element.selectionStart we can get the starting position of the selection of a text in terms of the index of the first character of the selected text in the text_element.value and in case we want to get the same of the last character in the selection we have to use text_element.selectionEnd.

Use it as follows:

<input type=text id=t1 value=abcd>
<button onclick="alert(document.getElementById('t1').selectionStart)">check position</button>

I'm giving you the fiddle_demo

How do I get the name of the rows from the index of a data frame?

this seems to work fine :

dataframe.axes[0].tolist()

How do I run a batch file from my Java Application?

The following is working fine:

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);

How to use Bootstrap 4 in ASP.NET Core

Unfortunately, you're going to have a hard time using NuGet to install Bootstrap (or most other JavaScript/CSS frameworks) on a .NET Core project. If you look at the NuGet install it tells you it is incompatible:

enter image description here

if you must know where local packages dependencies are, they are now in your local profile directory. i.e. %userprofile%\.nuget\packages\bootstrap\4.0.0\content\Scripts.

However, I suggest switching to npm, or bower - like in Saineshwar's answer.

@Scope("prototype") bean scope not creating new bean

Using ApplicationContextAware is tying you to Spring (which may or may not be an issue). I would recommend passing in a LoginActionFactory, which you can ask for a new instance of a LoginAction each time you need one.

Get error message if ModelState.IsValid fails?

publicIHttpActionResultPost(Productproduct) {  
    if (ModelState.IsValid) {  
        //Dosomethingwiththeproduct(notshown).  
        returnOk();  
    } else {  
        returnBadRequest();  
    }  
}

OR

public HttpResponseMessage Post(Product product)
        {
            if (ModelState.IsValid)
            {
                // Do something with the product (not shown).

                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

Removing u in list

The u means the strings are unicode. Translate all the strings to ascii to get rid of it:

a.encode('ascii', 'ignore')

How to restart ADB manually from Android Studio

open cmd and type the following command

netstat -aon|findstr 5037

and press enter.

you will get a reply like this :

  TCP    127.0.0.1:5037         0.0.0.0:0              LISTENING       3372
  TCP    127.0.0.1:5037         127.0.0.1:50126        TIME_WAIT       0
  TCP    127.0.0.1:5037         127.0.0.1:50127        TIME_WAIT       0
  TCP    127.0.0.1:50127        127.0.0.1:5037         TIME_WAIT       0

this shows the pid which is occupying the adb. in this 3372 is the value. it will not be same for anyone. so you need to do this every time you face this problem.

now type this :

taskkill /pid 3372(the pid you get in the previous step) /f

Voila! now adb runs perfectly.

Changing variable names with Python for loops

You could access your class's __dict__ attribute:

for i in range(3)
     self.__dict__['group%d' % i]=self.getGroup(selected, header+i)

But why can't you just use an array named group?

How can I center text (horizontally and vertically) inside a div block?

I always use the following CSS for a container, to center its content horizontally and vertically.

display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;

-webkit-box-align: center;
-moz-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

-webkit-box-pack: center;
-moz-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;

See it in action here: https://jsfiddle.net/yp1gusn7/

PhoneGap Eclipse Issue - eglCodecCommon glUtilsParamSize: unknow param errors

This is an error that you see when your emulator has the "Use host GPU" setting checked. If you uncheck it then the error goes away. Of course, then your emulator is not as responsive anymore.

Android fastboot waiting for devices

The shortest answer is first run the fastboot command (in my ubuntu case i.e. ./fastboot-linux oem unlock) (here i'm using ubuntu 12.04 and rooting nexus4) then power on your device in fastboot mode (in nexus 4 by pressing vol-down-key and power button)

Response.Redirect with POST instead of Get?

In PHP, you can send POST data with cURL. Is there something comparable for .NET?

Yes, HttpWebRequest, see my post below.

Run MySQLDump without Locking Tables

Due to https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_lock-tables :

Some options, such as --opt (which is enabled by default), automatically enable --lock-tables. If you want to override this, use --skip-lock-tables at the end of the option list.

How can I scan barcodes on iOS?

You can find another native iOS solution using Swift 4 and Xcode 9 at below. Native AVFoundation framework used with in this solution.

First part is the a subclass of UIViewController which have related setup and handler functions for AVCaptureSession.

import UIKit
import AVFoundation

class BarCodeScannerViewController: UIViewController {

    let captureSession = AVCaptureSession()
    var videoPreviewLayer: AVCaptureVideoPreviewLayer!
    var initialized = false

    let barCodeTypes = [AVMetadataObject.ObjectType.upce,
                        AVMetadataObject.ObjectType.code39,
                        AVMetadataObject.ObjectType.code39Mod43,
                        AVMetadataObject.ObjectType.code93,
                        AVMetadataObject.ObjectType.code128,
                        AVMetadataObject.ObjectType.ean8,
                        AVMetadataObject.ObjectType.ean13,
                        AVMetadataObject.ObjectType.aztec,
                        AVMetadataObject.ObjectType.pdf417,
                        AVMetadataObject.ObjectType.itf14,
                        AVMetadataObject.ObjectType.dataMatrix,
                        AVMetadataObject.ObjectType.interleaved2of5,
                        AVMetadataObject.ObjectType.qr]

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setupCapture()
        // set observer for UIApplicationWillEnterForeground, so we know when to start the capture session again
        NotificationCenter.default.addObserver(self,
                                           selector: #selector(willEnterForeground),
                                           name: .UIApplicationWillEnterForeground,
                                           object: nil)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // this view is no longer topmost in the app, so we don't need a callback if we return to the app.
        NotificationCenter.default.removeObserver(self,
                                              name: .UIApplicationWillEnterForeground,
                                              object: nil)
    }

    // This is called when we return from another app to the scanner view
    @objc func willEnterForeground() {
        setupCapture()
    }

    func setupCapture() {
        var success = false
        var accessDenied = false
        var accessRequested = false

        let authorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
        if authorizationStatus == .notDetermined {
            // permission dialog not yet presented, request authorization
            accessRequested = true
            AVCaptureDevice.requestAccess(for: .video,
                                      completionHandler: { (granted:Bool) -> Void in
                                          self.setupCapture();
            })
            return
        }
        if authorizationStatus == .restricted || authorizationStatus == .denied {
            accessDenied = true
        }
        if initialized {
            success = true
        } else {
            let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera,
                                                                                        .builtInTelephotoCamera,
                                                                                        .builtInDualCamera],
                                                                          mediaType: .video,
                                                                          position: .unspecified)

            if let captureDevice = deviceDiscoverySession.devices.first {
                do {
                    let videoInput = try AVCaptureDeviceInput(device: captureDevice)
                    captureSession.addInput(videoInput)
                    success = true
                } catch {
                    NSLog("Cannot construct capture device input")
                }
            } else {
                NSLog("Cannot get capture device")
            }
        }
        if success {
            DispatchQueue.global().async {
                self.captureSession.startRunning()
                DispatchQueue.main.async {
                    let captureMetadataOutput = AVCaptureMetadataOutput()
                    self.captureSession.addOutput(captureMetadataOutput)
                    let newSerialQueue = DispatchQueue(label: "barCodeScannerQueue") // in iOS 11 you can use main queue
                    captureMetadataOutput.setMetadataObjectsDelegate(self, queue: newSerialQueue)
                    captureMetadataOutput.metadataObjectTypes = self.barCodeTypes
                    self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
                    self.videoPreviewLayer.videoGravity = .resizeAspectFill
                    self.videoPreviewLayer.frame = self.view.layer.bounds
                    self.view.layer.addSublayer(self.videoPreviewLayer)
                } 
            }
            initialized = true
        } else {
            // Only show a dialog if we have not just asked the user for permission to use the camera.  Asking permission
            // sends its own dialog to th user
            if !accessRequested {
                // Generic message if we cannot figure out why we cannot establish a camera session
                var message = "Cannot access camera to scan bar codes"
                #if (arch(i386) || arch(x86_64)) && (!os(macOS))
                    message = "You are running on the simulator, which does not hae a camera device.  Try this on a real iOS device."
                #endif
                if accessDenied {
                    message = "You have denied this app permission to access to the camera.  Please go to settings and enable camera access permission to be able to scan bar codes"
                }
                let alertPrompt = UIAlertController(title: "Cannot access camera", message: message, preferredStyle: .alert)
                let confirmAction = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                    self.navigationController?.popViewController(animated: true)
                })
                alertPrompt.addAction(confirmAction)
                self.present(alertPrompt, animated: true, completion: nil)
            }
        }
    }

    func handleCapturedOutput(metadataObjects: [AVMetadataObject]) {
        if metadataObjects.count == 0 {
            return
        }

        guard let metadataObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject else {
            return
        }

        if barCodeTypes.contains(metadataObject.type) {
            if let metaDataString = metadataObject.stringValue {
                captureSession.stopRunning()
                displayResult(code: metaDataString)
                return
            }
        }
    }

    func displayResult(code: String) {
        let alertPrompt = UIAlertController(title: "Bar code detected", message: code, preferredStyle: .alert)
        if let url = URL(string: code) {
            let confirmAction = UIAlertAction(title: "Launch URL", style: .default, handler: { (action) -> Void in
                UIApplication.shared.open(url, options: [:], completionHandler: { (result) in
                    if result {
                        NSLog("opened url")
                    } else {
                        let alertPrompt = UIAlertController(title: "Cannot open url", message: nil, preferredStyle: .alert)
                        let confirmAction = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                        })
                        alertPrompt.addAction(confirmAction)
                        self.present(alertPrompt, animated: true, completion: {
                            self.setupCapture()
                        })
                    }
                })        
            })
            alertPrompt.addAction(confirmAction)
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
            self.setupCapture()
        })
        alertPrompt.addAction(cancelAction)
        present(alertPrompt, animated: true, completion: nil)
    }

}

Second part is the extension of our UIViewController subclass for AVCaptureMetadataOutputObjectsDelegate where we catch the captured outputs.

extension BarCodeScannerViewController: AVCaptureMetadataOutputObjectsDelegate {

    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        handleCapturedOutput(metadataObjects: metadataObjects)
    }

}

Update for Swift 4.2

.UIApplicationWillEnterForegroundchanges as UIApplication.willEnterForegroundNotification.

Retrieving subfolders names in S3 bucket from boto3

First of all, there is no real folder concept in S3. You definitely can have a file @ '/folder/subfolder/myfile.txt' and no folder nor subfolder.

To "simulate" a folder in S3, you must create an empty file with a '/' at the end of its name (see Amazon S3 boto - how to create a folder?)

For your problem, you should probably use the method get_all_keys with the 2 parameters : prefix and delimiter

https://github.com/boto/boto/blob/develop/boto/s3/bucket.py#L427

for key in bucket.get_all_keys(prefix='first-level/', delimiter='/'):
    print(key.name)

How to store a byte array in Javascript

You could store the data in an array of strings of some large fixed size. It should be efficient to access any particular character in that array of strings, and to treat that character as a byte.

It would be interesting to see the operations you want to support, perhaps expressed as an interface, to make the question more concrete.

What's a standard way to do a no-op in python?

Use pass for no-op:

if x == 0:
  pass
else:
  print "x not equal 0"

And here's another example:

def f():
  pass

Or:

class c:
  pass

Android Studio drawable folders

If you don't see a drawable folder for the DPI that you need, you can create it yourself. There's nothing magical about it; it's just a folder which needs to have the correct name.

Multiple types were found that match the controller named 'Home'

if you want to resolve it automatically.. you can use the application assambly just add the following code:

 routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { string.Format("{0}.Controllers", BuildManager.GetGlobalAsaxType().BaseType.Assembly.GetName().Name) }
        );

Selenium IDE - Command to wait for 5 seconds

This will wait until your link has appeared, and then you can click it.

Command: waitForElementPresent Target: link=do something Value:

Android marshmallow request permission?

I went through all answers, but doesn't satisfied my exact needed answer, so here is an example that I wrote and perfectly works, even user clicks the Don't ask again checkbox.

  1. Create a method that will be called when you want to ask for runtime permission like readContacts() or you can also have openCamera() as shown below:

    private void readContacts() {
        if (!askContactsPermission()) {
            return;
        } else {
            queryContacts();
        } }
    

Now we need to make askContactsPermission(), you can also name it as askCameraPermission() or whatever permission you are going to ask.

    private boolean askContactsPermission() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
        return true;
    }
    if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
        Snackbar.make(parentLayout, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                .setAction(android.R.string.ok, new View.OnClickListener() {
                    @Override
                    @TargetApi(Build.VERSION_CODES.M)
                    public void onClick(View v) {
                        requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                    }
                }).show();
    } else if (contactPermissionNotGiven) {
        openPermissionSettingDialog();
    } else {
        requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
        contactPermissionNotGiven = true;

    }
    return false;
}

Before writing this function make sure you have defined the below instance variable as shown:

    private View parentLayout;
    private boolean contactPermissionNotGiven;;


/**
 * Id to identity READ_CONTACTS permission request.
 */
private static final int REQUEST_READ_CONTACTS = 0;

Now final step to override the onRequestPermissionsResult method as shown below:

/**
 * Callback received when a permissions request has been completed.
 */
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode == REQUEST_READ_CONTACTS) {
        if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            queryContacts();
        }
    }
}

Here we are done with the RunTime permissions, the addon is the openPermissionSettingDialog() which simply open the Setting screen if user have permanently disable the permission by clicking Don't ask again checkbox. below is the method:

    private void openPermissionSettingDialog() {
    String message = getString(R.string.message_permission_disabled);
    AlertDialog alertDialog =
            new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
                    .setMessage(message)
                    .setPositiveButton(getString(android.R.string.ok),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent();
                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                                    intent.setData(uri);
                                    startActivity(intent);
                                    dialog.cancel();
                                }
                            }).show();
    alertDialog.setCanceledOnTouchOutside(true);
}

What we missed ? 1. Defining the used strings in strings.xml

_x000D_
_x000D_
<string name="permission_rationale">"Contacts permissions are needed to display Contacts."</string>_x000D_
    <string name="message_permission_disabled">You have disabled the permissions permanently,_x000D_
        To enable the permissions please go to Settings -> Permissions and enable the required Permissions,_x000D_
        pressing OK you will be navigated to Settings screen</string>
_x000D_
_x000D_
_x000D_

  1. Initializing the parentLayout variable inside onCreate method

    parentLayout = findViewById(R.id.content);

  2. Defining the required permission in AndroidManifest.xml

_x000D_
_x000D_
<uses-permission android:name="android.permission.READ_CONTACTS" />
_x000D_
_x000D_
_x000D_

  1. The queryContacts method, based on your need or the runtime permission you can call your method before which the permission was needed. in my case I simply use the loader to fetch the contact as shown below:

    private void queryContacts() {
    getLoaderManager().initLoader(0, null, this);}
    

This works great happy coding :)

Setting up SSL on a local xampp/apache server

You can enable SSL on XAMPP by creating self signed certificates and then installing those certificates. Type the below commands to generate and move the certificates to ssl folders.

openssl genrsa -des3 -out server.key 1024

openssl req -new -key server.key -out server.csr

cp server.key server.key.org

openssl rsa -in server.key.org -out server.key

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

cp server.crt /opt/lampp/etc/ssl.crt/domainname.crt

cp server.key /opt/lampp/etc/ssl.key/domainname.key

(Use sudo with each command if you are not the super user)

Now, Check that mod_ssl is enabled in [XAMPP_HOME]/etc/httpd.conf:

LoadModule ssl_module modules/mod_ssl.so

Add a virtual host, in this example "localhost.domainname.com" by editing [XAMPP_HOME]/etc/extra/httpd-ssl.conf as follows:

<virtualhost 127.0.1.4:443>
    ServerName localhost.domainname.com
    ServerAlias localhost.domainname.com *.localhost.domainname.com
    ServerAdmin admin@localhost

    DocumentRoot "/opt/lampp/htdocs/"

    DirectoryIndex index.php

    ErrorLog /opt/lampp/logs/domainname.local.error.log
    CustomLog /opt/lampp/logs/domainname.local.access.log combined

    SSLEngine on
    SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
    SSLCertificateFile /opt/lampp/etc/ssl.crt/domainname.crt
    SSLCertificateKeyFile /opt/lampp/etc/ssl.key/domainname.key

    <directory /opt/lampp/htdocs/>
            Options Indexes FollowSymLinks
            AllowOverride All
            Order allow,deny
            Allow from all
    </directory>
    BrowserMatch ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
</virtualhost>

Add the following entry to /etc/hosts:

127.0.1.4 localhost.domainname.com

Now, try installing the certificate/ try importing certificate to browser. I have checked this and this worked on Ubuntu.

Rails 3.1 and Image Assets

In rails 4 you can now use a css and sass helper image-url:

div.logo {background-image: image-url("logo.png");}

If your background images aren't showing up consider looking at how you're referencing them in your stylesheets.

How to get HttpClient returning status code and response body?

Don't provide the handler to execute.

Get the HttpResponse object, use the handler to get the body and get the status code from it directly

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    final HttpGet httpGet = new HttpGet(GET_URL);

    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        System.out.println("Response body: " + responseBody);
    }
}

For quick single calls, the fluent API is useful:

Response response = Request.Get(uri)
        .connectTimeout(MILLIS_ONE_SECOND)
        .socketTimeout(MILLIS_ONE_SECOND)
        .execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();

For older versions of java or httpcomponents, the code might look different.

Using python PIL to turn a RGB image into a pure black and white image

from PIL import Image 
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('result.png')

yields

enter image description here

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

The difference between substring and slice - is how they work with negative and overlooking lines abroad arguments:

substring (start, end)

Negative arguments are interpreted as zero. Too large values ??are truncated to the length of the string:   alert ( "testme" .substring (-2)); // "testme", -2 becomes 0

Furthermore, if start > end, the arguments are interchanged, i.e. plot line returns between the start and end:

alert ( "testme" .substring (4, -1)); // "test"
// -1 Becomes 0 -> got substring (4, 0)
// 4> 0, so that the arguments are swapped -> substring (0, 4) = "test"

slice

Negative values ??are measured from the end of the line:

alert ( "testme" .slice (-2)); // "me", from the end position 2
alert ( "testme" .slice (1, -1)); // "estm", from the first position to the one at the end.

It is much more convenient than the strange logic substring.

A negative value of the first parameter to substr supported in all browsers except IE8-.

If the choice of one of these three methods, for use in most situations - it will be slice: negative arguments and it maintains and operates most obvious.

Can't connect to local MySQL server through socket homebrew

You'll need to run mysql_install_db - easiest way is if you're in the install directory:

$ cd /usr/local/Cellar/mysql/<version>/ 
$ mysql_install_db

Alternatively, you can feed mysql_install_db a basedir parameter like the following:

$ mysql_install_db --basedir="$(brew --prefix mysql)"

Can you force Visual Studio to always run as an Administrator in Windows 8?

This is a copy of my answer to a similar post on SuperUser:

Option 1 - Set VSLauncher.exe and DevEnv.exe to always run as admin

To have Visual Studio always run as admin when opening any .sln file:

  1. Navigate to C:\Program Files (x86)\Common Files\Microsoft Shared\MSEnv\VSLauncher.exe.
  2. Right-click on VSLauncher.exe and choose Troubleshoot compatibility.
  3. Choose Troubleshoot program.
  4. Check off The program requires additional permissions and hit Next.
  5. Click the Test the program... button to launch VS.
  6. Click Next, then hit Yes, save these settings for this program, and then the close buton.

To have Visual Studio always run as an admin when just opening visual studio directly, do the same thing to the DevEnv.exe file(s). These file are located at:

Visual Studio 2010

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe

Visual Studio 2012

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe

Visual Studio 2013

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe

Visual Studio 2015

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe

Visual Studio 2017

C:\Program Files (x86)\Microsoft Visual Studio\2017\[VS SKU]\Common7\IDE\devenv.exe

Option 2 - Use VSCommands extension for Visual Studio

Install the free VSCommands extension for Visual Studio (it's in the Visual Studio Extensions Gallery) and then configure it to always have Visual Studio start with admin privileges by going to Tools -> VSCommands -> Options -> IDE Enhancements -> General and check off Always start Visual Studio with elevated permissions and click the Save button.

Note: VSCommands is not currently available for VS 2015, but their site says they are working on updating it to support VS 2015.

My Opinion

I prefer Option 2 because:

  • it also allows you to easily turn off this functionality.
  • VSCommands comes with lots of other great features so I always have it installed anyways.
  • it's just easier to do than option 1.

How to get json response using system.net.webrequest in c#?

Some APIs want you to supply the appropriate "Accept" header in the request to get the wanted response type.

For example if an API can return data in XML and JSON and you want the JSON result, you would need to set the HttpWebRequest.Accept property to "application/json".

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";

How do I get the directory from a file's full path?

You can use System.IO.Path.GetDirectoryName(fileName), or turn the path into a FileInfo using FileInfo.Directory.

If you're doing other things with the path, the FileInfo class may have advantages.

In what cases will HTTP_REFERER be empty

BalusC's list is solid. One additional way this field frequently appears empty is when the user is behind a proxy server. This is similar to being behind a firewall but is slightly different so I wanted to mention it for the sake of completeness.

Iterating over a numpy array

I see that no good desciption for using numpy.nditer() is here. So, I am gonna go with one. According to NumPy v1.21 dev0 manual, The iterator object nditer, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

I have to calculate mean_squared_error and I have already calculate y_predicted and I have y_actual from the boston dataset, available with sklearn.

def cal_mse(y_actual, y_predicted):
    """ this function will return mean squared error
       args:
           y_actual (ndarray): np array containing target variable
           y_predicted (ndarray): np array containing predictions from DecisionTreeRegressor
       returns:
           mse (integer)
    """
    sq_error = 0
    for i in np.nditer(np.arange(y_pred.shape[0])):
        sq_error += (y_actual[i] - y_predicted[i])**2
    mse = 1/y_actual.shape[0] * sq_error
    
    return mse

Hope this helps :). for further explaination visit

How do I add a user when I'm using Alpine as a base image?

Alpine uses the command adduser and addgroup for creating users and groups (rather than useradd and usergroup).

FROM alpine:latest

# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Tell docker that all future commands should run as the appuser user
USER appuser

The flags for adduser are:

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        -h DIR          Home directory
        -g GECOS        GECOS field
        -s SHELL        Login shell
        -G GRP          Group
        -S              Create a system user
        -D              Don't assign a password
        -H              Don't create home directory
        -u UID          User id
        -k SKEL         Skeleton directory (/etc/skel)

Add new user official docs

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

I had the same problem, I had to update MVC Future (Microsoft.AspNet.Mvc.Futures)

Install-Package Microsoft.AspNet.Mvc.Futures

pthread function from a class

My favorite way to handle a thread is to encapsulate it inside a C++ object. Here's an example:

class MyThreadClass
{
public:
   MyThreadClass() {/* empty */}
   virtual ~MyThreadClass() {/* empty */}

   /** Returns true if the thread was successfully started, false if there was an error starting the thread */
   bool StartInternalThread()
   {
      return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
   }

   /** Will not return until the internal thread has exited. */
   void WaitForInternalThreadToExit()
   {
      (void) pthread_join(_thread, NULL);
   }

protected:
   /** Implement this method in your subclass with the code you want your thread to run. */
   virtual void InternalThreadEntry() = 0;

private:
   static void * InternalThreadEntryFunc(void * This) {((MyThreadClass *)This)->InternalThreadEntry(); return NULL;}

   pthread_t _thread;
};

To use it, you would just create a subclass of MyThreadClass with the InternalThreadEntry() method implemented to contain your thread's event loop. You'd need to call WaitForInternalThreadToExit() on the thread object before deleting the thread object, of course (and have some mechanism to make sure the thread actually exits, otherwise WaitForInternalThreadToExit() would never return)

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

The active firewall on the server might be causing this. You can try to (temporarily) turn it off and see if it resolves the issue.

If it is indeed caused by the firewall, you should allegedly be able to resolve it by adding an inbound rule for TCP port 1433 set to allowed, but I personally haven't been able to connect this way.

How can I show the table structure in SQL Server query?

For recent versions of SQL Server Management Studio Write the in a query editor and Do "Alt" + "F1"

Declare a Range relative to the Active Cell with VBA

There is an .Offset property on a Range class which allows you to do just what you need

ActiveCell.Offset(numRows, numCols)

follow up on a comment:

Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))

and you can verify by MsgBox newRange.Address

and here's how to assign this range to an array

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

.gitignore file for java eclipse project

put .gitignore in your main catalog

git status (you will see which files you can commit)
git add -A
git commit -m "message"
git push

Mysql where id is in array

Change

$array=array_map('intval', explode(',', $string));

To:

$array= implode(',', array_map('intval', explode(',', $string)));

array_map returns an array, not a string. You need to convert the array to a comma separated string in order to use in the WHERE clause.

Cannot redeclare function php

You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:

if (!function_exists('parseDate')) {
    // ... proceed to declare your function
}

"Permission Denied" trying to run Python on Windows 10

May be you can try opening command prompt with Administrator privileges. (Run As Administrator). Works for me most of the time.

How do I get the object if it exists, or None if it does not exist?

You can do it this way:

go  = Content.objects.filter(name="baby").first()

Now go variable could be either the object you want or None

Ref: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#django.db.models.query.QuerySet.first

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

Assuming the file exists and you just need to update the timestamp.

type test.c > test.c.bkp && type test.c.bkp > test.c && del test.c.bkp

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

SQL: How do I SELECT only the rows with a unique value on certain column?

Assuming your table of data is called ProjectInfo:

SELECT DISTINCT Contract, Activity
    FROM ProjectInfo
    WHERE Contract = (SELECT Contract
                          FROM (SELECT DISTINCT Contract, Activity
                                    FROM ProjectInfo) AS ContractActivities
                          GROUP BY Contract
                          HAVING COUNT(*) = 1);

The innermost query identifies the contracts and the activities. The next level of the query (the middle one) identifies the contracts where there is just one activity. The outermost query then pulls the contract and activity from the ProjectInfo table for the contracts that have a single activity.

Tested using IBM Informix Dynamic Server 11.50 - should work elsewhere too.

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

egyamado's answer was really helpful! You can enhance it for your particular setup with something like this:

import sublime, sublime_plugin
import webbrowser

class OpenBrowserCommand(sublime_plugin.TextCommand):
   def run(self, edit, keyPressed, localHost, pathToFiles):  
      for region in self.view.sel():  
         if not region.empty():  
            # Get the selected text  
            url = self.view.substr(region)  
            # prepend beginning of local host url 
            url = localHost + url  
         else:
            # prepend beginning of local host url 
            url = localHost + self.view.file_name()
            # replace local path to file
            url = url.replace(pathToFiles, "")


         if keyPressed == "1":
            navigator = webbrowser.get("open -a /Applications/Firefox.app %s")
         if keyPressed == "2":
            navigator = webbrowser.get("open -a /Applications/Google\ Chrome.app %s")
         if keyPressed == "3":
            navigator = webbrowser.get("open -a /Applications/Safari.app %s")
         navigator.open_new(url)

And then in your keybindings:

{ "keys": ["alt+1"], "command": "open_browser", "args": {"keyPressed": "1", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}},
{ "keys": ["alt+2"], "command": "open_browser", "args": {"keyPressed": "2", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}},
{ "keys": ["alt+3"], "command": "open_browser", "args": {"keyPressed": "3", "localHost": "http://nbrown.smartdestinations.com", "pathToFiles":"/opt/local/apache2/htdocs"}}

We store sample urls at the top of all our templates, so the first part allows you to highlight that sample URL and launch it in a browser. If no text is highlighted, it will simply use the file name. You can adjust the command calls in the keybindings to your localhost url and the system path to the documents you're working on.

How to get parameter on Angular2 route in Angular way?

As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:

private _entityId: number;

constructor(private _route: ActivatedRoute) {
    // ...
}

ngOnInit() {
    // For a static snapshot of the route...
    this._entityId = this._route.snapshot.paramMap.get('id');

    // For subscribing to the observable paramMap...
    this._route.paramMap.pipe(
        switchMap((params: ParamMap) => this._entityId = params.get('id'))
    );

    // Or as an alternative, with slightly different execution...
    this._route.paramMap.subscribe((params: ParamMap) =>  {
        this._entityId = params.get('id');
    });
}

I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.

Source in Angular Docs

Can I mask an input text in a bat file?

1.Pure batch solution that (ab)uses XCOPY command and its /P /L switches found here (some improvements on this could be found here ):

:: Hidden.cmd
::Tom Lavedas, 02/05/2013, 02/20/2013
::Carlos, 02/22/2013
::https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/f7mb_f99lYI


@Echo Off
:HInput
SetLocal EnableExtensions EnableDelayedExpansion
Set "FILE=%Temp%.\T"
Set "FILE=.\T"
Keys List >"%File%"
Set /P "=Hidden text ending with Ctrl-C?: " <Nul
Echo.
Set "HInput="
:HInput_
For /F "tokens=1* delims=?" %%A In (
 '"Xcopy /P /L "%FILE%" "%FILE%" 2>Nul"'
) Do (
  Set "Text=%%B"
  If Defined Text (
    Set "Char=!Text:~1,1!"
    Set "Intro=1"
    For /F delims^=^ eol^= %%Z in ("!Char!") Do Set "Intro=0"
    Rem If press Intro
    If 1 Equ !Intro! Goto :HInput#
    Set "HInput=!HInput!!Char!"
  )
)
Goto :HInput_
:HInput#
Echo(!HInput!
Goto :Eof 

1.2 Another way based on replace command

@Echo Off
SetLocal EnableExtensions EnableDelayedExpansion

Set /P "=Enter a Password:" < Nul
Call :PasswordInput
Echo(Your input was:!Line!

Goto :Eof

:PasswordInput
::Author: Carlos Montiers Aguilera
::Last updated: 20150401. Created: 20150401.
::Set in variable Line a input password
For /F skip^=1^ delims^=^ eol^= %%# in (
'"Echo(|Replace.exe "%~f0" . /U /W"') Do Set "CR=%%#"
For /F %%# In (
'"Prompt $H &For %%_ In (_) Do Rem"') Do Set "BS=%%#"
Set "Line="
:_PasswordInput_Kbd
Set "CHR=" & For /F skip^=1^ delims^=^ eol^= %%# in (
'Replace.exe "%~f0" . /U /W') Do Set "CHR=%%#"
If !CHR!==!CR! Echo(&Goto :Eof
If !CHR!==!BS! (If Defined Line (Set /P "=!BS! !BS!" <Nul
Set "Line=!Line:~0,-1!"
)
) Else (Set /P "=*" <Nul
If !CHR!==! (Set "Line=!Line!^!"
) Else Set "Line=!Line!!CHR!"
)
Goto :_PasswordInput_Kbd

2.Password submitter that uses a HTA pop-up . This is a hybrit .bat/jscript/mshta file and should be saved as a .bat:

<!-- :
:: PasswordSubmitter.bat
@echo off
for /f "tokens=* delims=" %%p in ('mshta.exe "%~f0"') do (
    set "pass=%%p"
)

echo your password is %pass%
exit /b
-->

<html>
<head><title>Password submitter</title></head>
<body>

    <script language='javascript' >
        window.resizeTo(300,150);
        function entperPressed(e){
                if (e.keyCode == 13) {
                    pipePass();
                }
        }
        function pipePass() {
            var pass=document.getElementById('pass').value;
            var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
            close(fso.Write(pass));

        }
    </script>

    <input type='password' name='pass' size='15' onkeypress="return entperPressed(event)" ></input>
    <hr>
    <button onclick='pipePass()'>Submit</button>

</body>
</html>

3.A self-compiled .net hybrid .Again should be saved as .bat .In difference with other solutions it will create/compile a small .exe file that will be called (if you wish you can delete it). Also requires installed .net framework but that's rather not a problem:

@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal enableDelayedExpansion

for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d  /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
   set "jsc=%%v"
)

if not exist "%~n0.exe" (
    "%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)

for /f "tokens=* delims=" %%p in ('"%~n0.exe"') do (
    set "pass=%%p"
)

echo your password is !pass!

endlocal & exit /b %errorlevel%

*/



import System;



var pwd = "";
var key;

Console.Error.Write("Enter password: ");

        do {
           key = Console.ReadKey(true);

           if ( (key.KeyChar.ToString().charCodeAt(0)) >= 20 && (key.KeyChar.ToString().charCodeAt(0) <= 126) ) {
              pwd=pwd+(key.KeyChar.ToString());
              Console.Error.Write("*");
           }

           if ( key.Key == ConsoleKey.Backspace && pwd.Length > 0 ) {
               pwd=pwd.Remove(pwd.Length-1);
               Console.Error.Write("\b \b");
           }


        } while (key.Key != ConsoleKey.Enter);
        Console.Error.WriteLine();
        Console.WriteLine(pwd);

Correct way to find max in an Array in Swift

Here's a performance test for the solutions posted here. https://github.com/tedgonzalez/MaxElementInCollectionPerformance

This is the fastest for Swift 5

array.max()

Can't find android device using "adb devices" command

Referenced from this link!

THIS IS FOR A MAC ONLY!

Here’s what you need to do to make your phone visible to adb:

  1. Open terminal (Applications/Utilities/Terminal)
  2. cd /System/Library/Extensions/IOUSBFamily.kext/Contents/PlugIns/IOUSBCompositeDriver.kext/Contents
  3. sudo nano Info.plist (or vi, or emacs, or whatever console editor you prefer)
  4. Copy the IOUSBComposite section (from <key> to </dict>)
  5. Paste the section in at line 66 (right after where it appears) so you have 2 copies in the file
  6. Change the bDeviceSubClass value from 0 to 2
  7. Change the key name from IOUSBComposite to GW620

The end result should look something like this:

                    <key>GW620</key>
                    <dict>
                            <key>CFBundleIdentifier</key>
                            <string>com.apple.driver.AppleUSBComposite</string>
                            <key>IOClass</key>
                            <string>IOUSBCompositeDriver</string>
                            <key>IOProviderClass</key>
                            <string>IOUSBDevice</string>
                            <key>bDeviceClass</key>
                            <integer>0</integer>
                            <key>bDeviceSubClass</key>
                            <integer>2</integer>
                    </dict>

  1. sudo diskutil repairpermissions / and let it finish
  2. sudo touch /System/Library/Extensions and wait a few mins for the extension reindexing to finish
  3. adb devices should now see your phone

Note, this is VERY kludgy, and will probably break every time OSX updates itself, but it works. I can finally stop rebooting every time I want to work on the phone! :D