Programs & Examples On #Android configchanges

How to get main window handle from process id?

There's the possibility of a mis-understanding here. The WinForms framework in .Net automatically designates the first window created (e.g., Application.Run(new SomeForm())) as the MainWindow. The win32 API, however, doesn't recognize the idea of a "main window" per process. The message loop is entirely capable of handling as many "main" windows as system and process resources will let you create. So, your process doesn't have a "main window". The best you can do in the general case is use EnumWindows() to get all the non-child windows active on a given process and try to use some heuristics to figure out which one is the one you want. Luckily, most processes are only likely to have a single "main" window running most of the time, so you should get good results in most cases.

Escape quotes in JavaScript

Please find in the below code which escapes the single quotes as part of the entered string using a regular expression. It validates if the user-entered string is comma-separated and at the same time it even escapes any single quote(s) entered as part of the string.

In order to escape single quotes, just enter a backward slash followed by a single quote like: \’ as part of the string. I used jQuery validator for this example, and you can use as per your convenience.

Valid String Examples:

'Hello'

'Hello', 'World'

'Hello','World'

'Hello','World',' '

'It\'s my world', 'Can\'t enjoy this without me.', 'Welcome, Guest'

HTML:

<tr>
    <td>
        <label class="control-label">
            String Field:
        </label>
        <div class="inner-addon right-addon">
            <input type="text" id="stringField"
                   name="stringField"
                   class="form-control"
                   autocomplete="off"
                   data-rule-required="true"
                   data-msg-required="Cannot be blank."
                   data-rule-commaSeparatedText="true"
                   data-msg-commaSeparatedText="Invalid comma separated value(s).">
        </div>
    </td>

JavaScript:

     /**
 *
 * @param {type} param1
 * @param {type} param2
 * @param {type} param3
 */
jQuery.validator.addMethod('commaSeparatedText', function(value, element) {

    if (value.length === 0) {
        return true;
    }
    var expression = new RegExp("^((')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))(((,)|(,\\s))(')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))*$");
    return expression.test(value);
}, 'Invalid comma separated string values.');

jquery variable syntax

This is pure JavaScript.

There is nothing special about $. It is just a character that may be used in variable names.

var $ = 1;
var $$ = 2;
alert($ + $$);

jQuery just assigns it's core function to a variable called $. The code you have assigns this to a local variable called self and the results of calling jQuery with this as an argument to a global variable called $self.

It's ugly, dirty, confusing, but $, self and $self are all different variables that happen to have similar names.

String in function parameter

function("MyString");

is similar to

char *s = "MyString";
function(s);

"MyString" is in both cases a string literal and in both cases the string is unmodifiable.

function("MyString");

passes the address of a string literal to function as an argument.

Junit test case for database insert method with DAO and web service

The design of your classes will make it hard to test them. Using hardcoded connection strings or instantiating collaborators in your methods with new can be considered as test-antipatterns. Have a look at the DependencyInjection pattern. Frameworks like Spring might be of help here.

To have your DAO tested you need to have control over your database connection in your unit tests. So the first thing you would want to do is extract it out of your DAO into a class that you can either mock or point to a specific test database, which you can setup and inspect before and after your tests run.

A technical solution for testing db/DAO code might be dbunit. You can define your test data in a schema-less XML and let dbunit populate it in your test database. But you still have to wire everything up yourself. With Spring however you could use something like spring-test-dbunit which gives you lots of leverage and additional tooling.

As you call yourself a total beginner I suspect this is all very daunting. You should ask yourself if you really need to test your database code. If not you should at least refactor your code, so you can easily mock out all database access. For mocking in general, have a look at Mockito.

How to get a index value from foreach loop in jstl

<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>

above line was giving me an error. So I wrote down in below way which is working fine for me.

<a onclick="getCategoryIndex('<c:out value="${myIndex.index}"/>')" href="#">${categoryName}</a>

Maybe someone else might get same error. Look at this guys!

Is there a simple way to remove multiple spaces in a string?

Similar to the previous solutions, but more specific: replace two or more spaces with one:

>>> import re
>>> s = "The   fox jumped   over    the log."
>>> re.sub('\s{2,}', ' ', s)
'The fox jumped over the log.'

Parse date without timezone javascript

Since it is really a formatting issue when displaying the date (e.g. displays in local time), I like to use the new(ish) Intl.DateTimeFormat object to perform the formatting as it is more explicit and provides more output options:

const dateOptions = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };

const dateFormatter = new Intl.DateTimeFormat('en-US', dateOptions);
const dateAsFormattedString = dateFormatter.format(new Date('2019-06-01T00:00:00.000+00:00'));

console.log(dateAsFormattedString) // "June 1, 2019"

As shown, by setting the timeZone to 'UTC' it will not perform local conversions. As a bonus, it also allows you to create more polished outputs. You can read more about the Intl.DateTimeFormat object from Mozilla - Intl.DateTimeFormat.

Edit:

The same functionality can be achieved without creating a new Intl.DateTimeFormat object. Simply pass the locale and date options directly into the toLocaleDateString() function.

const dateOptions = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };
const myDate = new Date('2019-06-01T00:00:00.000+00:00');
today.toLocaleDateString('en-US', dateOptions); // "June 1, 2019"

How comment a JSP expression?

There are multiple way to comment in a JSP file.

1.  <%-- comment --%>

A JSP comment. Ignored by the JSP engine. Not visible in client machine (Browser source code).

2.  <!-- comment -->

An HTML comment. Ignored by the browser. It is visible in client machine (Browser source code) as a comment.

3. <% my code //my comment %>

Java Single line comment. Ignored by the Compiler. Not visible in client machine (Browser source code).

4.   <% my code /**
         my comment  **/  
       %>

Java Multi line comment. Ignored by the compiler. Not visible in client machine (Browser source code).

But one should use only comment type 1 and 2 because java documentation suggested. these two comment types (1 & 2) are designed for JSP.

How do I format a string using a dictionary in python-3.x?

Most answers formatted only the values of the dict.

If you want to also format the key into the string you can use dict.items():

geopoint = {'latitude':41.123,'longitude':71.091}
print("{} {}".format(*geopoint.items()))

Output:

('latitude', 41.123) ('longitude', 71.091)

If you want to format in an arbitry way, that is, not showing the key-values like tuples:

from functools import reduce
print("{} is {} and {} is {}".format(*reduce((lambda x, y: x + y), [list(item) for item in geopoint.items()])))

Output:

latitude is 41.123 and longitude is 71.091

JavaScript .replace only replaces first Match

From w3schools

The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring

Would be better to use a regex here then:

textTitle.replace(/ /g, '%20');

Fatal error: [] operator not supported for strings

Solved!

$a['index'] = [];
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';
$a['index'][] = 'another value';

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

SmsListenerClass

public class SmsListener extends BroadcastReceiver {

static final String ACTION =
        "android.provider.Telephony.SMS_RECEIVED";

@Override
public void onReceive(Context context, Intent intent) {

    Log.e("RECEIVED", ":-:-" + "SMS_ARRIVED");

    // TODO Auto-generated method stub
    if (intent.getAction().equals(ACTION)) {

        Log.e("RECEIVED", ":-" + "SMS_ARRIVED");

        StringBuilder buf = new StringBuilder();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {

            Object[] pdus = (Object[]) bundle.get("pdus");

            SmsMessage[] messages = new SmsMessage[pdus.length];
            SmsMessage message = null;

            for (int i = 0; i < messages.length; i++) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    String format = bundle.getString("format");
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
                } else {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                }

                message = messages[i];
                buf.append("Received SMS from  ");
                buf.append(message.getDisplayOriginatingAddress());
                buf.append(" - ");
                buf.append(message.getDisplayMessageBody());
            }

            MainActivity inst = MainActivity.instance();
            inst.updateList(message.getDisplayOriginatingAddress(),message.getDisplayMessageBody());

        }

        Log.e("RECEIVED:", ":" + buf.toString());

        Toast.makeText(context, "RECEIVED SMS FROM :" + buf.toString(), Toast.LENGTH_LONG).show();

    }
}

Activity

@Override
public void onStart() {
    super.onStart();
    inst = this;
}

public static MainActivity instance() {
    return inst;
}

public void updateList(final String msg_from, String msg_body) {

    tvMessage.setText(msg_from + " :- " + msg_body);

    sendSMSMessage(msg_from, msg_body);

}

protected void sendSMSMessage(String phoneNo, String message) {

    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, message, null, null);
        Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}

Manifest

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>

<receiver android:name=".SmsListener">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

ASP.NET MVC 3 - redirect to another action

Your method needs to return a ActionResult type:

public ActionResult Index()
{
    //All we want to do is redirect to the class selection page
    return RedirectToAction("SelectClasses", "Registration");
}

How to execute a query in ms-access in VBA code?

Take a look at this tutorial for how to use SQL inside VBA:

http://www.ehow.com/how_7148832_access-vba-query-results.html

For a query that won't return results, use (reference here):

DoCmd.RunSQL

For one that will, use (reference here):

Dim dBase As Database
dBase.OpenRecordset

What are the JavaScript KeyCodes?

Here are some useful links:

The 2nd column is the keyCode and the html column shows how it will displayed. You can test it here.

Conversion from 12 hours time to 24 hours time in java

Using LocalTime in Java 8, LocalTime has many useful methods like getHour() or the getMinute() method,

For example,

LocalTime intime = LocalTime.parse(inputString, DateTimeFormatter.ofPattern("h:m a"));
String outtime = intime.format(DateTimeFormatter.ISO_LOCAL_TIME);

In some cases, First line alone can do the required parsing

RESTful Authentication via Spring

You might consider Digest Access Authentication. Essentially the protocol is as follows:

  1. Request is made from client
  2. Server responds with a unique nonce string
  3. Client supplies a username and password (and some other values) md5 hashed with the nonce; this hash is known as HA1
  4. Server is then able to verify client's identity and serve up the requested materials
  5. Communication with the nonce can continue until the server supplies a new nonce (a counter is used to eliminate replay attacks)

All of this communication is made through headers, which, as jmort253 points out, is generally more secure than communicating sensitive material in the url parameters.

Digest Access Authentication is supported by Spring Security. Notice that, although the docs say that you must have access to your client's plain-text password, you can successfully authenticate if you have the HA1 hash for your client.

Detect encoding and make everything UTF-8

php.net/mb_detect_encoding

echo mb_detect_encoding($str, "auto");

or

echo mb_detect_encoding($str, "UTF-8, ASCII, ISO-8859-1");

i really don't know what the results are, but i'd suggest you just take some of your feeds with different encodings and try if mb_detect_encoding works or not.

update
auto is short for "ASCII,JIS,UTF-8,EUC-JP,SJIS". it returns the detected charset, which you can use to convert the string to utf-8 with iconv.

<?php
function convertToUTF8($str) {
    $enc = mb_detect_encoding($str);

    if ($enc && $enc != 'UTF-8') {
        return iconv($enc, 'UTF-8', $str);
    } else {
        return $str;
    }
}
?>

i haven't tested it, so no guarantee. and maybe there's a simpler way.

Setting value of active workbook in Excel VBA

Try this.

Dim Workbk as workbook
Set Workbk = thisworkbook

Now everything you program will apply just for your containing macro workbook.

Replace Default Null Values Returned From Left Outer Join

That's as easy as

IsNull(FieldName, 0)

Or more completely:

SELECT iar.Description, 
  ISNULL(iai.Quantity,0) as Quantity, 
  ISNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
  iar.Compliance 
FROM InventoryAdjustmentReason iar
LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'

What does '--set-upstream' do?

git branch --set-upstream <remote-branch>

sets the default remote branch for the current local branch.

Any future git pull command (with the current local branch checked-out),
will attempt to bring in commits from the <remote-branch> into the current local branch.


One way to avoid having to explicitly type --set-upstream is to use its shorthand flag -u as follows:

git push -u origin local-branch

This sets the upstream association for any future push/pull attempts automatically.
For more details, checkout this detailed explanation about upstream branches and tracking.


To avoid confusion, recent versions of git deprecate this somewhat ambiguous --set-upstream option in favour of a more verbose --set-upstream-to option with identical syntax and behaviour

git branch --set-upstream-to <origin/remote-branch>

C# Public Enums in Classes

You need to define the enum outside of the class.

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
     // ...

That being said, you may also want to consider using the standard naming guidelines for Enums, which would be CardSuit instead of card_suits, since Pascal Casing is suggested, and the enum is not marked with the FlagsAttribute, suggesting multiple values are appropriate in a single variable.

How to parse the AndroidManifest.xml file inside an .apk package

it can be helpful

public static int vCodeApk(String path) {
    PackageManager pm = G.context.getPackageManager();
    PackageInfo info = pm.getPackageArchiveInfo(path, 0);
    return info.versionCode;
    //        Toast.makeText(this, "VersionCode : " + info.versionCode + ", VersionName : " + info.versionName, Toast.LENGTH_LONG).show();
}

G is my Application class :

public class G extends Application {

What does it mean if a Python object is "subscriptable" or not?

It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.

Space between border and content? / Border distance from content?

Add padding. Padding the element will increase the space between its content and its border. However, note that a box-shadow will begin outside the border, not the content, meaning you can't put space between the shadow and the box. Alternatively you could use :before or :after pseudo selectors on the element to create a slightly bigger box that you place the shadow on, like so: http://jsbin.com/aqemew/edit#source

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

A refined version of Moob's post. Create a hash of the POST, save it as a session cookie, and compare hashes every session.

// Optionally Disable browser caching on "Back"
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Expires: Sun, 1 Jan 2000 12:00:00 GMT' );
header( 'Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT' );

$post_hash = md5( json_encode( $_POST ) );

if( session_start() )
{
    $post_resubmitted = isset( $_SESSION[ 'post_hash' ] ) && $_SESSION[ 'post_hash' ] == $post_hash;
    $_SESSION[ 'post_hash' ] = $post_hash;
    session_write_close();
}
else
{
    $post_resubmitted = false;
}

if ( $post_resubmitted ) {
  // POST was resubmitted
}
else
{
  // POST was submitted normally
}

How to check the first character in a string in Bash or UNIX shell?

Consider the case statement as well which is compatible with most sh-based shells:

case $str in
/*)
    echo 1
    ;;
*)
    echo 0
    ;;
esac

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can do it faster without any imports just by using magics:

%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0

Notice that all env variable are strings, so no need to use ". You can verify that env-variable is set up by running: %env <name_of_var>. Or check all of them with %env.

How do I break a string across more than one line of code in JavaScript?

I tried a number of the above suggestions but got an ILLEGAL character warning in Chrome code inspector. The following worked for me (only tested in Chrome though!)

alert('stuff on line 1\\nstuff on line 2);

comes out like...

stuff on line 1
stuff on line 2

NOTE the double backslash!!...this seems to be important!

Key Presses in Python

If you're platform is Windows, I wouldn't actually recommend Python. Instead, look into Autohotkey. Trust me, I love Python, but in this circumstance a macro program is the ideal tool for the job. Autohotkey's scripting is only decent (in my opinion), but the ease of simulating input will save you countless hours. Autohotkey scripts can be "compiled" as well so you don't need the interpreter to run the script.

Also, if this is for something on the Web, I recommend iMacros. It's a firefox plugin and therefore has a much better integration with websites. For example, you can say "write 1000 'a's in this form" instead of "simulate a mouseclick at (319,400) and then press 'a' 1000 times".

For Linux, I unfortunately have not been able to find a good way to easily create keyboard/mouse macros.

How to add an existing folder with files to SVN?

Let's try.. It is working for me..

svn add * --force

Objective-C - Remove last character from string

The solutions given here actually do not take into account multi-byte Unicode characters ("composed characters"), and could result in invalid Unicode strings.

In fact, the iOS header file which contains the declaration of substringToIndex contains the following comment:

Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters

See how to use rangeOfComposedCharacterSequenceAtIndex: to delete the last character correctly.

What is the role of "Flatten" in Keras?

enter image description here This is how Flatten works converting Matrix to single array.

Does an HTTP Status code of 0 have any meaning?

status 0 appear when an ajax call was cancelled before getting the response by refreshing the page or requesting a URL that is unreachable.

this status is not documented but exist over ajax and makeRequest call's from gadget.io.

Disable html5 video autoplay

just put the autoplay="false" on source tag.. :)

jQuery serialize does not register checkboxes

Using select fields as suggested by Andy is not necessarily the best option for the user experience since it needs two mouse clicks instead of one.

Moreover, a "Select" uses much more space in the UI than a checkbox.

Ash's answer is a simple solution but does not work in the case of array fields.

In my context, I have a variable length form, that holds rows displaying a mix of text and checkbox fields :

<input type="checkbox" value="1" name="thisIsAChkArray[]"/> 
<input type="text" value="" name="thisIsATxtArray[]"/>

For decoding the posted data, the order of the array elements is important. Just appending the non-checked items to a regular Jquery serialize does not keep the order of the row elements.

Here is a proposed solution based on Ash's answer :

(function($) {
  $.fn.serializeWithChkBox = function() {
    // perform a serialize form the non-checkbox fields
    var values = $(this).find('select')
                        .add(  $(this).find('input[type!=checkbox]') )
                        .serialize();
    // add values for checked and unchecked checkboxes fields
    $(this).find('input[type=checkbox]').each(function() {
      var chkVal = $(this).is(':checked') ? $(this).val() : "0";
      values += "&" + $(this).attr('name') + "=" + chkVal;
    });
    return values;
  }
})(jQuery);

How to delete a file from SD card?

Sorry: There is a mistake in my code before because of the site validation.

String myFile = "/Name Folder/File.jpg";  

String myPath = Environment.getExternalStorageDirectory()+myFile;  

File f = new File(myPath);
Boolean deleted = f.delete();

I think is clear... First you must to know your file location. Second,,, Environment.getExternalStorageDirectory() is a method who gets your app directory. Lastly the class File who handle your file...

How can I search sub-folders using glob.glob module?

There's a lot of confusion on this topic. Let me see if I can clarify it (Python 3.7):

  1. glob.glob('*.txt') :matches all files ending in '.txt' in current directory
  2. glob.glob('*/*.txt') :same as 1
  3. glob.glob('**/*.txt') :matches all files ending in '.txt' in the immediate subdirectories only, but not in the current directory
  4. glob.glob('*.txt',recursive=True) :same as 1
  5. glob.glob('*/*.txt',recursive=True) :same as 3
  6. glob.glob('**/*.txt',recursive=True):matches all files ending in '.txt' in the current directory and in all subdirectories

So it's best to always specify recursive=True.

How to put a component inside another component in Angular2?

I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent] from decorator.

import {myDirective} from './myDirective';

How to get column values in one comma separated value

I think it will be easy to you. I am using group_concat which concatenate diffent values with separator as we have defined

select ID,User, GROUP_CONCAT(Distinct Department order  by Department asc 

separator ', ') as Department from Table_Name   group by ID

get original element from ng-click

Not a direct answer to this question but rather to the "issue" of $event.currentTarget apparently be set to null.

This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.

You can check this for more information: Consecutive calls to console.log produce inconsistent results

jQuery get textarea text

Normally, it's the value property

testArea.value

Or is there something I'm missing in what you need?

Cocoa Touch: How To Change UIView's Border Color And Thickness?

I wouldn't suggest overriding the drawRect due to causing a performance hit.

Instead, I would modify the properties of the class like below (in your custom uiview):

  - (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
      self.layer.borderWidth = 2.f;
      self.layer.borderColor = [UIColor redColor].CGColor;
    }
  return self;

I didn't see any glitches when taking above approach - not sure why putting in the initWithFrame stops these ;-)

Arraylist swap elements

Use like this. Here is the online compilation of the code. Take a look http://ideone.com/MJJwtc

public static void swap(List list,
                        int i,
                        int j)

Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)

Parameters: list - The list in which to swap elements. i - the index of one element to be swapped. j - the index of the other element to be swapped.

Read The official Docs of collection

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int%29

import java.util.*;
import java.lang.*;

class Main {
    public static void main(String[] args) throws java.lang.Exception       
    {    
        //create an ArrayList object
        ArrayList words = new ArrayList();

        //Add elements to Arraylist
        words.add("A");
        words.add("B");
        words.add("C");
        words.add("D");
        words.add("E");

        System.out.println("Before swaping, ArrayList contains : " + words);

        /*
      To swap elements of Java ArrayList use,
      static void swap(List list, int firstElement, int secondElement)
      method of Collections class. Where firstElement is the index of first
      element to be swapped and secondElement is the index of the second element
      to be swapped.

      If the specified positions are equal, list remains unchanged.

      Please note that, this method can throw IndexOutOfBoundsException if
      any of the index values is not in range.        */

        Collections.swap(words, 0, words.size() - 1);

        System.out.println("After swaping, ArrayList contains : " + words);    

    }
}

Oneline compilation example http://ideone.com/MJJwtc

SQL Query - how do filter by null or not null

Just like you said

select * from tbl where statusid is null

or

select * from tbl where statusid is not null

If your statusid is not null, then it will be selected just fine when you have an actual value, no need for any "if" logic if that is what you were thinking

select * from tbl where statusid = 123 -- the record(s) returned will not have null statusid

if you want to select where it is null or a value, try

select * from tbl where statusid = 123 or statusid is null

UML class diagram enum

They are simply showed like this:

_______________________
|   <<enumeration>>   |
|    DaysOfTheWeek    |
|_____________________|
| Sunday              |
| Monday              |
| Tuesday             |
| ...                 |
|_____________________|

And then just have an association between that and your class.

Pip Install not installing into correct directory?

You could just change the shebang line. I do this all the time on new systems.

If you want pip to install to a current version of Python installed just update the shebang line to the correct version of pythons path.

For example, to change pip (not pip3) to install to Python 3:

#!/usr/bin/python

To:

#!/usr/bin/python3

Any module you install using pip should install to Python not Python.

Or you could just change the path.

How do I use this JavaScript variable in HTML?

You can create an element with an id and then assign that length value to that element.

_x000D_
_x000D_
var name = prompt("What's your name?");_x000D_
var lengthOfName = name.length_x000D_
document.getElementById('message').innerHTML = lengthOfName;
_x000D_
<p id='message'></p>
_x000D_
_x000D_
_x000D_

What to do with branch after merge

I prefer RENAME rather than DELETE

All my branches are named in the form of

  • Fix/fix-<somedescription> or
  • Ftr/ftr-<somedescription> or
  • etc.

Using Tower as my git front end, it neatly organizes all the Ftr/, Fix/, Test/ etc. into folders.
Once I am done with a branch, I rename them to Done/...-<description>.

That way they are still there (which can be handy to provide history) and I can always go back knowing what it was (feature, fix, test, etc.)

standard size for html newsletter template

Ideally the email content should be about 550px wide to fit within most email clients preview window. If you know for sure your target market can view bigger then you can design bigger. Loads of email examples over on http://www.beautiful-email-newsletters.com/

Capture the Screen into a Bitmap

Try this code

Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics gr = Graphics.FromImage(bmp);
gr.CopyFromScreen(0, 0, 0, 0, bmp.Size);
pictureBox1.Image = bmp;
bmp.Save("img.png",System.Drawing.Imaging.ImageFormat.Png);

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are the same. Numeric is functionally equivalent to decimal.

MSDN: decimal and numeric

Bootstrap 4 card-deck with number of columns based on viewport

Updated 2018

If you want a responsive card-deck, use the visibility utils to force a wrap every X columns on different viewport width(breakpoints)...

Bootstrap 4 responsive card-deck (v 4.1)


Original answer for Bootstrap 4 alpha 2:

You can use the grid col-*-* to get the different widths (instead of card-deck) and then set equal height to the cols using flexbox.

.row > div[class*='col-'] {
  display: flex;
  flex:1 0 auto;
}

http://codeply.com/go/O0KdSG2YX2 (alpha 2)

The problem is that w/o flexbox enabled the card-deck uses table-cell where it becomes very hard to control the width. As of Bootstrap 4 Alpha 6, flexbox is default so the additional CSS is not required for flexbox, and the h-100 class can be used to make the cards full height: http://www.codeply.com/go/gnOzxd4Spk


Related question: Bootstrap 4 - Responsive cards in card-columns

Check whether a string is not null and not empty

Simply, to ignore white space as well:

if (str == null || str.trim().length() == 0) {
    // str is empty
} else {
    // str is not empty
}

Is there a Public FTP server to test upload and download?

Tele2 provides ftp://speedtest.tele2.net , you can log in as anonymous and upload anything to test your upload speed. For download testing they provide fixed size files, you can choose which fits best to your test.

You can connect with username of anonymous and any password (e.g. anonymous ). You can upload files to upload folder. You can't create new folder here. Your file is deleted immediately after successful upload.

Found here: http://speedtest.tele2.net/

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

I was using XSSFWorkbook to read .xls, which resulted in InvalidFormatException. I have to use a more generic Workbook and Sheet to make it work.

This post helped me solved my problem.

Print raw string from variable? (not getting the answers)

Just simply use r'string'. Hope this will help you as I see you haven't got your expected answer yet:

    test = 'C:\\Windows\Users\alexb\'
    rawtest = r'%s' %test

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

I like the Aptana Browser Preview windo for this.

You can get it from their update site: http://download.aptana.org/tools/studio/plugin/update/studio/

After you install the Aptana plugin, open an Aptana project and there should be an option under help to install aptana features. under other you will find a Firefox/XUL browser. There may be a more direct way to install the XUL plugin, but the above procedure works.

Using custom std::set comparator

Yacoby's answer inspires me to write an adaptor for encapsulating the functor boilerplate.

template< class T, bool (*comp)( T const &, T const & ) >
class set_funcomp {
    struct ftor {
        bool operator()( T const &l, T const &r )
            { return comp( l, r ); }
    };
public:
    typedef std::set< T, ftor > t;
};

// usage

bool my_comparison( foo const &l, foo const &r );
set_funcomp< foo, my_comparison >::t boo; // just the way you want it!

Wow, I think that was worth the trouble!

Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class'

  1. Opened package.json
  2. Changed "@angular-devkit/build-angular": "^0.800.0" to "@angular-devkit/build-angular": "^0.10.0" or changed Changing from "@angular-devkit/build-angular": "^0.802.1" to "@angular-devkit/build-angular": "^0.13.9"
  3. Run npm install
  4. Run ng serve

The original version can be diferent, but is necessary change it at 0.10.0 or 0.13.9 version that fix the problem

Where to place JavaScript in an HTML file?

Your javascript links can got either in the head or at the end of the body tag, it is true that performance improves by putting the link at the end of your body tag, but unless performance is an issue, placing them in the head is nicer for people to read and you know where the links are located and can reference them easier.

What is the meaning of <> in mysql query?

<> is equal to != i.e, both are used to represent the NOT EQUAL operation. For instance, email <> '' and email != '' are same.

Limiting double to 3 decimal places

Multiply by 1000 then use Truncate then divide by 1000.

React onClick and preventDefault() link refresh/redirect?

React events are actually Synthetic Events, not Native Events. As it is written here:

Event delegation: React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops.

Try to use Use Event.stopImmediatePropagation:

upvote: (e) ->
  e.stopPropagation();
  e.nativeEvent.stopImmediatePropagation();

Should I initialize variable within constructor or outside constructor

It can depend on what your are initialising, for example you cannot just use field initialisation if a checked exception is involved. For example, the following:

public class Foo {
    FileInputStream fis = new FileInputStream("/tmp"); // throws FileNotFoundException
}

Will cause a compile-time error unless you also include a constructor declaring that checked exception, or extend a superclass which does, e.g.:

public Foo() throws FileNotFoundException {} 

CSS how to make scrollable list

As per your question vertical listing have a scrollbar effect.

CSS / HTML :

_x000D_
_x000D_
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <meta charset="utf-8">_x000D_
        <title>JS Bin</title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <header>header area</header>_x000D_
        <nav>_x000D_
            <ul>_x000D_
                <li>Link 1</li>_x000D_
                <li>Link 2</li>_x000D_
                <li>Link 3</li>_x000D_
                <li>Link 4</li>_x000D_
                <li>Link 5</li>_x000D_
                <li>Link 6</li> _x000D_
                <li>Link 7</li> _x000D_
                <li>Link 8</li>_x000D_
                <li>Link 9</li>_x000D_
                <li>Link 10</li>_x000D_
                <li>Link 11</li>_x000D_
                <li>Link 13</li>_x000D_
                <li>Link 13</li>_x000D_
_x000D_
            </ul>_x000D_
        </nav>_x000D_
        _x000D_
        <footer>footer area</footer>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Selected tab's color in Bottom Navigation View

BottomNavigationView uses colorPrimary from the theme applied for the selected tab and it uses android:textColorSecondary for the inactive tab icon tint.

So you can create a style with the prefered primary color and set it as a theme to your BottomNavigationView in an xml layout file.

styles.xml:

 <style name="BottomNavigationTheme" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">@color/active_tab_color</item>
        <item name="android:textColorSecondary">@color/inactive_tab_color</item>
 </style>

your_layout.xml:

<android.support.design.widget.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?android:attr/windowBackground"
            android:theme="@style/BottomNavigationTheme"
            app:menu="@menu/navigation" />

Print an integer in binary format in Java

System.out.println(Integer.toBinaryString(343));

How to use ClassLoader.getResources() correctly?

Here is code based on bestsss' answer:

    Enumeration<URL> en = getClass().getClassLoader().getResources(
            "META-INF");
    List<String> profiles = new ArrayList<>();
    while (en.hasMoreElements()) {
        URL url = en.nextElement();
        JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
        try (JarFile jar = urlcon.getJarFile();) {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                String entry = entries.nextElement().getName();
                System.out.println(entry);
            }
        }
    }

The result of a query cannot be enumerated more than once

if you getting this type of error so I suggest you used to stored proc data as usual list then binding the other controls because I also get this error so I solved it like this ex:-

repeater.DataSource = data.SPBinsReport().Tolist();
repeater.DataBind();

try like this

What does "|=" mean? (pipe equal operator)

Note: ||= does not exist. (logical or) You can use

y= y || expr; // expr is NOT evaluated if y==true

or

y = expr ? true : y;  // expr is always evaluated.

Update Multiple Rows in Entity Framework from a list of ids

something like below

var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
    var friends= db.Friends.Where(f=>idList.Contains(f.ID)).ToList();
    friends.ForEach(a=>a.msgSentBy='1234');
    db.SaveChanges();
}

UPDATE:

you can update multiple fields as below

friends.ForEach(a =>
                      {
                         a.property1 = value1;
                         a.property2 = value2;
                      });

Using a remote repository with non-standard port

SSH doesn't use the : syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config file and add:

Host git.host.de
  Port 4019

Then specify just git.host.de without a port number.

How to get the browser language using JavaScript

Try this script to get your browser language

_x000D_
_x000D_
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Cheers

Private class declaration

To answer your question:

If we can have inner private class then why can't we have outer private class...?

You can, the distinction is that the inner class is at the "class" access level, whereas the "outer" class is at the "package" access level. From the Oracle Tutorials:

If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

Thus, package-private (declaring no modifier) is the effect you would expect from declaring an "outer" class private, the syntax is just different.

Package signatures do not match the previously installed version

Only 1 emulator or device may be open at a time. Make sure you don't have multiple emulators running.

How can I check if an ip is in a network in Python?

I'm not a fan of using modules when they are not needed. This job only requires simple math, so here is my simple function to do the job:

def ipToInt(ip):
    o = map(int, ip.split('.'))
    res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
    return res

def isIpInSubnet(ip, ipNetwork, maskLength):
    ipInt = ipToInt(ip)#my test ip, in int form

    maskLengthFromRight = 32 - maskLength

    ipNetworkInt = ipToInt(ipNetwork) #convert the ip network into integer form
    binString = "{0:b}".format(ipNetworkInt) #convert that into into binary (string format)

    chopAmount = 0 #find out how much of that int I need to cut off
    for i in range(maskLengthFromRight):
        if i < len(binString):
            chopAmount += int(binString[len(binString)-1-i]) * 2**i

    minVal = ipNetworkInt-chopAmount
    maxVal = minVal+2**maskLengthFromRight -1

    return minVal <= ipInt and ipInt <= maxVal

Then to use it:

>>> print isIpInSubnet('66.151.97.0', '66.151.97.192',24) 
True
>>> print isIpInSubnet('66.151.97.193', '66.151.97.192',29) 
True
>>> print isIpInSubnet('66.151.96.0', '66.151.97.192',24) 
False
>>> print isIpInSubnet('66.151.97.0', '66.151.97.192',29) 

That's it, this is much faster than the solutions above with the included modules.

invalid command code ., despite escaping periods, using sed

Simply add an extension to the -i flag. This basically creates a backup file with the original file.

sed -i.bakup 's/linenumber/number/' ~/.vimrc

sed will execute without the error

How do I define global variables in CoffeeScript?

To me it seems @atomicules has the simplest answer, but I think it can be simplified a little more. You need to put an @ before anything you want to be global, so that it compiles to this.anything and this refers to the global object.

so...

@bawbag = (x, y) ->
    z = (x * y)

bawbag(5, 10)

compiles to...

this.bawbag = function(x, y) {
  var z;
  return z = x * y;
};
bawbag(5, 10);

and works inside and outside of the wrapper given by node.js

(function() {
    this.bawbag = function(x, y) {
      var z;
      return z = x * y;
    };
    console.log(bawbag(5,13)) // works here
}).call(this);

console.log(bawbag(5,11)) // works here

Case insensitive std::string.find()

If you want “real” comparison according to Unicode and locale rules, use ICU’s Collator class.

How can I enable auto complete support in Notepad++?

Open Notepad++ and Settings -> Preferences -> Auto-Completion -> Check the Auto-insert options you want. this link will help alot: http://docs.notepad-plus-plus.org/index.php/Auto_Completion

RESTful API methods; HEAD & OPTIONS

OPTIONS tells you things such as "What methods are allowed for this resource".

HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.

What is the difference between 'java', 'javaw', and 'javaws'?

java.exe is associated with the console, whereas javaw.exe doesn't have any such association. So, when java.exe is run, it automatically opens a command prompt window where output and error streams are shown.

Take screenshots in the iOS simulator

It's just as simple as command+s or File > Save Screen Shot in iOS Simulator. It will appear on your desktop by default.

Passing bash variable to jq

Posting it here as it might help others. In string it might be necessary to pass the quotes to jq. To do the following with jq:

.items[] | select(.name=="string")

in bash you could do

EMAILID=$1
projectID=$(cat file.json | jq -r '.resource[] | select(.username=='\"$EMAILID\"') | .id')

essentially escaping the quotes and passing it on to jq

Spaces in URLs?

Spaces are simply replaced by "%20" like :

http://www.example.com/my%20beautiful%20page

Notification not showing in Oreo

First of all, if you dont know, from Android Oreo i.e API level 26 it's compulsory that notifications are resgitered with a channel.

In that case many tutorials might confuse you because they show different example for notification above oreo and below.

So here is is a common code which runs on both above and below oreo:

String CHANNEL_ID = "MESSAGE";
String CHANNEL_NAME = "MESSAGE";

NotificationManagerCompat manager = NotificationManagerCompat.from(MainActivity.this);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
    NotificationManager.IMPORTANCE_DEFAULT);
    manager.createNotificationChannel(channel);
}

Notification notification = new NotificationCompat.Builder(MainActivity.this,CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_android_black_24dp)
        .setContentTitle(TitleTB.getText().toString())
        .setContentText(MessageTB.getText().toString())
        .build();
manager.notify(getRandomNumber(), notification); // In case you pass a number instead of getRandoNumber() then the new notification will override old one and you wont have more then one notification so to do so u need to pass unique number every time so here is how we can do it by "getRandoNumber()"
private static int getRandomNumber() {
    Date dd= new Date();
    SimpleDateFormat ft =new SimpleDateFormat ("mmssSS");
    String s=ft.format(dd);
    return Integer.parseInt(s);
}

Video Tutorial: YOUTUBE VIDEO

In case you want to download this demo: GitHub Link

Centos/Linux setting logrotate to maximum file size for all logs

As mentioned by Zeeshan, the logrotate options size, minsize, maxsize are triggers for rotation.

To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.

The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.

For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.

Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.

on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate

Or add

*/5 * * * * /etc/cron.daily/logrotate 

To your /etc/crontab file. To run it every 5 minutes.

The size option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.

The man page is a little confusing there. Here's my explanation.

minsize rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.

maxsize will rotate when the log reaches a set size or the appropriate time has passed. e.g. maxsize 50MB + daily. If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.

size will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.

So in the op's case. Specficially 50MB max I'd use something like the following:

/var/log/logpath/*.log {
    maxsize 50M
    hourly
    missingok
    rotate 8
    compress
    notifempty
    nocreate
}

Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.

Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.

Ensure logrotate is run every 30 mins.

*/30 * * * * /etc/cron.daily/logrotate 

convert nan value to zero

You could use np.where to find where you have NaN:

import numpy as np

a = np.array([[   0,   43,   67,    0,   38],
              [ 100,   86,   96,  100,   94],
              [  76,   79,   83,   89,   56],
              [  88,   np.nan,   67,   89,   81],
              [  94,   79,   67,   89,   69],
              [  88,   79,   58,   72,   63],
              [  76,   79,   71,   67,   56],
              [  71,   71,   np.nan,   56,  100]])

b = np.where(np.isnan(a), 0, a)

In [20]: b
Out[20]: 
array([[   0.,   43.,   67.,    0.,   38.],
       [ 100.,   86.,   96.,  100.,   94.],
       [  76.,   79.,   83.,   89.,   56.],
       [  88.,    0.,   67.,   89.,   81.],
       [  94.,   79.,   67.,   89.,   69.],
       [  88.,   79.,   58.,   72.,   63.],
       [  76.,   79.,   71.,   67.,   56.],
       [  71.,   71.,    0.,   56.,  100.]])

gcc: undefined reference to

However, avpicture_get_size is defined.

No, as the header (<libavcodec/avcodec.h>) just declares it.

The definition is in the library itself.

So you might like to add the linker option to link libavcodec when invoking gcc:

-lavcodec

Please also note that libraries need to be specified on the command line after the files needing them:

gcc -I$HOME/ffmpeg/include program.c -lavcodec

Not like this:

gcc -lavcodec -I$HOME/ffmpeg/include program.c

Referring to Wyzard's comment, the complete command might look like this:

gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec

For libraries not stored in the linkers standard location the option -L specifies an additional search path to lookup libraries specified using the -l option, that is libavcodec.x.y.z in this case.


For a detailed reference on GCC's linker option, please read here.

Local and global temporary tables in SQL Server

I didn't see any answers that show users where we can find a Global Temp table. You can view Local and Global temp tables in the same location when navigating within SSMS. Screenshot below taken from this link.

Databases --> System Databases --> tempdb --> Temporary Tables

enter image description here

SQL How to correctly set a date variable value and use it?

If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?

So, you are saying that the following two queries produce correct results:

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))

DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))

Binding arrow keys in JS/jQuery

Example of pure js with going right or left

        window.addEventListener('keydown', function (e) {
            // go to the right
            if (e.keyCode == 39) {

            }
            // go to the left
            if (e.keyCode == 37) {

            }
        });

How to clear a textbox once a button is clicked in WPF?

For example:

XAML:

<Button Content="ok" Click="Button_Click"/>
<TextBlock Name="textBoxName"/>

In code:

 private void Button_Click(object sender, RoutedEventArgs e)
{
textBoxName.Text = "";
}

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

Declare Variable for a Query String

DECLARE @theDate DATETIME
SET @theDate = '2010-01-01'

Then change your query to use this logic:

AND 
(
    tblWO.OrderDate > DATEADD(MILLISECOND, -1, @theDate) 
    AND tblWO.OrderDate < DATEADD(DAY, 1, @theDate)
)

How do I concatenate strings and variables in PowerShell?

If you're concatenating strings to build file paths, use the Join-Path command:

Join-Path C:\temp "MyNewFolder"

It'll automatically add the appropriate trailing / leading slashes for you, which makes things a lot easier.

Adding author name in Eclipse automatically to existing files

To old files I don't know how to do it... I think you will need a script to go thru all files and add the header.

To change the new ones you can do this.

Go to Eclipse menu bar

  1. Window menu.
  2. Preferences
  3. search for Templates
  4. go to Code templates
  5. click on +code
  6. Click on New Java files
  7. Click Edit
  8. add

/**
${user}
*/

And it's done every new File will have your name on it !

What is callback in Android?

You create an interface first, then define a method, which would act as a callback. In this example we would have two classes, one classA and another classB

Interface:

public interface OnCustomEventListener{
  public void onEvent();   //method, which can have parameters
}

the listener itself in classB (we only set the listener in classB)

private OnCustomEventListener mListener; //listener field

//setting the listener
public void setCustomEventListener(OnCustomEventListener eventListener) {
   this.mListener=eventListener;
}

in classA, how we start listening for whatever classB has to tell

classB.setCustomEventListener(new OnCustomEventListener(){
    public void onEvent(){
       //do whatever you want to do when the event is performed.
    }
});  

how do we trigger an event from classB (for example on button pressed)

if(this.mListener!=null){
   this.mListener.onEvent();
}

P.S. Your custom listener may have as many parameters as you want

Source

Paste multiple columns together

I'd construct a new data.frame:

d <- data.frame('a' = 1:3, 'b' = c('a','b','c'), 'c' = c('d', 'e', 'f'), 'd' = c('g', 'h', 'i')) 

cols <- c( 'b' , 'c' , 'd' )

data.frame(a = d[, 'a'], x = do.call(paste, c(d[ , cols], list(sep = '-'))))

Kotlin - How to correctly concatenate a String

Yes, you can concatenate using a + sign. Kotlin has string templates, so it's better to use them like:

var fn = "Hello"
var ln = "World"

"$fn $ln" for concatenation.

You can even use String.plus() method.

How to remove rows with any zero value

Using tidyverse/dplyr, you can also remove rows with any zero value in a subset of variables:

# variables starting with Mac must be non-zero
filter_at(df, vars(starts_with("Mac")), all_vars((.) != 0))

# variables x, y, and z must be non-zero
filter_at(df, vars(x, y, z), all_vars((.) != 0))

# all numeric variables must be non-zero
filter_if(df, is.numeric, all_vars((.) != 0))

OSError: [WinError 193] %1 is not a valid Win32 application

Python installers usually register .py files with the system. If you run the shell explicitly, it works:

import subprocess
subprocess.call(['hello.py', 'htmlfilename.htm'], shell=True)
# --- or ----
subprocess.call('hello.py htmlfilename.htm', shell=True)

You can check your file associations on the command line with

C:\>assoc .py
.py=Python.File

C:\>ftype Python.File
Python.File="C:\Python27\python.exe" "%1" %*

Convert any object to a byte[]

How about something simple like this?

return ((object[])value).Cast<byte>().ToArray(); 

How to redirect to action from JavaScript method?

(This is more of a comment but I can't comment because of the low reputation, somebody might find these useful)

If you're in sth.com/product and you want to redirect to sth.com/product/index use

window.location.href = "index";

If you want to redirect to sth.com/home

window.location.href = "/home";

and if you want you want to redirect to sth.com/home/index

window.location.href = "/home/index";

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

DataTable: How to get item value with row name and column name? (VB)

'Create a class to hold the pair...

        Public Class ColumnValue
            Public ColumnName As String
            Public ColumnValue As New Object
        End Class

    'Build the pair...

        For Each row In [YourDataTable].Rows

              For Each item As DataColumn In row.Table.Columns
                Dim rowValue As New ColumnValue
                rowValue.ColumnName = item.Caption
                rowValue.ColumnValue = row.item(item.Ordinal)
                RowValues.Add(rowValue)
                rowValue = Nothing
              Next

        ' Now you can grab the value by the column name...

        Dim results = (From p In RowValues Where p.ColumnName = "MyColumn" Select  p.ColumnValue).FirstOrDefault    

        Next

Playing a video in VideoView in Android

VideoView videoView =(VideoView) findViewById(R.id.videoViewId);

Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo");

 videoView.setVideoURI(uri);
videoView.start();

Instead of using setVideoPath use setVideoUri. you can get path of your video stored in external storage by using (Environment.getExternalStorageDirectory().getAbsolutePath()+"/yourvideo")and parse it into Uri. If your video is stored in sdcard/MyVideo/video.mp4 replace "/yourvideo" in code by "/MyVideo/video.mp4"

This works fine for me :) `

Why cannot change checkbox color whatever I do?

Late but as a note: after upgrading Chrome to v/81, all check boxes & radio buttons turned blue. So here is a dead simple solution if you ain't okay with blue but with grayscale;

input[type='checkbox'], input[type='radio'] { filter: grayscale(1) }

See more on MDN:
https://developer.mozilla.org/en-US/docs/Web/CSS/filter
https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/grayscale

Import existing Gradle Git project into Eclipse

There is a simplest and quick way to import a Gradle project into Eclipse. Just download the Gradle plugin for Eclipse from here.
https://marketplace.eclipse.org/content/gradle-integration-eclipse-0

And then from import select Gradle and your project would be imported. Then you have to click on Build Model to run it.


EDIT
Above link for Gradle plugin is no more valid. You can use the link as mentioned in the comment by @vikramvi

https://marketplace.eclipse.org/content/buildship-gradle-integration

Finding last occurrence of substring in string, replacing that

Naïve approach:

a = "A long string with a . in the middle ending with ."
fchar = '.'
rchar = '. -'
a[::-1].replace(fchar, rchar[::-1], 1)[::-1]

Out[2]: 'A long string with a . in the middle ending with . -'

Aditya Sihag's answer with a single rfind:

pos = a.rfind('.')
a[:pos] + '. -' + a[pos+1:]

How can I compile my Perl script so it can be executed on systems without perl installed?

Look at PAR (Perl Archiving Toolkit).

PAR is a Cross-Platform Packaging and Deployment tool, dubbed as a cross between Java's JAR and Perl2EXE/PerlApp.

header('HTTP/1.0 404 Not Found'); not doing anything

For PHP >= 5.4 you can use a simpler function like this : http_response_code(404);
PHP Documentation

Is there a destructor for Java?

Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.

There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error).

There was a question that spawned in-depth discussion of finalize recently, so that should provide more depth if required...

How to iterate over array of objects in Handlebars?

You can pass this to each block. See here: http://jsfiddle.net/yR7TZ/1/

{{#each this}}
    <div class="row"></div>
{{/each}}

TypeError: unhashable type: 'numpy.ndarray'

numpy.ndarray can contain any type of element, e.g. int, float, string etc. Check the type an do a conversion if neccessary.

VBA: Selecting range by variables

I recorded a macro with 'Relative References' and this is what I got :

Range("F10").Select
ActiveCell.Offset(0, 3).Range("A1:D11").Select

Heres what I thought : If the range selection is in quotes, VBA really wants a STRING and interprets the cells out of it so tried the following:

Dim MyRange as String
MyRange = "A1:D11"
Range(MyRange).Select

And it worked :) ie.. just create a string using your variables, make sure to dimension it as a STRING variables and Excel will read right off of it ;)

Following tested and found working :

Sub Macro04()

Dim Copyrange As String

Startrow = 1
Lastrow = 11
Let Copyrange = "A" & Startrow & ":" & "D" & Lastrow
Range(Copyrange).Select
End Sub

"The public type <<classname>> must be defined in its own file" error in Eclipse

Save this class in the file StaticDemo.java. Also you cant have more than one public classes in one file.

What is a stack trace, and how can I use it to debug my application errors?

Just to add to the other examples, there are inner(nested) classes that appear with the $ sign. For example:

public class Test {

    private static void privateMethod() {
        throw new RuntimeException();
    }

    public static void main(String[] args) throws Exception {
        Runnable runnable = new Runnable() {
            @Override public void run() {
                privateMethod();
            }
        };
        runnable.run();
    }
}

Will result in this stack trace:

Exception in thread "main" java.lang.RuntimeException
        at Test.privateMethod(Test.java:4)
        at Test.access$000(Test.java:1)
        at Test$1.run(Test.java:10)
        at Test.main(Test.java:13)

How to check if a file exists in Ansible?

**

How to check if a file exists in Ansible using when condition

**

Below is the ansible play i used to remove the file when the file exists in the OS end.

 - name: find out /etc/init.d/splunk file exists or not'
      stat:
        path: /etc/init.d/splunk
      register: splunkresult
      tags:
        - always

    - name: 'Remove splunk from init.d file if splunk already running'
      file:
        path: /etc/init.d/splunk
        state: absent
      when: splunkresult.stat.exists == true
      ignore_errors: yes
      tags:
        - always

I have used play condition as like below

when: splunkresult.stat.exists == true --> Remove the file

you can give true/false based on your requirement

when: splunkresult.stat.exists == false
when: splunkresult.stat.exists == true

How to assert greater than using JUnit Assert?

As I recognize, at the moment, in JUnit, the syntax is like this:

AssertTrue(Long.parseLong(previousTokenValues[1]) > Long.parseLong(currentTokenValues[1]), "your fail message ");

Means that, the condition is in front of the message.

How to change the pop-up position of the jQuery DatePicker control

Here is my variation of Datepicker calendar aligning.

I think that it's pretty nice, because you can control positioning via jQuery UI Position util.

One restriction: jquery.ui.position.js required.

Code:

$('input[name=date]').datepicker({
    beforeShow: function(input, inst) {
        // Handle calendar position before showing it.
        // It's not supported by Datepicker itself (for now) so we need to use its internal variables.
        var calendar = inst.dpDiv;

        // Dirty hack, but we can't do anything without it (for now, in jQuery UI 1.8.20)
        setTimeout(function() {
            calendar.position({
                my: 'right top',
                at: 'right bottom',
                collision: 'none',
                of: input
            });
        }, 1);
    }
})

Centering text in a table in Twitter Bootstrap

The .table td 's text-align is set to left, rather than center.

Adding this should center all your tds:

.table td {
   text-align: center;   
}

_x000D_
_x000D_
@import url('https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css');_x000D_
table,_x000D_
thead,_x000D_
tr,_x000D_
tbody,_x000D_
th,_x000D_
td {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.table td {_x000D_
  text-align: center;_x000D_
}
_x000D_
<table class="table">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>1</th>_x000D_
      <th>1</th>_x000D_
      <th>1</th>_x000D_
      <th>1</th>_x000D_
      <th>2</th>_x000D_
      <th>2</th>_x000D_
      <th>2</th>_x000D_
      <th>2</th>_x000D_
      <th>3</th>_x000D_
      <th>3</th>_x000D_
      <th>3</th>_x000D_
      <th>3</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td colspan="4">Lorem</td>_x000D_
      <td colspan="4">ipsum</td>_x000D_
      <td colspan="4">dolor</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Updated JSFIDDLE

Delete last commit in bitbucket

As others have said, usually you want to use hg backout or git revert. However, sometimes you really want to get rid of a commit.

First, you'll want to go to your repository's settings. Click on the Strip commits link.

Strip commits link in bitbucket settings

Enter the changeset ID for the changeset you want to destroy, and click Preview strip. That will let you see what kind of damage you're about to do before you do it. Then just click Confirm and your commit is no longer history. Make sure you tell all your collaborators what you've done, so they don't accidentally push the offending commit back.

Get the current file name in gulp.src()

If you want to use @OverZealous' answer (https://stackoverflow.com/a/21806974/1019307) in Typescript, you need to import instead of require:

import * as debug from 'gulp-debug';

...

    return gulp.src('./examples/*.html')
        .pipe(debug({title: 'example src:'}))
        .pipe(gulp.dest('./build'));

(I also added a title).

Any reason not to use '+' to concatenate two strings?

There is nothing wrong in concatenating two strings with +. Indeed it's easier to read than ''.join([a, b]).

You are right though that concatenating more than 2 strings with + is an O(n^2) operation (compared to O(n) for join) and thus becomes inefficient. However this has not to do with using a loop. Even a + b + c + ... is O(n^2), the reason being that each concatenation produces a new string.

CPython2.4 and above try to mitigate that, but it's still advisable to use join when concatenating more than 2 strings.

What is the difference between Cygwin and MinGW?

Cygwin is an attempt to create a complete UNIX/POSIX environment on Windows. To do this it uses various DLLs. While these DLLs are covered by GPLv3+, their license contains an exception that does not force a derived work to be covered by the GPLv3+. MinGW is a C/C++ compiler suite which allows you to create Windows executables without dependency on such DLLs - you only need the normal MSVC runtimes, which are part of any normal Microsoft Windows installation.

You can also get a small UNIX/POSIX like environment, compiled with MinGW called MSYS. It doesn't have anywhere near all the features of Cygwin, but is ideal for programmers wanting to use MinGW.

React Checkbox not sending onChange

In material ui, state of checkbox can be fetched as

this.refs.complete.state.switched

How to calculate DATE Difference in PostgreSQL?

Your calculation is correct for DATE types, but if your values are timestamps, you should probably use EXTRACT (or DATE_PART) to be sure to get only the difference in full days;

EXTRACT(DAY FROM MAX(joindate)-MIN(joindate)) AS DateDifference

An SQLfiddle to test with. Note the timestamp difference being 1 second less than 2 full days.

List<Object> and List<?>

To answer your second question, yes, you can cast the List<?> as a List<Object> or a List<T> of any type, since the ? (Wildcard) parameter indicates that the list contains a homogenous collection of an any Object. However, there's no way to know at compile what the type is since it's part of the exported API only - meaning you can't see what's being inserted into the List<?>.

Here's how you would make the cast:

List<?> wildcardList = methodThatReturnsWildcardList();
// generates Unchecked cast compiler warning
List<Object> objectReference = (List<Object>)wildcardList;

In this case you can ignore the warning because in order for an object to be used in a generic class it must be a subtype of Object. Let's pretend that we're trying to cast this as a List<Integer> when it actually contains a collection of Strings.

// this code will compile safely
List<?> wildcardList = methodThatReturnsWildcardList();
List<Integer> integerReference = (List<Integer>)wildcardList;

// this line will throw an invalid cast exception for any type other than Integer
Integer myInteger = integerRefence.get(0);

Remember: generic types are erased at runtime. You won't know what the collection contains, but you can get an element and call .getClass() on it to determine its type.

Class objectClass = wildcardList.get(0).getClass();

Find the version of an installed npm package

This is simple question, and should have a simpler answer than what I see above.

To see the installed npm packages with their version, the command is npm ls --depth=0, which, by default, displays what is installed locally. To see the globally installed packages, add the -global argument: npm ls --depth=0 -global.

--depth=0 returns a list of installed packages without their dependencies, which is what you're wanting to do most of the time.

ls is the name of the command, and list is an alias for ls.

Convert hex color value ( #ffffff ) to integer value

Answer is really simple guys, in android if you want to convert hex color in to int, just use android Color class, example shown as below

this is for light gray color

Color.parseColor("#a8a8a8");

Thats it and you will get your result.

Delayed function calls

It sounds like the control of the creation of both these objects and their interdependence needs to controlled externally, rather than between the classes themselves.

Select Specific Columns from Spark DataFrame

Problem was to select columns of on dataframe after joining with other dataframe.

I tried below and select the columns of salaryDf from the joined dataframe.

Hope this will help

        val empDf=spark.read.option("header","true").csv("/data/tech.txt")

        val salaryDf=spark.read.option("header","true").csv("/data/salary.txt")

        val joinData= empDf.join(salaryDf,empDf.col("first") === salaryDf.col("first") and  empDf.col("last") === salaryDf.col("last"))

      //**below will select the colums of salaryDf only**

     val finalDF=joinData.select(salaryDf.columns map  salaryDf.col:_*)

//same way we can select the columns of empDf
joinData.select(empDf.columns map  empDf.col:_*)

How to read request body in an asp.net core webapi controller?

To those who simply want to get the content (request body) from the request:

Use the [FromBody] attribute in your controller method parameter.

[Route("api/mytest")]
[ApiController]
public class MyTestController : Controller
{
    [HttpPost]
    [Route("content")]
    public async Task<string> ReceiveContent([FromBody] string content)
    {
        // Do work with content
    }
}

As doc says: this attribute specifies that a parameter or property should be bound using the request body.

How to scroll page in flutter

Use LayoutBuilder and Get the output you want

Wrap the SingleChildScrollView with LayoutBuilder and implement the Builder function.

we can use a LayoutBuilder to get the box contains or the amount of space available.

LayoutBuilder(
    builder: (BuildContext context, BoxConstraints constraints){
      return SingleChildScrollView(
        child: Stack(
          children: <Widget>[
            Container(
              height: constraints.maxHeight,
            ),
            topTitle(context),
            middleView(context),
            bottomView(context),
          ],
        ),
      );
    }
)

Why are arrays of references illegal?

Consider an array of pointers. A pointer is really an address; so when you initialize the array, you are analogously telling the computer, "allocate this block of memory to hold these X numbers (which are addresses of other items)." Then if you change one of the pointers, you are just changing what it points to; it is still a numerical address which is itself sitting in the same spot.

A reference is analogous to an alias. If you were to declare an array of references, you would basically be telling the computer, "allocate this amorphous blob of memory consisting of all these different items scattered around."

How to access the elements of a 2D array?

If you have this :

a = [[1, 1], [2, 1],[3, 1]]

You can easily access this by using :

print(a[0][2])
a[0][1] = 7
print(a)

'Connect-MsolService' is not recognized as the name of a cmdlet

I had to do this in that order:

Install-Module MSOnline
Install-Module AzureAD
Import-Module AzureAD

Merging two images with PHP

You can try my function for merging images horizontally or vertically without changing image ratio. just copy paste will work.

function merge($filename_x, $filename_y, $filename_result, $mergeType = 0) {

    //$mergeType 0 for horizandal merge 1 for vertical merge

 // Get dimensions for specified images
 list($width_x, $height_x) = getimagesize($filename_x);
 list($width_y, $height_y) = getimagesize($filename_y);


$lowerFileName = strtolower($filename_x); 
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
    $image_x = imagecreatefromjpeg($filename_x);    
}else if(substr_count($lowerFileName, '.png')>0){
    $image_x = imagecreatefrompng($filename_x); 
}else if(substr_count($lowerFileName, '.gif')>0){
    $image_x = imagecreatefromgif($filename_x); 
}


$lowerFileName = strtolower($filename_y); 
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
    $image_y = imagecreatefromjpeg($filename_y);    
}else if(substr_count($lowerFileName, '.png')>0){
    $image_y = imagecreatefrompng($filename_y); 
}else if(substr_count($lowerFileName, '.gif')>0){
    $image_y = imagecreatefromgif($filename_y); 
}


if($mergeType==0){
    //for horizandal merge
     if($height_y<$height_x){
        $new_height = $height_y;

        $new_x_height = $new_height;
        $precentageReduced = ($height_x - $new_height)/($height_x/100);
        $new_x_width = ceil($width_x - (($width_x/100) * $precentageReduced));

         $tmp = imagecreatetruecolor($new_x_width, $new_x_height);
        imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
        $image_x = $tmp;

        $height_x = $new_x_height;
        $width_x = $new_x_width;

     }else{
        $new_height = $height_x;

        $new_y_height = $new_height;
        $precentageReduced = ($height_y - $new_height)/($height_y/100);
        $new_y_width = ceil($width_y - (($width_y/100) * $precentageReduced));

         $tmp = imagecreatetruecolor($new_y_width, $new_y_height);
        imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
        $image_y = $tmp;

        $height_y = $new_y_height;
        $width_y = $new_y_width;

     }

     $new_width = $width_x + $width_y;

     $image = imagecreatetruecolor($new_width, $new_height);

    imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
    imagecopy($image, $image_y, $width_x, 0, 0, 0, $width_y, $height_y);

}else{


    //for verical merge
    if($width_y<$width_x){
        $new_width = $width_y;

        $new_x_width = $new_width;
        $precentageReduced = ($width_x - $new_width)/($width_x/100);
        $new_x_height = ceil($height_x - (($height_x/100) * $precentageReduced));

        $tmp = imagecreatetruecolor($new_x_width, $new_x_height);
        imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
        $image_x = $tmp;

        $width_x = $new_x_width;
        $height_x = $new_x_height;

     }else{
        $new_width = $width_x;

        $new_y_width = $new_width;
        $precentageReduced = ($width_y - $new_width)/($width_y/100);
        $new_y_height = ceil($height_y - (($height_y/100) * $precentageReduced));

         $tmp = imagecreatetruecolor($new_y_width, $new_y_height);
        imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
        $image_y = $tmp;

        $width_y = $new_y_width;
        $height_y = $new_y_height;

     }

     $new_height = $height_x + $height_y;

     $image = imagecreatetruecolor($new_width, $new_height);

    imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
    imagecopy($image, $image_y, 0, $height_x, 0, 0, $width_y, $height_y);

}





$lowerFileName = strtolower($filename_result); 
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
    imagejpeg($image, $filename_result);
}else if(substr_count($lowerFileName, '.png')>0){
    imagepng($image, $filename_result);
}else if(substr_count($lowerFileName, '.gif')>0){
    imagegif($image, $filename_result); 
}


 // Clean up
 imagedestroy($image);
 imagedestroy($image_x);
 imagedestroy($image_y);

}


merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged_har.jpg',0); //merge horizontally
merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged.jpg',1); //merge vertically

How do I toggle an ng-show in AngularJS based on a boolean?

You just need to toggle the value of "isReplyFormOpen" on ng-click event

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
 <div ng-show="isReplyFormOpen" id="replyForm">
   </div>

How do you set a JavaScript onclick event to a class with css

It can't be done via CSS as CSS only changes the presentation (e.g. only Javascript can make the alert popup). I'd strongly recommend you check out a Javascript library called jQuery as it makes doing something like this trivial:

$(document).ready(function(){
  $("a").click(function(){
    alert("hohoho");
  });
});

c# search string in txt file

If you whant only one first string, you can use simple for-loop.

var lines = File.ReadAllLines(pathToTextFile);

var firstFound = false;
for(int index = 0; index < lines.Count; index++)
{
   if(!firstFound && lines[index].Contains("CustomerEN"))
   {
      firstFound = true;
   }
   if(firstFound && lines[index].Contains("CustomerCh"))
   {
      //do, what you want, and exit the loop
      // return lines[index];
   }
}

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

How to get parameters from a URL string?

In Laravel, I'm use:

private function getValueFromString(string $string, string $key)
{
    parse_str(parse_url($string, PHP_URL_QUERY), $result);

    return isset($result[$key]) ? $result[$key] : null;
}

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

Convert python datetime to timestamp in milliseconds

For those who searches for an answer without parsing and loosing milliseconds, given dt_obj is a datetime:

python3 only, elegant

int(dt_obj.timestamp() * 1000)

both python2 and python3 compatible:

import time

int(time.mktime(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000)

How do I improve ASP.NET MVC application performance?

Use the latest version of Task Parallel Library (TPL), according to .Net version. Have to choose the correct modules of TPL for different purposes.

How can I specify the schema to run an sql file against in the Postgresql command line

Main Example

The example below will run myfile.sql on database mydatabase using schema myschema.

psql "dbname=mydatabase options=--search_path=myschema" -a -f myfile.sql

The way this works is the first argument to the psql command is the dbname argument. The docs mention a connection string can be provided.

If this parameter contains an = sign or starts with a valid URI prefix (postgresql:// or postgres://), it is treated as a conninfo string

The dbname keyword specifies the database to connect to and the options keyword lets you specify command-line options to send to the server at connection startup. Those options are detailed in the server configuration chapter. The option we are using to select the schema is search_path.

Another Example

The example below will connect to host myhost on database mydatabase using schema myschema. The = special character must be url escaped with the escape sequence %3D.

psql postgres://myuser@myhost?options=--search_path%3Dmyschema

Creating a JSON array in C#

Also , with Anonymous types ( I prefer not to do this) -- this is just another approach.

void Main()
{
    var x = new
    {
        items = new[]
        {
            new
            {
                name = "command", index = "X", optional = "0"
            },
            new
            {
                name = "command", index = "X", optional = "0"
            }
        }
    };
    JavaScriptSerializer js = new JavaScriptSerializer(); //system.web.extension assembly....
    Console.WriteLine(js.Serialize(x));
}

result :

{"items":[{"name":"command","index":"X","optional":"0"},{"name":"command","index":"X","optional":"0"}]}

"unrecognized import path" with go get

The issues are relating to an invalid GOROOT.

I think you installed Go in /usr/local/go.
So change your GOROOT path to the value of /usr/local/go/bin.

It seems that you meant to have your workspace (GOPATH) located at /home/me/go.

This might fix your problem.
Add this to the bottom of your bash profile, located here => $HOME/.profile

export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin

Make sure to remove the old references of GOROOT.

Then try installing web.go again.

If that doesn't work, then have Ubuntu install Go for you.

sudo apt-get install golang

Video tutorial: http://www.youtube.com/watch?v=2PATwIfO5ag

Why do I get "MismatchSenderId" from GCM server side?

If use for native Android, check your AndroidMaifest.xml file:

<meta-data
        android:name="onesignal_google_project_number"
        android:value="str:1234567890" />  
  <!--             its is correct. -->

instead

   <meta-data
        android:name="onesignal_google_project_number"
        android:value="@string/google_project_number" />

Hope it helps!!

Java time-based map/cache with expiring keys

If anybody needs a simple thing, following is a simple key-expiring set. It might be converted to a map easily.

public class CacheSet<K> {
    public static final int TIME_OUT = 86400 * 1000;

    LinkedHashMap<K, Hit> linkedHashMap = new LinkedHashMap<K, Hit>() {
        @Override
        protected boolean removeEldestEntry(Map.Entry<K, Hit> eldest) {
            final long time = System.currentTimeMillis();
            if( time - eldest.getValue().time > TIME_OUT) {
                Iterator<Hit> i = values().iterator();

                i.next();
                do {
                    i.remove();
                } while( i.hasNext() && time - i.next().time > TIME_OUT );
            }
            return false;
        }
    };


    public boolean putIfNotExists(K key) {
        Hit value = linkedHashMap.get(key);
        if( value != null ) {
            return false;
        }

        linkedHashMap.put(key, new Hit());
        return true;
    }

    private static class Hit {
        final long time;


        Hit() {
            this.time = System.currentTimeMillis();
        }
    }
}

In Bootstrap 3,How to change the distance between rows in vertical?

If it was me I would introduce new CSS class and use along with unmodified bootstrap row class.

HTML

<div class="row extra-bottom-padding" id="a">
   <img>...</img>
<div>
<div class="row" id="b">
   <button>..</button>
<div>

CSS

.row.extra-bottom-padding{
   margin-bottom: 20px;
}

Why is Spring's ApplicationContext.getBean considered bad?

Others have pointed to the general problem (and are valid answers), but I'll just offer one additional comment: it's not that you should NEVER do it, but rather that do it as little as possible.

Usually this means that it is done exactly once: during bootstrapping. And then it's just to access the "root" bean, through which other dependencies can be resolved. This can be reusable code, like base servlet (if developing web apps).

How to resolve the C:\fakepath?

seems you can't find the full path in you localhost by js, but you can hide the fakepath to just show the file name. Use jQuery to get the file input's selected filename without the path

How to get a table cell value using jQuery?

A working example: http://jsfiddle.net/0sgLbynd/

<table>
<tr>
    <td>0</td>
    <td class="ms-vb2">1</td>
    <td class="ms-vb2">2</td>
    <td class="ms-vb2">3</td>
    <td class="ms-vb2">4</td>
    <td class="ms-vb2">5</td>
    <td class="ms-vb2">6</td>
</tr>
</table>


$(document).ready(function () {
//alert("sss");
$("td").each(function () {
    //alert($(this).html());
    $(this).html("aaaaaaa");
});
});

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

My problem was my Target profile didn't have the proper code signing option selected:

Target Menu -> Code Signing -> Code Signing Identity

Choose "iPhone developer" then select the provisional profile you created.

How can I remove Nan from list Python/NumPy

I noticed that Pandas for example will return 'nan' for blank values. Since it's not a string you need to convert it to one in order to match it. For example:

ulist = df.column1.unique() #create a list from a column with Pandas which 
for loc in ulist:
    loc = str(loc)   #here 'nan' is converted to a string to compare with if
    if loc != 'nan':
        print(loc)

Configure apache to listen on port other than 80

Open httpd.conf file in your text editor. Find this line:

Listen 80

and change it

Listen 8079

After change, save it and restart apache.

How do you read scanf until EOF in C?

You need to check the return value against EOF, not against 1.

Note that in your example, you also used two different variable names, words and word, only declared words, and didn't declare its length, which should be 16 to fit the 15 characters read in plus a NUL character.

Apache and Node.js on the Same Server

I am assuming that you are making a web app because you refer to Apache and Node. Quick answer - Is it possible - YES. Is it recommended - NO. Node bundles it's own webserver and most websites run on port 80. I am also assuming that there is currently no Apache plugin which is supported by Nodejs and I am not sure if creating a virtual host is the best way to implement this. These are the questions that should be answered by developers who maintain Nodejs like the good folks at Joyent.

Instead of ports, it would be better to evaluate Node's tech stack which is completely different from most others and which is why I love it but it also involves a few compromises that you should be aware of in advance.

Your example looks similar to a CMS or a sharing web app and there are hundreds of out of the box apps available that will run just fine on Apache. Even if you do not like any readymade solution, you could write a webapp in PHP / Java / Python or mix n match it with a couple of ready made apps and they are all designed and supported to run behind a single instance of Apache.

It's time to pause and think about what I just said.

Now you are ready to decide on which techstack you are going to use. If your website will never use any out of the thousands of ready made apps that require Apache, then go for Node otherwise you must first eliminate the assumptions that I have stated earlier.

In the end, your choice of techstack is way more important than any individual component.

I completely agree with @Straseus that it is relatively trivial to use node.js file system api for handling uploads and downloads but think more about what you want from your website in the long run and then choose your techstack.

Learning Node's framework is easier than learning other frameworks but it is not a panacea. With a slightly more effort (which may be a worthwhile endeavor in itself), you can learn any other framework too. We all learn from each other and you will be more productive if you are working as a small team than if you are working alone and your backend technical skills will also develop faster. Therefore, do not discount the skills of other members of your team so cheaply.

This post is about a year old and chances are that you have already decided but I hope that my rant will help the next person who is going through a similar decision.

Thanks for reading.

Using Font Awesome icon for bullet points, with a single list item element

My solution using standard <ul> and <i> inside <li>

  <ul>
    <li><i class="fab fa-cc-paypal"></i> <div>Paypal</div></li>
    <li><i class="fab fa-cc-apple-pay"></i> <div>Apple Pay</div></li>
    <li><i class="fab fa-cc-stripe"></i> <div>Stripe</div></li>
    <li><i class="fab fa-cc-visa"></i> <div>VISA</div></li>
  </ul>

enter image description here

DEMO HERE

Moving x-axis to the top of a plot in matplotlib

You want set_ticks_position rather than set_label_position:

ax.xaxis.set_ticks_position('top') # the rest is the same

This gives me:

enter image description here

this in equals method

You are comparing two objects for equality. The snippet:

if (obj == this) {     return true; } 

is a quick test that can be read

"If the object I'm comparing myself to is me, return true"

. You usually see this happen in equals methods so they can exit early and avoid other costly comparisons.

How to call a Web Service Method?

In visual studio, use the "Add Web Reference" feature and then enter in the URL of your web service.

By adding a reference to the DLL, you not referencing it as a web service, but simply as an assembly.

When you add a web reference it create a proxy class in your project that has the same or similar methods/arguments as your web service. That proxy class communicates with your web service via SOAP but hides all of the communications protocol stuff so you don't have to worry about it.

How To Remove Outline Border From Input Button

Removing nessorry accessible event not a good idea in up to standard web developments. either way if you looking for a solution removing just the outline doesn't solve the problem. you also have to remove the blue color shadow. for specific scenarios use a separate class name to isolate the this special style to your button.

.btn.focus, .btn:focus {
    outline: 0;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, .25);
}

Better do this

.remove-border.focus, .remove-border:focus {
        outline: 0;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, .25);
 }

Strip double quotes from a string in .NET

If you only want to strip the quotes from the ends of the string (not the middle), and there is a chance that there can be spaces at either end of the string (i.e. parsing a CSV format file where there is a space after the commas), then you need to call the Trim function twice...for example:

string myStr = " \"sometext\"";     //(notice the leading space)
myStr = myStr.Trim('"');            //(would leave the first quote: "sometext)
myStr = myStr.Trim().Trim('"');     //(would get what you want: sometext)

Laravel Request::all() Should Not Be Called Statically

The facade is another Request class, access it with the full path:

$input = \Request::all();

From laravel 5 you can also access it through the request() function:

$input = request()->all();

align textbox and text/labels in html?

You have two boxes, left and right, for each label/input pair. Both boxes are in one row and have fixed width. Now, you just have to make label text float to the right with text-align: right;

Here's a simple example:

http://jsfiddle.net/qP46X/

java.lang.OutOfMemoryError: Java heap space in Maven

In order to resolve java.lang.OutOfMemoryError: Java heap space in Maven, try to configure below configuration in pom

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>${maven-surefire-plugin.version}</version>
     <configuration>
        <verbose>true</verbose>
        <fork>true</fork>
        <argLine>-XX:MaxPermSize=500M</argLine>
    </configuration>
</plugin>

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

"N/A" is not an integer. It must throw NumberFormatException if you try to parse it to an integer.

Check before parsing or handle Exception properly.

  1. Exception Handling

    try{
        int i = Integer.parseInt(input);
    } catch(NumberFormatException ex){ // handle your exception
        ...
    }
    

or - Integer pattern matching -

String input=...;
String pattern ="-?\\d+";
if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
 ...
}

Is there a better way to run a command N times in bash?

If you are OK doing it periodically, you could run the following command to run it every 1 sec indefinitely. You can put other custom checks in place to run it n number of times.

watch -n 1 some_command

If you wish to have visual confirmation of changes, append --differences prior to the ls command.

According to the OSX man page, there's also

The --cumulative option makes highlighting "sticky", presenting a running display of all positions that have ever changed. The -t or --no-title option turns off the header showing the interval, command, and current time at the top of the display, as well as the following blank line.

Linux/Unix man page can be found here

Can I use Homebrew on Ubuntu?

The following steps worked for me:

  • Clone it from github

    git clone https://github.com/Homebrew/linuxbrew.git ~/.linuxbrew
    
  • Open your .bash_profile file using vi ~/.bash_profile

  • Add these lines

    export PATH="$HOME/.linuxbrew/bin:$PATH"
    export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
    export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"
    
  • Then type the following lines in your terminal

    export PATH=$HOME/.linuxbrew/bin:$PATH
    hash -r
    

Yes, it is done. Type brew in your terminal to check its existence.

How do I horizontally center an absolute positioned element inside a 100% width div?

You will have to assign both left and right property 0 value for margin: auto to center the logo.

So in this case:

#logo {
  background:red;
  height:50px;
  position:absolute;
  width:50px;
  left: 0;
  right: 0;
  margin: 0 auto;
}

You might also want to set position: relative for #header.

This works because, setting left and right to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin is set to auto. margin takes up all the extra space(equally on each side) leaving the content to its specified width. This results in content becoming center aligned.

Check if a string is not NULL or EMPTY

As in many other programming and scripting languages you can do so by adding ! in front of the condition

if (![string]::IsNullOrEmpty($version))
{
    $request += "/" + $version
}

Vendor code 17002 to connect to SQLDeveloper

In your case the "Vendor code 17002" is the equivalent of the ORA-12541 error: It's most likely that your listener is down, or has an improper port or service name. From the docs:

ORA-12541: TNS no listener

Cause: Listener for the source repository has not been started.

Action: Start the Listener on the machine where the source repository resides.

How do I combine 2 select statements into one?

use a case into the select and use in the where close a OR

something like this, I didn't tested it but it should work, I think...

select case when CCC='D' then 'test1' else 'test2' end, *
from table
where (CCC='D' AND DDD='X') or (CCC<>'D' AND DDD='X')

How to turn off gcc compiler optimization to enable buffer overflow

On newer distros (as of 2016), it seems that PIE is enabled by default so you will need to disable it explicitly when compiling.

Here's a little summary of commands which can be helpful when playing locally with buffer overflow exercises in general:

Disable canary:

gcc vuln.c -o vuln_disable_canary -fno-stack-protector

Disable DEP:

gcc vuln.c -o vuln_disable_dep -z execstack

Disable PIE:

gcc vuln.c -o vuln_disable_pie -no-pie

Disable all of protection mechanisms listed above (warning: for local testing only):

gcc vuln.c -o vuln_disable_all -fno-stack-protector -z execstack -no-pie

For 32-bit machines, you'll need to add the -m32 parameter as well.

Can't Autowire @Repository annotated interface in Spring Boot

It seems your @ComponentScan annotation is not set properly. Try :

@ComponentScan(basePackages = {"com.pharmacy"})

Actually you do not need the component scan if you have your main class at the top of the structure, for example directly under com.pharmacy package.

Also, you don't need both

@SpringBootApplication
@EnableAutoConfiguration

The @SpringBootApplication annotation includes @EnableAutoConfiguration by default.

How do I mock a service that returns promise in AngularJS Jasmine unit test?

We can also write jasmine's implementation of returning promise directly by spy.

spyOn(myOtherService, "makeRemoteCallReturningPromise").andReturn($q.when({}));

For Jasmine 2:

spyOn(myOtherService, "makeRemoteCallReturningPromise").and.returnValue($q.when({}));

(copied from comments, thanks to ccnokes)

JavaScript override methods

_x000D_
_x000D_
function A() {_x000D_
    var c = new C();_x000D_
 c.modify = function(){_x000D_
  c.x = 123;_x000D_
  c.y = 333;_x000D_
 }_x000D_
 c.sum();_x000D_
}_x000D_
_x000D_
function B() {_x000D_
    var c = new C();_x000D_
 c.modify = function(){_x000D_
  c.x = 999;_x000D_
  c.y = 333;_x000D_
 }_x000D_
 c.sum();_x000D_
}_x000D_
_x000D_
_x000D_
C = function () {_x000D_
   this.x = 10;_x000D_
   this.y = 20;_x000D_
_x000D_
   this.modify = function() {_x000D_
      this.x = 30;_x000D_
      this.y = 40;_x000D_
   };_x000D_
   _x000D_
   this.sum = function(){_x000D_
 this.modify();_x000D_
 console.log("The sum is: " + (this.x+this.y));_x000D_
   }_x000D_
}_x000D_
_x000D_
A();_x000D_
B();
_x000D_
_x000D_
_x000D_

Pause in Python

There's no need to wait for input before closing, just change your command like so:

cmd /K python <script>

The /K switch will execute the command that follows, but leave the command interpreter window open, in contrast to /C, which executes and then closes.

Ruby: Easiest Way to Filter Hash Keys?

The easiest way is to include the gem 'activesupport' (or gem 'active_support').

params.slice(:choice1, :choice2, :choice3)

How to install Laravel's Artisan?

While you are working with Laravel you must be in root of laravel directory structure. There are App, route, public etc folders is root directory. Just follow below step to fix issue. check composer status using : composer -v

First, download the Laravel installer using Composer:

composer global require "laravel/installer"

Please check with below command:

php artisan serve

still not work then create new project with existing code. using LINK

relative path to CSS file

You have to move the css folder into your web folder. It seems that your web folder on the hard drive equals the /ServletApp folder as seen from the www. Other content than inside your web folder cannot be accessed from the browsers.

The url of the CSS link is then

 <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>

Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

I would recommend the Select option because cursors take longer.
Also using the Select is much easier to understand for anyone who has to modify your query

WooCommerce return product object by id

Another easy way is to use the WC_Product_Factory class and then call function get_product(ID)

http://docs.woothemes.com/wc-apidocs/source-class-WC_Product_Factory.html#16-63

sample:

// assuming the list of product IDs is are stored in an array called IDs;
$_pf = new WC_Product_Factory();  
foreach ($IDs as $id) {

    $_product = $_pf->get_product($id);

    // from here $_product will be a fully functional WC Product object, 
    // you can use all functions as listed in their api
}

You can then use all the function calls as listed in their api: http://docs.woothemes.com/wc-apidocs/class-WC_Product.html

How do I find what Java version Tomcat6 is using?

Or you could use the Probe application and just look at its System Info page. Much easier than writing code, and once you start using it you'll never go back to Tomcat Manager.

Having both a Created and Last Updated timestamp columns in MySQL 4.0

This is how can you have automatic & flexible createDate/lastModified fields using triggers:

First define them like this:

CREATE TABLE `entity` (
  `entityid` int(11) NOT NULL AUTO_INCREMENT,
  `createDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `lastModified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `name` varchar(255) DEFAULT NULL,
  `comment` text,
  PRIMARY KEY (`entityid`),
)

Then add these triggers:

DELIMITER ;;
CREATE trigger entityinsert BEFORE INSERT ON entity FOR EACH ROW BEGIN SET NEW.createDate=IF(ISNULL(NEW.createDate) OR NEW.createDate='0000-00-00 00:00:00', CURRENT_TIMESTAMP, IF(NEW.createDate<CURRENT_TIMESTAMP, NEW.createDate, CURRENT_TIMESTAMP));SET NEW.lastModified=NEW.createDate; END;;
DELIMITER ;
CREATE trigger entityupdate BEFORE UPDATE ON entity FOR EACH ROW SET NEW.lastModified=IF(NEW.lastModified<OLD.lastModified, OLD.lastModified, CURRENT_TIMESTAMP);
  • If you insert without specifying createDate or lastModified, they will be equal and set to the current timestamp.
  • If you update them without specifying createDate or lastModified, the lastModified will be set to the current timestamp.

But here's the nice part:

  • If you insert, you can specify a createDate older than the current timestamp, allowing imports from older times to work well (lastModified will be equal to createDate).
  • If you update, you can specify a lastModified older than the previous value ('0000-00-00 00:00:00' works well), allowing to update an entry if you're doing cosmetic changes (fixing a typo in a comment) and you want to keep the old lastModified date. This will not modify the lastModified date.

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

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

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

or

if 'List contents' in UserInput: 

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

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

GSON - Date format

I'm on Gson 2.8.6 and discovered this bug today.

My approach allows all our existing clients (mobile/web/etc) to continue functioning as they were, but adds some handling for those using 24h formats and allows millis too, for good measure.

Gson rawGson = new Gson();
SimpleDateFormat fmt = new SimpleDateFormat("MMM d, yyyy HH:mm:ss")
private class DateDeserializer implements JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        try {
            return new rawGson.fromJson(json, Date.class);
        } catch (JsonSyntaxException e) {}
        String timeString = json.getAsString();
        log.warning("Standard date deserialization didn't work:" + timeString);
        try {
            return fmt.parse(timeString);
        } catch (ParseException e) {}
        log.warning("Parsing as json 24 didn't work:" + timeString);
        return new Date(json.getAsLong());
    }
}

Gson gson = new GsonBuilder()
    .registerTypeAdapter(Date.class, new DateDeserializer())
    .create();

I kept serialization the same as all clients understand the standard json date format.

Ordinarily, I don't think it's good practice to use try/catch blocks, but this should be a fairly rare case.

How to convert enum names to string in c

An simpler alternative to Hokyo's "Non-Sequential enums" answer, based on using designators to instantiate the string array:

#define NAMES C(RED, 10)C(GREEN, 20)C(BLUE, 30)
#define C(k, v) k = v,
enum color { NAMES };
#undef C

#define C(k, v) [v] = #k,    
const char * const color_name[] = { NAMES };

What does it mean to have an index to scalar variable error? python

IndexError: invalid index to scalar variable happens when you try to index a numpy scalar such as numpy.int64 or numpy.float64. It is very similar to TypeError: 'int' object has no attribute '__getitem__' when you try to index an int.

>>> a = np.int64(5)
>>> type(a)
<type 'numpy.int64'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index to scalar variable.
>>> a = 5
>>> type(a)
<type 'int'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

"break;" out of "if" statement?

This is actually the conventional use of the break statement. If the break statement wasn't nested in an if block the for loop could only ever execute one time.

MSDN lists this as their example for the break statement.

Parse JSON file using GSON

Imo, the best way to parse your JSON response with GSON would be creating classes that "match" your response and then use Gson.fromJson() method.
For example:

class Response {
    Map<String, App> descriptor;
    // standard getters & setters...
}

class App {
  String name;
  int age;
  String[] messages;
  // standard getters & setters...
}

Then just use:

Gson gson = new Gson();
Response response = gson.fromJson(yourJson, Response.class);

Where yourJson can be a String, any Reader, a JsonReader or a JsonElement.

Finally, if you want to access any particular field, you just have to do:

String name = response.getDescriptor().get("app3").getName();

You can always parse the JSON manually as suggested in other answers, but personally I think this approach is clearer, more maintainable in long term and it fits better with the whole idea of JSON.