Programs & Examples On #Blackjack

Card Game – Where the aim is to get your cards as closer to 21 then the dealer, while not going over. J, Q, K are worth 10. A are either 11 or 1.

Convert an array into an ArrayList

List<Card> list = new ArrayList<Card>(Arrays.asList(hand));

How to get the fields in an Object via reflection?

I've an object (basically a VO) in Java and I don't know its type. I need to get values which are not null in that object.

Maybe you don't necessary need reflection for that -- here is a plain OO design that might solve your problem:

  1. Add an interface Validation which expose a method validate which checks the fields and return whatever is appropriate.
  2. Implement the interface and the method for all VO.
  3. When you get a VO, even if it's concrete type is unknown, you can typecast it to Validation and check that easily.

I guess that you need the field that are null to display an error message in a generic way, so that should be enough. Let me know if this doesn't work for you for some reason.

Netbeans - class does not have a main method

in Project window right click on your project and select properties go to Run and set Main Class ( you can brows it) . this manual work if you have static main in some class :

public class Someclass
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        //your code
    }
}

Netbeans doesn't have any conflict with W7 and you can use version 6.8 .

SQL set values of one column equal to values of another column in the same table

I don't think that other example is what you're looking for. If you're just updating one column from another column in the same table you should be able to use something like this.

update some_table set null_column = not_null_column where null_column is null

CheckBox in RecyclerView keeps on checking different items

In my case this worked.

@Override
public void onViewRecycled(MyViewHolder holder) {
    holder.checkbox.setChecked(false); // - this line do the trick
    super.onViewRecycled(holder);
}

How to import component into another root component in Angular 2

above answers In simple words, you have to register under @NgModule's

declarations: [
    AppComponent, YourNewComponentHere
  ] 

of app.module.ts

do not forget to import that component.

How to create helper file full of functions in react native?

If you want to use class, you can do this.

Helper.js

  function x(){}

  function y(){}

  export default class Helper{

    static x(){ x(); }

    static y(){ y(); }

  }

App.js

import Helper from 'helper.js';

/****/

Helper.x

HTML code for an apostrophe

Even though &apos; reads nicer than &#39; and it's a shame not to use it, as a fail-safe, use &#39;.

&apos; is a valid HTML 5 entity, however it is not a valid HTML 4 entity.

Unless <!DOCTYPE html> is at the top of your HTML document, use &#39;

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

How to reliably open a file in the same directory as a Python script

I'd do it this way:

from os.path import abspath, exists

f_path = abspath("fooabar.txt")

if exists(f_path):
    with open(f_path) as f:
        print f.read()

The above code builds an absolute path to the file using abspath and is equivalent to using normpath(join(os.getcwd(), path)) [that's from the pydocs]. It then checks if that file actually exists and then uses a context manager to open it so you don't have to remember to call close on the file handle. IMHO, doing it this way will save you a lot of pain in the long run.

Exit while loop by user hitting ENTER key

You need to find out what the variable User would look like when you just press Enter. I won't give you the full answer, but a tip: Fire an interpreter and try it out. It's not that hard ;) Notice that print's sep is '\n' by default (was that too much :o)

Showing the stack trace from a running Python application

I would add this as a comment to haridsv's response, but I lack the reputation to do so:

Some of us are still stuck on a version of Python older than 2.6 (required for Thread.ident), so I got the code working in Python 2.5 (though without the thread name being displayed) as such:

import traceback
import sys
def dumpstacks(signal, frame):
    code = []
    for threadId, stack in sys._current_frames().items():
            code.append("\n# Thread: %d" % (threadId))
        for filename, lineno, name, line in traceback.extract_stack(stack):
            code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
            if line:
                code.append("  %s" % (line.strip()))
    print "\n".join(code)

import signal
signal.signal(signal.SIGQUIT, dumpstacks)

Disabling SSL Certificate Validation in Spring RestTemplate

What you need to add is a custom HostnameVerifier class bypasses certificate verification and returns true

HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

This needs to be placed appropriately in your code.

Remove HTML Tags from an NSString on the iPhone

If you are willing to use Three20 framework, it has a category on NSString that adds stringByRemovingHTMLTags method. See NSStringAdditions.h in Three20Core subproject.

Why does GitHub recommend HTTPS over SSH?

It's possible to argue that using SSHs key to authenticate is less secure because we tend to change our password more periodically than we generate new SSH keys.

Servers that limit the lifespan for which they'll honor given SSH keys can help force users toward the practice of refreshing SSH-keys periodically.

How to read all files in a folder from Java?

File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();

for (File file : listOfFiles) {
    if (file.isFile()) {
        System.out.println(file.getName());
    }
}

How to move all files including hidden files into parent directory via *

Let me introduce you to my friend "dotglob". It turns on and off whether or not "*" includes hidden files.

$ mkdir test
$ cd test
$ touch a b c .hidden .hi .den
$ ls -a
. ..  .den  .hi .hidden a b c

$ shopt -u dotglob
$ ls *
a b c
$ for i in * ; do echo I found: $i ; done
I found: a
I found: b
I found: c

$ shopt -s dotglob
$ ls *
.den  .hi .hidden a b c
$ for i in * ; do echo I found: $i ; done
I found: .den
I found: .hi
I found: .hidden
I found: a
I found: b
I found: c

It defaults to "off".

$ shopt dotglob
dotglob         off

It is best to turn it back on when you are done otherwise you will confuse things that assume it will be off.

Change the background color of a row in a JTable

Resumee of Richard Fearn's answer , to make each second line gray:

jTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer()
{
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
        return c;
    }
});

console.log not working in Angular2 Component (Typescript)

Also try to update your browser because Angular need latest browser. check: https://angular.io/guide/browser-support

I fixed console.log issue after updating latest browser.

python location on mac osx

On Mac OS X, it's in the Python framework in /System/Library/Frameworks/Python.framework/Resources.

Full path is:

/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python

Btw it's easy to find out where you can find a specific binary: which Python will show you the path of your Python binary (which is probably the same as I posted above).

How can I count the number of characters in a Bash variable

jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23

link Couting characters, words, lenght of the words and total lenght in a sentence

How to use the IEqualityComparer

Your GetHashCode implementation always returns the same value. Distinct relies on a good hash function to work efficiently because it internally builds a hash table.

When implementing interfaces of classes it is important to read the documentation, to know which contract you’re supposed to implement.1

In your code, the solution is to forward GetHashCode to Class_reglement.Numf.GetHashCode and implement it appropriately there.

Apart from that, your Equals method is full of unnecessary code. It could be rewritten as follows (same semantics, ¼ of the code, more readable):

public bool Equals(Class_reglement x, Class_reglement y)
{
    return x.Numf == y.Numf;
}

Lastly, the ToList call is unnecessary and time-consuming: AddRange accepts any IEnumerable so conversion to a List isn’t required. AsEnumerable is also redundant here since processing the result in AddRange will cause this anyway.


1 Writing code without knowing what it actually does is called cargo cult programming. It’s a surprisingly widespread practice. It fundamentally doesn’t work.

AttributeError: 'str' object has no attribute 'append'

What you are trying to do is add additional information to each item in the list that you already created so

    alist[ 'from form', 'stuff 2', 'stuff 3']

    for j in range( 0,len[alist]):
        temp= []
        temp.append(alist[j]) # alist[0] is 'from form' 
        temp.append('t') # slot for first piece of data 't'
        temp.append('-') # slot for second piece of data

    blist.append(temp)      # will be alist with 2 additional fields for extra stuff assocated with each item in alist  

How to find out the MySQL root password

The default password which worked for me after immediate installation of mysql server is : mysql

Java getHours(), getMinutes() and getSeconds()

Java 8

    System.out.println(LocalDateTime.now().getHour());       // 7
    System.out.println(LocalDateTime.now().getMinute());     // 45
    System.out.println(LocalDateTime.now().getSecond());     // 32

Calendar

System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));  // 7 
System.out.println(Calendar.getInstance().get(Calendar.MINUTE));       // 45
System.out.println(Calendar.getInstance().get(Calendar.SECOND));       // 32

Joda Time

    System.out.println(new DateTime().getHourOfDay());      // 7
    System.out.println(new DateTime().getMinuteOfHour());   // 45
    System.out.println(new DateTime().getSecondOfMinute()); // 32

Formatted

Java 8

    // 07:48:55.056
    System.out.println(ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME));
    // 7:48:55
    System.out.println(LocalTime.now().getHour() + ":" + LocalTime.now().getMinute() + ":" + LocalTime.now().getSecond());

    // 07:48:55
    System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));

    // 074855
    System.out.println(new SimpleDateFormat("HHmmss").format(Calendar.getInstance().getTime()));

    // 07:48:55 
    System.out.println(new Date().toString().substring(11, 20));

How to set a variable inside a loop for /F

Simple example of batch code using %var%, !var!, and %%.

In this example code, focus here is that we want to capture a start time using the built in variable TIME (using time because it always changes automatically):

Code:

@echo off
setlocal enabledelayedexpansion
SET "SERVICES_LIST=MMS ARSM MMS2"
SET START=%TIME%
SET "LAST_SERVICE="

for %%A in (%SERVICES_LIST%) do (
    SET START=!TIME!
    CALL :SOME_FUNCTION %%A
    SET "LAST_SERVICE=%%A"
    ping -n 5 127.0.0.1 > NUL
    SET OTHER=!START!
    if !OTHER! EQU !START! (
    echo !OTHER! is equal to !START! as expected
    ) ELSE (
    echo NOTHING
    )
)
ECHO Last service run was %LAST_SERVICE%

:: Function declared like this
:SOME_FUNCTION
echo Running: %1
EXIT /B 0

Comments on code:

  • Use enabledelayedexpansion
  • The first three SET lines are typical uses of the SET command, use this most of the time.
  • The next line is a for loop, must use %%A for iteration, then %%B if a loop inside it etc.. You can not use long variable names.
  • To access a changed variable such as the time variable, you must use !! or set with !! (have enableddelayexpansion enabled).
  • When looping in for loop each iteration is accessed as the %%A variable.
  • The code in the for loop is point out the various ways to set a variable. Looking at 'SET OTHER=!START!', if you were to change to SET OTHER=%START% you will see why !! is needed. (hint: you will see NOTHING) output.
  • In short !! is more likely needed inside of loops, %var% in general, %% always a for loop.

Further reading

Use the following links to determine why in more detail:

JQuery Bootstrap Multiselect plugin - Set a value as selected in the multiselect dropdown

 var valArr = ["1","2","3"];

/* Below Code Matches current object's (i.e. option) value with the array values */
 /* Returns -1 if match not found */
 $("select").multiselect("widget").find(":checkbox").each(function(){
    if(jQuery.inArray(this.value, valArr) !=-1)
            this.click();

   });

This selects the options whose value matches with values in array.

How to fix "Referenced assembly does not have a strong name" error?

I was running into this with a ServiceStack dll I had installed with nuget. Turns out there was another set of dlls available that were labeled signed. Not going to be the answer for everyone, but you may just need to check for an existing signed version of your assembly. ServiceStack.Signed

How to use the 'main' parameter in package.json?

Just think of it as the "starting point".

In a sense of object-oriented programming, say C#, it's the init() or constructor of the object class, that's what "entry point" meant.

For example

public class IamMain  // when export and require this guy
{
    public IamMain()  // this is "main"
    {...}

    ...   // many others such as function, properties, etc.
}

How to set custom favicon in Express?

If you are using Express > 4.0, you could go for serve-favicon

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

If, like me, you prefer to deal with strongly typed objects** go with:

MyObj obj =  JsonConvert.DeserializeObject<MyObj>(jsonString);

This way you get to use intellisense and compile time type error checking.

You can easily create the required objects by copying your JSON into memory and pasting it as JSON objects (Visual Studio -> Edit -> Paste Special -> Paste JSON as Classes).

See here if you don't have that option in Visual Studio.

You will also need to make sure your JSON is valid. Add your own object at the start if it is just an array of objects. i.e. {"obj":[{},{},{}]}

** I know that dynamic makes things easier sometimes but I'm a bit ol'skool with this.

Visual Studio Code how to resolve merge conflicts with git?

For VS Code 1.38 or if you could not find any "lightbulb" button. Pay close attention to the greyed out text above the conflicts; there is a list of actions you can take.

How to get the filename without the extension from a path in Python?

os.path.splitext() won't work if there are multiple dots in the extension.

For example, images.tar.gz

>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> print os.path.splitext(file_name)[0]
images.tar

You can just find the index of the first dot in the basename and then slice the basename to get just the filename without extension.

>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> index_of_dot = file_name.index('.')
>>> file_name_without_extension = file_name[:index_of_dot]
>>> print file_name_without_extension
images

Oracle: If Table Exists

The best and most efficient way is to catch the "table not found" exception: this avoids the overhead of checking if the table exists twice; and doesn't suffer from the problem that if the DROP fails for some other reason (that might be important) the exception is still raised to the caller:

BEGIN
   EXECUTE IMMEDIATE 'DROP TABLE ' || table_name;
EXCEPTION
   WHEN OTHERS THEN
      IF SQLCODE != -942 THEN
         RAISE;
      END IF;
END;

ADDENDUM For reference, here are the equivalent blocks for other object types:

Sequence

BEGIN
  EXECUTE IMMEDIATE 'DROP SEQUENCE ' || sequence_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -2289 THEN
      RAISE;
    END IF;
END;

View

BEGIN
  EXECUTE IMMEDIATE 'DROP VIEW ' || view_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -942 THEN
      RAISE;
    END IF;
END;

Trigger

BEGIN
  EXECUTE IMMEDIATE 'DROP TRIGGER ' || trigger_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4080 THEN
      RAISE;
    END IF;
END;

Index

BEGIN
  EXECUTE IMMEDIATE 'DROP INDEX ' || index_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -1418 THEN
      RAISE;
    END IF;
END;

Column

BEGIN
  EXECUTE IMMEDIATE 'ALTER TABLE ' || table_name
                || ' DROP COLUMN ' || column_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -904 AND SQLCODE != -942 THEN
      RAISE;
    END IF;
END;

Database Link

BEGIN
  EXECUTE IMMEDIATE 'DROP DATABASE LINK ' || dblink_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -2024 THEN
      RAISE;
    END IF;
END;

Materialized View

BEGIN
  EXECUTE IMMEDIATE 'DROP MATERIALIZED VIEW ' || mview_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -12003 THEN
      RAISE;
    END IF;
END;

Type

BEGIN
  EXECUTE IMMEDIATE 'DROP TYPE ' || type_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4043 THEN
      RAISE;
    END IF;
END;

Constraint

BEGIN
  EXECUTE IMMEDIATE 'ALTER TABLE ' || table_name
            || ' DROP CONSTRAINT ' || constraint_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -2443 AND SQLCODE != -942 THEN
      RAISE;
    END IF;
END;

Scheduler Job

BEGIN
  DBMS_SCHEDULER.drop_job(job_name);
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -27475 THEN
      RAISE;
    END IF;
END;

User / Schema

BEGIN
  EXECUTE IMMEDIATE 'DROP USER ' || user_name;
  /* you may or may not want to add CASCADE */
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -1918 THEN
      RAISE;
    END IF;
END;

Package

BEGIN
  EXECUTE IMMEDIATE 'DROP PACKAGE ' || package_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4043 THEN
      RAISE;
    END IF;
END;

Procedure

BEGIN
  EXECUTE IMMEDIATE 'DROP PROCEDURE ' || procedure_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4043 THEN
      RAISE;
    END IF;
END;

Function

BEGIN
  EXECUTE IMMEDIATE 'DROP FUNCTION ' || function_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -4043 THEN
      RAISE;
    END IF;
END;

Tablespace

BEGIN
  EXECUTE IMMEDIATE 'DROP TABLESPACE' || tablespace_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -959 THEN
      RAISE;
    END IF;
END;

Synonym

BEGIN
  EXECUTE IMMEDIATE 'DROP SYNONYM ' || synonym_name;
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -1434 THEN
      RAISE;
    END IF;
END;

Remove all the elements that occur in one list from another

Use the Python set type. That would be the most Pythonic. :)

Also, since it's native, it should be the most optimized method too.

See:

http://docs.python.org/library/stdtypes.html#set

http://docs.python.org/library/sets.htm (for older python)

# Using Python 2.7 set literal format.
# Otherwise, use: l1 = set([1,2,6,8])
#
l1 = {1,2,6,8}
l2 = {2,3,5,8}
l3 = l1 - l2

ImportError: No module named 'django.core.urlresolvers'

To solve this either you down-grade the Django to any version lesser than 2.0. pip install Django==1.11.29.

How do I write stderr to a file while using "tee" with a pipe?

If you're using zsh, you can use multiple redirections, so you don't even need tee:

./cmd 1>&1 2>&2 1>out_file 2>err_file

Here you're simply redirecting each stream to itself and the target file.


Full example

% (echo "out"; echo "err">/dev/stderr) 1>&1 2>&2 1>/tmp/out_file 2>/tmp/err_file
out
err
% cat /tmp/out_file
out
% cat /tmp/err_file
err

Note that this requires the MULTIOS option to be set (which is the default).

MULTIOS

Perform implicit tees or cats when multiple redirections are attempted (see Redirection).

How do you make sure email you send programmatically is not automatically marked as spam?

It could very well be the case that people who sign up for your service are entering emails with typing mistakes that you do not correct. For example: chris@gmial.com -or- james@hotnail.com.

And such domains are configured to be used as spamtraps which will automatically flag your email server's IP and/or domain and hurt its reputation.

To avoid this, do a double-check for the email address that is entered upon your product subscription. Also, send a confirmation email to really ensure that this email address is 100% validated by a human being that is entering the confirmation email, before you send them the product key or accept their subscription. The verification email should require the recipient to click a link or reply in order to really confirm that the owner of the mailbox is the person who signed up.

Common elements in two lists

Use Collection#retainAll().

listA.retainAll(listB);
// listA now contains only the elements which are also contained in listB.

If you want to avoid that changes are being affected in listA, then you need to create a new one.

List<Integer> common = new ArrayList<Integer>(listA);
common.retainAll(listB);
// common now contains only the elements which are contained in listA and listB.

Proper way to exit command line program?

if you do ctrl-z and then type exit it will close background applications.

Ctrl+Q is another good way to kill the application.

Move a view up only when the keyboard covers an input field

Why not implement this in a UITableViewController instead? The keyboard won't hide any text fields when its shown.

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

There are two ways to handle this.

1) Check the event.target result in your callback to see if it matches your parent div

var g_ParentDiv;

function OnMouseOut(event) {
    if (event.target != g_ParentDiv) {
        return;
    }
    // handle mouse event here!
};


window.onload = function() {
    g_ParentDiv = document.getElementById("parentdiv");
    g_ParentDiv.onmouseout = OnMouseOut;
};

<div id="parentdiv">
    <img src="childimage.jpg" id="childimg" />
</div>

2) Or use event capturing and call event.stopPropagation in the callback function

var g_ParentDiv;

function OnMouseOut(event) {

    event.stopPropagation(); // don't let the event recurse into children

    // handle mouse event here!
};


window.onload = function() {
    g_ParentDiv = document.getElementById("parentdiv");
    g_ParentDiv.addEventListener("mouseout", OnMouseOut, true); // pass true to enable event capturing so parent gets event callback before children
};

<div id="parentdiv">
    <img src="childimage.jpg" id="childimg" />
</div>

How to import a jar in Eclipse

Just a comment on importing jars into Eclipse (plug-in development) projects:

In case you are developing Eclipse plug-ins, it makes sense to use Eclipse's native bundling mechanism instead of just importing the jar into a plug-in project. Eclipse (or better its underlying OSGi runtime, Equinox) uses so-called bundles which contain some more information than plain jars (e.g., version infos, dependencies to other bundles, exported packages; see the MANIFEST.MF file). Because of this information, OSGi bundles can be dynamically loaded/unloaded and there is automatic dependency resolution available in an OSGi/Eclipse runtime. Hence, using OSGi bundles instead of plain jars (contained inside another OSGi bundle) has some advantages.

(BTW: Eclipse plug-ins are the same thing as OSGi bundles.)

There is a good chance that somebody already bundled a certain (3rd party) library as an OSGi bundle. You might want to take a look at the following bundle repositories:

How to Make A Chevron Arrow Using CSS?

Left Right Arrow with hover effect using Roko C. Buljan box-shadow trick

_x000D_
_x000D_
.arr {_x000D_
  display: inline-block;_x000D_
  padding: 1.2em;_x000D_
  box-shadow: 8px 8px 0 2px #777 inset;_x000D_
}_x000D_
.arr.left {_x000D_
  transform: rotate(-45deg);_x000D_
}_x000D_
.arr.right {_x000D_
  transform: rotate(135deg);_x000D_
}_x000D_
.arr:hover {_x000D_
  box-shadow: 8px 8px 0 2px #000 inset_x000D_
}
_x000D_
<div class="arr left"></div>_x000D_
<div class="arr right"></div>
_x000D_
_x000D_
_x000D_

Changing permissions via chmod at runtime errors with "Operation not permitted"

You, or most likely your sysadmin, will need to login as root and run the chown command: http://www.computerhope.com/unix/uchown.htm

Through this command you will become the owner of the file.

Or, you can be a member of a group that owns this file and then you can use chmod.

But, talk with your sysadmin.

Difference between e.target and e.currentTarget

make an example:

var body = document.body,
    btn = document.getElementById( 'id' );
body.addEventListener( 'click', function( event ) {
    console.log( event.currentTarget === body );
    console.log( event.target === btn );
}, false );

when you click 'btn', and 'true' and 'true' will be appeared!

Checking if object is empty, works with ng-show but not from controller?

another simple one-liner:

var ob = {};
Object.keys(ob).length // 0

What is the difference between hg forget and hg remove?

'hg forget' is just shorthand for 'hg remove -Af'. From the 'hg remove' help:

...and -Af can be used to remove files from the next revision without deleting them from the working directory.

Bottom line: 'remove' deletes the file from your working copy on disk (unless you uses -Af) and 'forget' doesn't.

twitter bootstrap typeahead ajax example

I did some modifications on the jquery-ui.min.js:

//Line 319 ORIG:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").appendTo(d(...
// NEW:
this.menu=d("<ul></ul>").addClass("ui-autocomplete").addClass("typeahead").addClass("dropdown-menu").appendTo(d(...

// Line 328 ORIG:
this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr...
// NEW:this.element.attr....

// Line 329 ORIG:
this.active=a.eq(0).children("a")
this.active.children("a")
// NEW:
this.active=a.eq(0).addClass("active").children("a")
this.active.removeClass("active").children("a")`

and add following css

.dropdown-menu {
    max-width: 920px;
}
.ui-menu-item {
    cursor: pointer;        
}

Works perfect.

Validate decimal numbers in JavaScript - IsNumeric()

Here's a dead-simple one (tested in Chrome, Firefox, and IE):

function isNumeric(x) {
  return parseFloat(x) == x;
}

Test cases from question:

console.log('trues');
console.log(isNumeric('-1'));
console.log(isNumeric('-1.5'));
console.log(isNumeric('0'));
console.log(isNumeric('0.42'));
console.log(isNumeric('.42'));

console.log('falses');
console.log(isNumeric('99,999'));
console.log(isNumeric('0x89f'));
console.log(isNumeric('#abcdef'));
console.log(isNumeric('1.2.3'));
console.log(isNumeric(''));
console.log(isNumeric('blah'));

Some more test cases:

console.log('trues');
console.log(isNumeric(0));
console.log(isNumeric(-1));
console.log(isNumeric(-500));
console.log(isNumeric(15000));
console.log(isNumeric(0.35));
console.log(isNumeric(-10.35));
console.log(isNumeric(2.534e25));
console.log(isNumeric('2.534e25'));
console.log(isNumeric('52334'));
console.log(isNumeric('-234'));
console.log(isNumeric(Infinity));
console.log(isNumeric(-Infinity));
console.log(isNumeric('Infinity'));
console.log(isNumeric('-Infinity'));

console.log('falses');
console.log(isNumeric(NaN));
console.log(isNumeric({}));
console.log(isNumeric([]));
console.log(isNumeric(''));
console.log(isNumeric('one'));
console.log(isNumeric(true));
console.log(isNumeric(false));
console.log(isNumeric());
console.log(isNumeric(undefined));
console.log(isNumeric(null));
console.log(isNumeric('-234aa'));

Note that it considers infinity a number.

ipad safari: disable scrolling, and bounce effect?

To prevent scrolling on modern mobile browsers you need to add the passive: false. I had been pulling my hair out getting this to work until I found this solution. I have only found this mentioned in one other place on the internet.

_x000D_
_x000D_
function preventDefault(e){_x000D_
    e.preventDefault();_x000D_
}_x000D_
_x000D_
function disableScroll(){_x000D_
    document.body.addEventListener('touchmove', preventDefault, { passive: false });_x000D_
}_x000D_
function enableScroll(){_x000D_
    document.body.removeEventListener('touchmove', preventDefault);_x000D_
}
_x000D_
_x000D_
_x000D_

Installing a local module using npm?

So I had a lot of problems with all of the solutions mentioned so far...

I have a local package that I want to always reference (rather than npm link) because it won't be used outside of this project (for now) and also won't be uploaded to an npm repository for wide use as of yet.

I also need it to work on Windows AND Unix, so sym-links aren't ideal.

Pointing to the tar.gz result of (npm package) works for the dependent npm package folder, however this causes issues with the npm cache if you want to update the package. It doesn't always pull in the new one from the referenced npm package when you update it, even if you blow away node_modules and re-do your npm-install for your main project.

so.. This is what worked well for me!

Main Project's Package.json File Snippet:

  "name": "main-project-name",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    ...
    "preinstall": "cd ../some-npm-package-angular && npm install && npm run build"
  },
  "private": true,
  "dependencies": {
    ...
    "@com/some-npm-package-angular": "file:../some-npm-package-angular/dist",
    ...
  }

This achieves 3 things:

  • Avoids the common error (at least with angular npm projects) "index.ts is not part of the compilation." - as it points to the built (dist) folder.
  • Adds a preinstall step to build the referenced npm client package to make sure the dist folder of our dependent package is built.
  • Avoids issues where referencing a tar.gz file locally may be cached by npm and not updated in the main project without lots of cleaning/troubleshooting/re-building/re-installing.

I hope this is clear, and helps someone out.

The tar.gz approach also sort of works..

npm install (file path) also sort of works.

This was all based off of a generated client from an openapi spec that we wanted to keep in a separate location (rather than using copy-pasta for individual files)

====== UPDATE: ======

There are additional errors with a regular development flow with the above solution, as npm's versioning scheme with local files is absolutely terrible. If your dependent package changes frequently, this whole scheme breaks because npm will cache your last version of the project and then blow up when the SHA hash doesn't match anymore with what was saved in your package-lock.json file, among other issues.

As a result, I recommend using the *.tgz approach with a version update for each change. This works by doing three things.

First:

For your dependent package, use the npm library "ng-packagr". This is automatically added to auto-generated client packages created by the angular-typescript code generator for OpenAPI 3.0.

As a result the project that I'm referencing has a "scripts" section within package.json that looks like this:

  "scripts": {
    "build": "ng-packagr -p ng-package.json",
    "package": "npm install && npm run build && cd dist && npm pack"
  },

And the project referencing this other project adds a pre-install step to make sure the dependent project is up to date and rebuilt before building itself:

  "scripts": {
    "preinstall": "npm run clean && cd ../some-npm-package-angular && npm run package"
  },

Second

Reference the built tgz npm package from your main project!

  "dependencies": {
    "@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-<packageVersion>.tgz",
    ...
  }

Third

Update the dependent package's version EVERY TIME you update the dependent package. You'll also have to update the version in the main project.

If you do not do this, NPM will choke and use a cached version and explode when the SHA hash doesn't match. NPM versions file-based packages based on the filename changing. It won't check the package itself for an updated version in package.json, and the NPM team stated that they will not fix this, but people keep raising the issue: https://github.com/microsoft/WSL/issues/348

for now, just update the:

"version": "1.0.0-build5",

In the dependent package's package.json file, then update your reference to it in the main project to reference the new filename, ex:

"dependencies": {
       "@com/some-npm-package-angular": "file:../some-npm-package-angular/dist/some-npm-package-angular-1.0.0-build5.tgz",
        ...
}

You get used to it. Just update the two package.json files - version then the ref to the new filename.

Hope that helps someone...

What is the (function() { } )() construct in JavaScript?

Normally, JavaScript code has global scope in the application. When we declare global variable in it, there is a chance for using the same duplicate variable in some other area of the development for some other purpose. Because of this duplication there may happen some error. So we can avoid this global variables by using immediately invoking function expression , this expression is self-executing expression.When we make our code inside this IIFE expression global variable will be like local scope and local variable.

Two ways we can create IIFE

(function () {
    "use strict";
    var app = angular.module("myModule", []);
}());

OR

(function () {
    "use strict";
    var app = angular.module("myModule", []);
})();

In the code snippet above, “var app” is a local variable now.

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

As per the docs:

You can set annotation processor argument (room.schemaLocation) to tell Room to export the schema into a folder. Even though it is not mandatory, it is a good practice to have version history in your codebase and you should commit that file into your version control system (but don't ship it with your app!).

So if you don't need to check the schema and you want to get rid of the warning, just add exportSchema = false to your RoomDatabase, as follows.

@Database(entities = { YourEntity.class }, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
   //...
}

If you follow @mikejonesguy answer below, you will follow the good practice mentioned in the docs :). Basically you will get a .json file in your ../app/schemas/ folder. And it looks something like this:

{
  "formatVersion": 1,
  "database": {
    "version": 1,
    "identityHash": "53db508c5248423325bd5393a1c88c03",
    "entities": [
      {
        "tableName": "sms_table",
        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `message` TEXT, `date` INTEGER, `client_id` INTEGER)",
        "fields": [
          {
            "fieldPath": "id",
            "columnName": "id",
            "affinity": "INTEGER"
          },
          {
            "fieldPath": "message",
            "columnName": "message",
            "affinity": "TEXT"
          },
          {
            "fieldPath": "date",
            "columnName": "date",
            "affinity": "INTEGER"
          },
          {
            "fieldPath": "clientId",
            "columnName": "client_id",
            "affinity": "INTEGER"
          }
        ],
        "primaryKey": {
          "columnNames": [
            "id"
          ],
          "autoGenerate": true
        },
        "indices": [],
        "foreignKeys": []
      }
    ],
    "setupQueries": [
      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"53db508c5248423325bd5393a1c88c03\")"
    ]
  }
}

If my understanding is correct, you will get such a file with every database version update, so that you can easily follow the history of your db.

Can gcc output C code after preprocessing?

Yes. Pass gcc the -E option. This will output preprocessed source code.

Write a file in UTF-8 using FileWriter (Java)?

You need to use the OutputStreamWriter class as the writer parameter for your BufferedWriter. It does accept an encoding. Review javadocs for it.

Somewhat like this:

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
    new FileOutputStream("jedis.txt"), "UTF-8"
));

Or you can set the current system encoding with the system property file.encoding to UTF-8.

java -Dfile.encoding=UTF-8 com.jediacademy.Runner arg1 arg2 ...

You may also set it as a system property at runtime with System.setProperty(...) if you only need it for this specific file, but in a case like this I think I would prefer the OutputStreamWriter.

By setting the system property you can use FileWriter and expect that it will use UTF-8 as the default encoding for your files. In this case for all the files that you read and write.

EDIT

  • Starting from API 19, you can replace the String "UTF-8" with StandardCharsets.UTF_8

  • As suggested in the comments below by tchrist, if you intend to detect encoding errors in your file you would be forced to use the OutputStreamWriter approach and use the constructor that receives a charset encoder.

    Somewhat like

    CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
    encoder.onMalformedInput(CodingErrorAction.REPORT);
    encoder.onUnmappableCharacter(CodingErrorAction.REPORT);
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("jedis.txt"),encoder));
    

    You may choose between actions IGNORE | REPLACE | REPORT

Also, this question was already answered here.

How do you add an ActionListener onto a JButton in Java

I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?

ngOnInit not being called when Injectable class is Instantiated

I had to call a function once my dataService was initialized, instead, I called it inside the constructor, that worked for me.

Find index of last occurrence of a substring in a string

Try this:

s = 'hello plombier pantin'
print (s.find('p'))
6
print (s.index('p'))
6
print (s.rindex('p'))
15
print (s.rfind('p'))

python replace single backslash with double backslash

Use:

string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\")

Escape the \ character.

Handling Enter Key in Vue.js

This event works to me:

@keyup.enter.native="onEnter".

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

What I did was creating my own Window and Style. Because I like to have control over everything and I didn't want some external libraries just to use a Window from it. I looked at already mentioned MahApps.Metro on GitHub

MahApps

and also very nice Modern UI on GitHub. (.NET4.5 only)

Modern UI

There is one more it's Elysium but I really didn't try this one.

Elysium

The style I did was really easy when I looked how it's done in these. Now I have my own Window and I can do whatever I want with xaml... for me it's the main reason why I did my own. And I made one more for you too :) I should probably say that I wouldn't be able to do it without exploring Modern UI it was great help. I tried to make it look like VS2012 Window. It looks like this.

MyWindow

Here is code (please note that it's targeting .NET4.5)

public class MyWindow : Window
{

    public MyWindow()
    {
        this.CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, this.OnCloseWindow));
        this.CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, this.OnMaximizeWindow, this.OnCanResizeWindow));
        this.CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, this.OnMinimizeWindow, this.OnCanMinimizeWindow));
        this.CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, this.OnRestoreWindow, this.OnCanResizeWindow));
    }

    private void OnCanResizeWindow(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = this.ResizeMode == ResizeMode.CanResize || this.ResizeMode == ResizeMode.CanResizeWithGrip;
    }

    private void OnCanMinimizeWindow(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = this.ResizeMode != ResizeMode.NoResize;
    }

    private void OnCloseWindow(object target, ExecutedRoutedEventArgs e)
    {
        SystemCommands.CloseWindow(this);
    }

    private void OnMaximizeWindow(object target, ExecutedRoutedEventArgs e)
    {
        SystemCommands.MaximizeWindow(this);
    }

    private void OnMinimizeWindow(object target, ExecutedRoutedEventArgs e)
    {
        SystemCommands.MinimizeWindow(this);
    }

    private void OnRestoreWindow(object target, ExecutedRoutedEventArgs e)
    {
        SystemCommands.RestoreWindow(this);
    }
}

And here resources:

<BooleanToVisibilityConverter x:Key="bool2VisibilityConverter" />

<Color x:Key="WindowBackgroundColor">#FF2D2D30</Color>
<Color x:Key="HighlightColor">#FF3F3F41</Color>
<Color x:Key="BlueColor">#FF007ACC</Color>
<Color x:Key="ForegroundColor">#FFF4F4F5</Color>

<SolidColorBrush x:Key="WindowBackgroundColorBrush" Color="{StaticResource WindowBackgroundColor}"/>
<SolidColorBrush x:Key="HighlightColorBrush" Color="{StaticResource HighlightColor}"/>
<SolidColorBrush x:Key="BlueColorBrush" Color="{StaticResource BlueColor}"/>
<SolidColorBrush x:Key="ForegroundColorBrush" Color="{StaticResource ForegroundColor}"/>

<Style x:Key="WindowButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
    <Setter Property="Padding" Value="1" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter x:Name="contentPresenter"
                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                          Margin="{TemplateBinding Padding}"
                          RecognizesAccessKey="True" />
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="{StaticResource HighlightColorBrush}" />
                    </Trigger>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="{DynamicResource BlueColorBrush}" />
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter TargetName="contentPresenter" Property="Opacity" Value=".5" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="MyWindowStyle" TargetType="local:MyWindow">
    <Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
    <Setter Property="Background" Value="{DynamicResource WindowBackgroundBrush}"/>
    <Setter Property="ResizeMode" Value="CanResizeWithGrip" />
    <Setter Property="UseLayoutRounding" Value="True" />
    <Setter Property="TextOptions.TextFormattingMode" Value="Display" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyWindow">
                <Border x:Name="WindowBorder" Margin="{Binding Source={x:Static SystemParameters.WindowNonClientFrameThickness}}" Background="{StaticResource WindowBackgroundColorBrush}">
                    <Grid>
                        <Border BorderThickness="1">
                            <AdornerDecorator>
                                <Grid x:Name="LayoutRoot">
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="25" />
                                        <RowDefinition Height="*" />
                                        <RowDefinition Height="15" />
                                    </Grid.RowDefinitions>
                                    <ContentPresenter Grid.Row="1" Grid.RowSpan="2" Margin="7"/>
                                    <Rectangle x:Name="HeaderBackground" Height="25" Fill="{DynamicResource WindowBackgroundColorBrush}" VerticalAlignment="Top" Grid.Row="0"/>
                                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
                                        <Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
                                            <Button.Content>
                                                <Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
                                                    <Path Data="M0,6 L8,6 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                        Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2"  />
                                                </Grid>
                                            </Button.Content>
                                        </Button>
                                        <Grid Margin="1,0,1,0">
                                            <Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
                                                <Button.Content>
                                                    <Grid Width="30" Height="25" UseLayoutRounding="True" RenderTransform="1,0,0,1,.5,.5">
                                                        <Path Data="M2,0 L8,0 L8,6 M0,3 L6,3 M0,2 L6,2 L6,8 L0,8 Z" Width="8" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                            Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1"  />
                                                    </Grid>
                                                </Button.Content>
                                            </Button>
                                            <Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
                                                <Button.Content>
                                                    <Grid Width="31" Height="25">
                                                        <Path Data="M0,1 L9,1 L9,8 L0,8 Z" Width="9" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                            Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2"  />
                                                    </Grid>
                                                </Button.Content>
                                            </Button>
                                        </Grid>
                                        <Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close"  Style="{StaticResource WindowButtonStyle}">
                                            <Button.Content>
                                                <Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
                                                    <Path Data="M0,0 L8,7 M8,0 L0,7 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                        Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1.5"  />
                                                </Grid>
                                            </Button.Content>
                                        </Button>
                                    </StackPanel>
                                    <TextBlock x:Name="WindowTitleTextBlock" Grid.Row="0" Text="{TemplateBinding Title}" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"  Margin="8 -1 0 0"  FontSize="16"  Foreground="{TemplateBinding Foreground}"/>
                                    <Grid Grid.Row="2">
                                        <Path x:Name="ResizeGrip" Visibility="Collapsed" Width="12" Height="12" Margin="1" HorizontalAlignment="Right"
                                        Stroke="{StaticResource BlueColorBrush}" StrokeThickness="1" Stretch="None" Data="F1 M1,10 L3,10 M5,10 L7,10 M9,10 L11,10 M2,9 L2,11 M6,9 L6,11 M10,9 L10,11 M5,6 L7,6 M9,6 L11,6 M6,5 L6,7 M10,5 L10,7 M9,2 L11,2 M10,1 L10,3" />
                                    </Grid>
                                </Grid>
                            </AdornerDecorator>
                        </Border>
                        <Border BorderBrush="{StaticResource BlueColorBrush}" BorderThickness="1" Visibility="{Binding IsActive, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Converter={StaticResource bool2VisibilityConverter}}" />
                    </Grid>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="WindowState" Value="Maximized">
                        <Setter TargetName="Maximize" Property="Visibility" Value="Collapsed" />
                        <Setter TargetName="Restore" Property="Visibility" Value="Visible" />
                        <Setter TargetName="LayoutRoot" Property="Margin" Value="7" />
                    </Trigger>
                    <Trigger Property="WindowState" Value="Normal">
                        <Setter TargetName="Maximize" Property="Visibility" Value="Visible" />
                        <Setter TargetName="Restore" Property="Visibility" Value="Collapsed" />
                    </Trigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="ResizeMode" Value="CanResizeWithGrip" />
                            <Condition Property="WindowState" Value="Normal" />
                        </MultiTrigger.Conditions>
                        <Setter TargetName="ResizeGrip" Property="Visibility" Value="Visible" />
                    </MultiTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="WindowChrome.WindowChrome">
        <Setter.Value>
            <WindowChrome CornerRadius="0" GlassFrameThickness="1" UseAeroCaptionButtons="False" />
        </Setter.Value>
    </Setter>
</Style>

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

How to get the index of an element in an IEnumerable?

The best way to catch the position is by FindIndex This function is available only for List<>

Example

int id = listMyObject.FindIndex(x => x.Id == 15); 

If you have enumerator or array use this way

int id = myEnumerator.ToList().FindIndex(x => x.Id == 15); 

or

 int id = myArray.ToList().FindIndex(x => x.Id == 15); 

Convert string to BigDecimal in java

May I add something. If you are using currency you should use Scale(2), and you should probably figure out a round method.

multiple classes on single element html

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

Replacing H1 text with a logo image: best method for SEO and accessibility?

For SEO reason:

<div itemscope itemtype="https://schema.org/Organization">
 <p id="logo"><a href="/"><span itemprop="Brand">Your business</span> <span class="icon fa-stg"></span> - <span itemprop="makesOffer">sell staff</span></a></p>
 </div>
   <h1>Your awesome title</h1>

Anaconda Installed but Cannot Launch Navigator

Tried all solutions here but these 2 steps solved the issue:

1) manual update of open-ssl from here: https://slproweb.com/products/Win32OpenSSL.html
2) update OpenSSL using conda update openssl command in the Anaconda Prompt

solved the issue!

With android studio no jvm found, JAVA_HOME has been set

Just delete the folder highlighted below. Depending on your Android Studio version, mine is 3.5 and reopen Android studio.

enter image description here

File size exceeds configured limit (2560000), code insight features not available

For the 64-bit 2020 version

I tried in vain to find the current location of this file for version 2020. When navigating to Help > Edit Custom Properties a new (empty) file is created at appData/Roaming/JetBrains/IntelliJIdea2020.1/idea.properties. There is no /bin directory as some tutorials suggest. However, neither adding the block from the accepted answer to this file nor adding the same file to /bin resulted in an update to my configuration.

I finally discovered that a reference to the same property exists in appData/Roaming/JetBrains/IntelliJIdea2020.1/idea64.exe.vmoptions. It looks like this:

-Didea.max.intellisense.filesize=3470

I changed it to this, which should be adequate for my needs:

-Didea.max.intellisense.filesize=9999

This strikes me as a bug in this version where the behavior of the menu item doesn't reflect what's needed, but it may also be the case that my particular setup is somehow different than stock. I do have PyCharm and the JDK installed.

jQuery function after .append

I know it's not the best solution, but the best practice:

$("#root").append(child);

setTimeout(function(){
  // Action after append
},100);

Which is the correct C# infinite loop, for (;;) or while (true)?

Gasp, use:

while (!false)
{

}

OR as jsight pointed out, you may want to be doubly sure:

while (!false && true)
{
}

Before people yell at me, it's all the same CIL code, I checked :)

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

I had an issue with Page.ClientScript.RegisterStartUpScript - I wasn't using an update panel, but the control was cached. This meant that I had to insert the script into a Literal (or could use a PlaceHolder) so when rendered from the cache the script is included.

A similar solution might work for you.

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

How do we check if a pointer is NULL pointer?

Well, this question was asked and answered way back in 2011, but there is nullptrin C++11. That's all I'm using currently.

You can read more from Stack Overflow and also from this article.

How can I make setInterval also work when a tab is inactive in Chrome?

Heavily influenced by Ruslan Tushov's library, I've created my own small library. Just add the script in the <head> and it will patch setInterval and setTimeout with ones that use WebWorker.

PowerShell Remoting giving "Access is Denied" error

Running the command prompt or Powershell ISE as an administrator fixed this for me.

find files by extension, *.html under a folder in nodejs

You can use Filehound to do this.

For example: find all .html files in /tmp:

const Filehound = require('filehound');

Filehound.create()
  .ext('html')
  .paths("/tmp")
  .find((err, htmlFiles) => {
    if (err) return console.error("handle err", err);

    console.log(htmlFiles);
});

For further information (and examples), check out the docs: https://github.com/nspragg/filehound

Disclaimer: I'm the author.

How to disable mouse right click on a web page?

Try this : write below code on body & feel the magic :)

body oncontextmenu="return false"

Loop through a date range with JavaScript

If startDate and endDate are indeed date objects you could convert them to number of milliseconds since midnight Jan 1, 1970, like this:

var startTime = startDate.getTime(), endTime = endDate.getTime();

Then you could loop from one to another incrementing loopTime by 86400000 (1000*60*60*24) - number of milliseconds in one day:

for(loopTime = startTime; loopTime < endTime; loopTime += 86400000)
{
    var loopDay=new Date(loopTime)
    //use loopDay as you wish
}

How to Call a JS function using OnClick event

You are attempting to attach an event listener function before the element is loaded. Place fun() inside an onload event listener function. Call f1() within this function, as the onclick attribute will be ignored.

function f1() {
    alert("f1 called");
    //form validation that recalls the page showing with supplied inputs.    
}
window.onload = function() {
    document.getElementById("Save").onclick = function fun() {
        alert("hello");
        f1();
        //validation code to see State field is mandatory.  
    }
}

JSFiddle

How to download a Nuget package without nuget.exe or Visual Studio extension?

To obtain the current stable version of the NuGet package use:

https://www.nuget.org/api/v2/package/{packageID}

Google Chrome Full Black Screen

Same thing just happened to me on Google Chrome v22.0.1221.1 (Nvidia GPU). The workaround was to disable GPU compositing on all pages (setting available on chrome://flags/)

If it happens in Chrome version > 45.x, See answer https://stackoverflow.com/a/32955808/293023 by @detale.

Use google-chrome -disable-gpu from the command line to temporary disable gpu.

How to set level logging to DEBUG in Tomcat?

JULI logging levels for Tomcat

SEVERE - Serious failures

WARNING - Potential problems

INFO - Informational messages

CONFIG - Static configuration messages

FINE - Trace messages

FINER - Detailed trace messages

FINEST - Highly detailed trace messages

You can find here more https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/pasoe-admin/tomcat-logging.html

Identify duplicates in a List

java 8 base solution:

List duplicates =    
list.stream().collect(Collectors.groupingBy(Function.identity()))
    .entrySet()
    .stream()
    .filter(e -> e.getValue().size() > 1)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

JavaScript naming conventions

I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase could equally well be used the opposite way, it's just that language users tend to follow the language authors.

having said that, i think most libraries tend to roughly follow a simplification of Java's CamelCase. I find Douglas Crockford advices tasteful enough for me.

A table name as a variable

Use sp_executesql to execute any SQL, e.g.

DECLARE @tbl    sysname,
        @sql    nvarchar(4000),
        @params nvarchar(4000),
        @count  int

DECLARE tblcur CURSOR STATIC LOCAL FOR
   SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
   ORDER  BY 1
OPEN tblcur

WHILE 1 = 1
BEGIN
   FETCH tblcur INTO @tbl
   IF @@fetch_status <> 0
      BREAK

   SELECT @sql =
   N' SELECT @cnt = COUNT(*) FROM dbo.' + quotename(@tbl) +
   N' WHERE LastUpdated BETWEEN @fromdate AND ' +
   N'                           coalesce(@todate, ''99991231'')'
   SELECT @params = N'@fromdate datetime, ' +
                    N'@todate   datetime = NULL, ' +
                    N'@cnt      int      OUTPUT'
   EXEC sp_executesql @sql, @params, '20060101', @cnt = @count OUTPUT

   PRINT @tbl + ': ' + convert(varchar(10), @count) + ' modified rows.'
END

DEALLOCATE tblcur

Pandas: Subtracting two date columns and the result being an integer

Create a vectorized method

def calc_xb_minus_xa(df):
    time_dict = {
        '<Minute>': 'm',
        '<Hour>': 'h',
        '<Day>': 'D',
        '<Week>': 'W',
        '<Month>': 'M',
        '<Year>': 'Y'
    }

    time_delta = df.at[df.index[0], 'end_time'] - df.at[df.index[0], 'open_time']
    offset_base_name = str(to_offset(time_delta).base)
    time_term = time_dict.get(offset_base_name)

    result = (df.end_time - df.open_time) / np.timedelta64(1, time_term)
    return result

Then in your df do:

df['x'] = calc_xb_minus_xa(df)

This will work for minutes, hours, days, weeks, month and Year. open_time and end_time need to change according your df

What is it exactly a BLOB in a DBMS context

They are binary large objects, you can use them to store binary data such as images or serialized objects among other things.

What is the command to exit a Console application in C#?

Several options, by order of most appropriate way:

  1. Return an int from the Program.Main method
  2. Throw an exception and don't handle it anywhere (use for unexpected error situations)
  3. To force termination elsewhere, System.Environment.Exit (not portable! see below)

Edited 9/2013 to improve readability

Returning with a specific exit code: As Servy points out in the comments, you can declare Main with an int return type and return an error code that way. So there really is no need to use Environment.Exit unless you need to terminate with an exit code and can't possibly do it in the Main method. Most probably you can avoid that by throwing an exception, and returning an error code in Main if any unhandled exception propagates there. If the application is multi-threaded you'll probably need even more boilerplate to properly terminate with an exit code so you may be better off just calling Environment.Exit.

Another point against using Evironment.Exit - even when writing multi-threaded applications - is reusability. If you ever want to reuse your code in an environment that makes Environment.Exit irrelevant (such as a library that may be used in a web server), the code will not be portable. The best solution still is, in my opinion, to always use exceptions and/or return values that represent that the method reached some error/finish state. That way, you can always use the same code in any .NET environment, and in any type of application. If you are writing specifically an app that needs to return an exit code or to terminate in a way similar to what Environment.Exit does, you can then go ahead and wrap the thread at the highest level and handle the errors/exceptions as needed.

When to use: Java 8+ interface default method, vs. abstract method

Although its an old question let me give my input on it as well.

  1. abstract class: Inside abstract class we can declare instance variables, which are required to the child class

    Interface: Inside interface every variables is always public static and final we cannot declare instance variables

  2. abstract class: Abstract class can talk about state of object

    Interface: Interface can never talk about state of object

  3. abstract class: Inside Abstract class we can declare constructors

    Interface: Inside interface we cannot declare constructors as purpose of
    constructors is to initialize instance variables. So what is the need of constructor there if we cannot have instance variables in interfaces.

  4. abstract class: Inside abstract class we can declare instance and static blocks

    Interface: Interfaces cannot have instance and static blocks.

  5. abstract class: Abstract class cannot refer lambda expression

    Interfaces: Interfaces with single abstract method can refer lambda expression

  6. abstract class: Inside abstract class we can override OBJECT CLASS methods

    Interfaces: We cannot override OBJECT CLASS methods inside interfaces.

I will end on the note that:

Default method concepts/static method concepts in interface came just to save implementation classes but not to provide meaningful useful implementation. Default methods/static methods are kind of dummy implementation, "if you want you can use them or you can override them (in case of default methods) in implementation class" Thus saving us from implementing new methods in implementation classes whenever new methods in interfaces are added. Therefore interfaces can never be equal to abstract classes.

Android camera intent

Try the following I found here

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == Activity.RESULT_OK && requestCode == 0) {
    String result = data.toURI();
    // ...
  }
}

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

I am a newbie to the iOS app development. I was practising to develop iOS apps from the very beginning and while running a very basic Hello World app, I also faced same issue that only a black blank screen appears after building and running the app in iOS simulator. Somehow while struggling to find out a solution to the problem I accidentally clicked Window-->Scale-->50% in iOS simulator and it did solve my problem. I could then see the Home page with my app and clicking on app icon I was able to run my app successfully. App versions: Xcode 5.1 iOS Simulator: 7.1 OSX: 10.9.3

How to check for empty array in vba macro

I see similar answers on here... but not mine...

This is how I am unfortunatley going to deal with it... I like the len(join(arr)) > 0 approach, but it wouldn't work if the array was an array of emptystrings...

Public Function arrayLength(arr As Variant) As Long
  On Error GoTo handler

  Dim lngLower As Long
  Dim lngUpper As Long

  lngLower = LBound(arr)
  lngUpper = UBound(arr)

  arrayLength = (lngUpper - lngLower) + 1
  Exit Function

handler:
  arrayLength = 0 'error occured.  must be zero length
End Function

C - The %x format specifier

From http://en.wikipedia.org/wiki/Printf_format_string

use 0 instead of spaces to pad a field when the width option is specified. For example, printf("%2d", 3) results in " 3", while printf("%02d", 3) results in "03".

SQL: How to to SUM two values from different tables

you can also try this in sql-server !!

select a.city,a.total + b.total as mytotal from [dbo].[cash] a join [dbo].[cheque] b on a.city=b.city 

demo

or try using sum,union

select sum(total)  as mytotal,city
from
(
    select * from cash union
    select * from cheque
) as vij
group by city 

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

@Janei: my first comment here is about your sample ;)

I think if you do like this, you want to take 4, then applying the sort on these 4.

var dados =  from d in dc.tbl_News.Take(4) 
                orderby d.idNews descending
                select new 
                {
                    d.idNews,
                    d.titleNews,
                    d.textNews,
                    d.dateNews,
                    d.imgNewsThumb
                };

Different than sorting whole tbl_News by idNews descending and then taking 4

var dados =  (from d in dc.tbl_News
                orderby d.idNews descending
                select new 
                {
                    d.idNews,
                    d.titleNews,
                    d.textNews,
                    d.dateNews,
                    d.imgNewsThumb
                }).Take(4);

no ? results may be different.

What is the difference between 'protected' and 'protected internal'?

This table shows the difference. protected internal is the same as protected, except it also allows access from other classes in the same assembly.

Comparison of C# modifiers

Delete all the records

If you want to reset your table, you can do

truncate table TableName

truncate needs privileges, and you can't use it if your table has dependents (another tables that have FK of your table,

Editing specific line in text file in Python

Suppose I have a file named file_name as following:

this is python
it is file handling
this is editing of line

We have to replace line 2 with "modification is done":

f=open("file_name","r+")
a=f.readlines()
for line in f:
   if line.startswith("rai"):
      p=a.index(line)
#so now we have the position of the line which to be modified
a[p]="modification is done"
f.seek(0)
f.truncate() #ersing all data from the file
f.close()
#so now we have an empty file and we will write the modified content now in the file
o=open("file_name","w")
for i in a:
   o.write(i)
o.close()
#now the modification is done in the file

How do I add slashes to a string in Javascript?

if (!String.prototype.hasOwnProperty('addSlashes')) {
    String.prototype.addSlashes = function() {
        return this.replace(/&/g, '&amp;') /* This MUST be the 1st replacement. */
             .replace(/'/g, '&apos;') /* The 4 other predefined entities, required. */
             .replace(/"/g, '&quot;')
             .replace(/\\/g, '\\\\')
             .replace(/</g, '&lt;')
             .replace(/>/g, '&gt;').replace(/\u0000/g, '\\0');
        }
}

Usage: alert(str.addSlashes());

ref: https://stackoverflow.com/a/9756789/3584667

How to use a Bootstrap 3 glyphicon in an html select

I don't think the standard HTML select will display HTML content. I'd suggest checking out Bootstrap select: http://silviomoreto.github.io/bootstrap-select/

It has several options for displaying icons or other HTML markup in the select.

<select id="mySelect" data-show-icon="true">
  <option data-content="<i class='glyphicon glyphicon-cutlery'></i>">-</option>
  <option data-subtext="<i class='glyphicon glyphicon-eye-open'></i>"></option>
  <option data-subtext="<i class='glyphicon glyphicon-heart-empty'></i>"></option>
  <option data-subtext="<i class='glyphicon glyphicon-leaf'></i>"></option>
  <option data-subtext="<i class='glyphicon glyphicon-music'></i>"></option>
  <option data-subtext="<i class='glyphicon glyphicon-send'></i>"></option>
  <option data-subtext="<i class='glyphicon glyphicon-star'></i>"></option>
</select>

Here is a demo: https://www.codeply.com/go/l6ClKGBmLS

Using git to get just the latest revision

Alternate solution to doing shallow clone (git clone --depth=1 <URL>) would be, if remote side supports it, to use --remote option of git archive:

$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Or, if remote repository in question is browse-able using some web interface like gitweb or GitHub, then there is a chance that it has 'snapshot' feature, and you can download latest version (without versioning information) from web interface.

How do you log all events fired by an element in jQuery?

$(element).on("click mousedown mouseup focus blur keydown change",function(e){
     console.log(e);
});

That will get you a lot (but not all) of the information on if an event is fired... other than manually coding it like this, I can't think of any other way to do that.

Use index in pandas to plot data

Try this,

monthly_mean.plot(y='A', use_index=True)

How to initialize a vector of vectors on a struct?

You use new to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.

You have no reason to use new, since A is an automatic variable. You can simply initialise A using its constructor:

vector<vector<int> > A(dimension, vector<int>(dimension));

Use chrome as browser in C#?

1/3/2017 --> January the 3rd 2017

Hi there, today I found this article to achieve this, the article is called "Creating an HTML UI for Desktop .NET Applications" and is intended to embed a chromium based control in a WPF application. It saved me the day.

https://www.infoq.com/articles/html-desktop-net

I hope it helps somebody else.

NOTE: it is based on DotNetBrowser, see license agreement here: https://www.teamdev.com/dotnetbrowser-licence-agreement

How to add an extra language input to Android?

Sliding the space bar only works if you gave more then one input language selected.

In that case the space bar will also indicate the selected language and show arrows to indicate Sliding will change selection.

This is easy fast and changes the dictionary at the same time.

First response seems the mist accurate.

Regards

How to conditionally take action if FINDSTR fails to find a string

In DOS/Windows Batch most commands return an exitCode, called "errorlevel", that is a value that customarily is equal to zero if the command ends correctly, or a number greater than zero if ends because an error, with greater numbers for greater errors (hence the name).

There are a couple methods to check that value, but the original one is:

IF ERRORLEVEL value command

Previous IF test if the errorlevel returned by the previous command was GREATER THAN OR EQUAL the given value and, if this is true, execute the command. For example:

verify bad-param
if errorlevel 1 echo Errorlevel is greater than or equal 1
echo The value of errorlevel is: %ERRORLEVEL%

Findstr command return 0 if the string was found and 1 if not:

CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y

Previous code will copy the file if the string was NOT found in the file.

CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF NOT ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y

Previous code copy the file if the string was found. Try this:

findstr "string" file
if errorlevel 1 (
    echo String NOT found...
) else (
    echo String found
)

SELECT INTO a table variable in T-SQL

Try something like this:

DECLARE @userData TABLE(
    name varchar(30) NOT NULL,
    oldlocation varchar(30) NOT NULL
);

INSERT INTO @userData (name, oldlocation)
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;

Tar archiving that takes input from a list of files

Some versions of tar, for example, the default versions on HP-UX (I tested 11.11 and 11.31), do not include a command line option to specify a file list, so a decent work-around is to do this:

tar cvf allfiles.tar $(cat mylist.txt)

UIView Infinite 360 degree rotation animation?

There are following different ways to perform 360 degree animation with UIView.

Using CABasicAnimation

var rotationAnimation = CABasicAnimation()
rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: (Double.pi))
rotationAnimation.duration = 1.0
rotationAnimation.isCumulative = true
rotationAnimation.repeatCount = 100.0
view.layer.add(rotationAnimation, forKey: "rotationAnimation")


Here is an extension functions for UIView that handles start & stop rotation operations:

extension UIView {

    // Start rotation
    func startRotation() {
        let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.fromValue = 0
        rotation.toValue = NSNumber(value: Double.pi)
        rotation.duration = 1.0
        rotation.isCumulative = true
        rotation.repeatCount = FLT_MAX
        self.layer.add(rotation, forKey: "rotationAnimation")
    }

    // Stop rotation
    func stopRotation() {
        self.layer.removeAnimation(forKey: "rotationAnimation")
    }
}


Now using, UIView.animation closure:

UIView.animate(withDuration: 0.5, animations: { 
      view.transform = CGAffineTransform(rotationAngle: (CGFloat(Double.pi)) 
}) { (isAnimationComplete) in
    // Animation completed 
}

Method to get all files within folder and subfolders that will return a list

you can use something like this :

string [] filePaths = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);

instead of using "." you can type the name of the file or just the type like "*.txt" also SearchOption.AllDirectories is to search in all subfolders you can change that if you only want one level more about how to use it on here

Exit a Script On Error

If you want to be able to handle an error instead of blindly exiting, instead of using set -e, use a trap on the ERR pseudo signal.

#!/bin/bash
f () {
    errorCode=$? # save the exit code as the first thing done in the trap function
    echo "error $errorCode"
    echo "the command executing at the time of the error was"
    echo "$BASH_COMMAND"
    echo "on line ${BASH_LINENO[0]}"
    # do some error handling, cleanup, logging, notification
    # $BASH_COMMAND contains the command that was being executed at the time of the trap
    # ${BASH_LINENO[0]} contains the line number in the script of that command
    # exit the script or return to try again, etc.
    exit $errorCode  # or use some other value or do return instead
}
trap f ERR
# do some stuff
false # returns 1 so it triggers the trap
# maybe do some other stuff

Other traps can be set to handle other signals, including the usual Unix signals plus the other Bash pseudo signals RETURN and DEBUG.

Insert a row to pandas dataframe

One way to achieve this is

>>> pd.DataFrame(np.array([[2, 3, 4]]), columns=['A', 'B', 'C']).append(df, ignore_index=True)
Out[330]: 
   A  B  C
0  2  3  4
1  5  6  7
2  7  8  9

Generally, it's easiest to append dataframes, not series. In your case, since you want the new row to be "on top" (with starting id), and there is no function pd.prepend(), I first create the new dataframe and then append your old one.

ignore_index will ignore the old ongoing index in your dataframe and ensure that the first row actually starts with index 1 instead of restarting with index 0.

Typical Disclaimer: Cetero censeo ... appending rows is a quite inefficient operation. If you care about performance and can somehow ensure to first create a dataframe with the correct (longer) index and then just inserting the additional row into the dataframe, you should definitely do that. See:

>>> index = np.array([0, 1, 2])
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[0:1] = [list(s1), list(s2)]
>>> df2
Out[336]: 
     A    B    C
0    5    6    7
1    7    8    9
2  NaN  NaN  NaN
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[1:] = [list(s1), list(s2)]

So far, we have what you had as df:

>>> df2
Out[339]: 
     A    B    C
0  NaN  NaN  NaN
1    5    6    7
2    7    8    9

But now you can easily insert the row as follows. Since the space was preallocated, this is more efficient.

>>> df2.loc[0] = np.array([2, 3, 4])
>>> df2
Out[341]: 
   A  B  C
0  2  3  4
1  5  6  7
2  7  8  9

SQL GROUP BY CASE statement with aggregate function

I think the answer is pretty simple (unless I'm missing something?)

SELECT    
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END AS some_product
FROM some_table
GROUP BY
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END

You can put the CASE STATEMENT in the GROUP BY verbatim (minus the alias column name)

android - listview get item view by position

Preferred way to change the appearance/whatever of row views once the ListView is drawn is to change something in the data ListView draws from (the array of objects that is passed into your Adapter) and make sure to account for that in your getView() function, then redraw the ListView by calling

notifyDataSetChanged();

EDIT: while there is a way to do this, if you need to do this chances are doing something wrong. While are few edge cases I can think about, generally using notifyDataSetChanged() and other built in mechanisms is a way to go.

EDIT 2: One of the common mistakes people make is trying to come up with their own way to respond to user clicking/selecting a row in the ListView, as in one of the comments to this post. There is an existing way to do this. Here's how:

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    /* Parameters
    parent:     The AdapterView where the click happened.
    view:       The view within the AdapterView that was clicked (this will be a view provided by the adapter)
    position:   The position of the view in the adapter.
    id:         The row id of the item that was clicked. */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //your code here
    }
});

ListView has a lot of build-in functionality and there is no need to reinvent the wheel for simpler cases. Since ListView extends AdapterView, you can set the same Listeners, such as OnItemClickListener as in the example above.

Integer value in TextView

TextView tv = new TextView(this);
tv.setText("" + 4);

how to use the Box-Cox power transformation in R

Box and Cox (1964) suggested a family of transformations designed to reduce nonnormality of the errors in a linear model. In turns out that in doing this, it often reduces non-linearity as well.

Here is a nice summary of the original work and all the work that's been done since: http://www.ime.usp.br/~abe/lista/pdfm9cJKUmFZp.pdf

You will notice, however, that the log-likelihood function governing the selection of the lambda power transform is dependent on the residual sum of squares of an underlying model (no LaTeX on SO -- see the reference), so no transformation can be applied without a model.

A typical application is as follows:

library(MASS)

# generate some data
set.seed(1)
n <- 100
x <- runif(n, 1, 5)
y <- x^3 + rnorm(n)

# run a linear model
m <- lm(y ~ x)

# run the box-cox transformation
bc <- boxcox(y ~ x)

enter image description here

(lambda <- bc$x[which.max(bc$y)])
[1] 0.4242424

powerTransform <- function(y, lambda1, lambda2 = NULL, method = "boxcox") {

  boxcoxTrans <- function(x, lam1, lam2 = NULL) {

    # if we set lambda2 to zero, it becomes the one parameter transformation
    lam2 <- ifelse(is.null(lam2), 0, lam2)

    if (lam1 == 0L) {
      log(y + lam2)
    } else {
      (((y + lam2)^lam1) - 1) / lam1
    }
  }

  switch(method
         , boxcox = boxcoxTrans(y, lambda1, lambda2)
         , tukey = y^lambda1
  )
}


# re-run with transformation
mnew <- lm(powerTransform(y, lambda) ~ x)

# QQ-plot
op <- par(pty = "s", mfrow = c(1, 2))
qqnorm(m$residuals); qqline(m$residuals)
qqnorm(mnew$residuals); qqline(mnew$residuals)
par(op)

enter image description here

As you can see this is no magic bullet -- only some data can be effectively transformed (usually a lambda less than -2 or greater than 2 is a sign you should not be using the method). As with any statistical method, use with caution before implementing.

To use the two parameter Box-Cox transformation, use the geoR package to find the lambdas:

library("geoR")
bc2 <- boxcoxfit(x, y, lambda2 = TRUE)

lambda1 <- bc2$lambda[1]
lambda2 <- bc2$lambda[2]

EDITS: Conflation of Tukey and Box-Cox implementation as pointed out by @Yui-Shiuan fixed.

How to unlock android phone through ADB

if the device is locked with black screen run the following:

  1. adb shell input keyevent 26 - this will turn screen on
  2. adb shell input keyevent 82 - this will unlock and ask for pin
  3. adb shell input text xxxx && adb shell input keyevent 66 - this will input your pin and press enter, unlocking device to home screen

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

My issue was I was instatiating the player completely from start but I used an iframe instead of a wrapper div.

How do I get formatted JSON in .NET using C#?

Shortest version to prettify existing JSON: (edit: using JSON.net)

JToken.Parse("mystring").ToString()

Input:

{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}

Output:

{
  "menu": {
    "id": "file",
    "value": "File",
    "popup": {
      "menuitem": [
        {
          "value": "New",
          "onclick": "CreateNewDoc()"
        },
        {
          "value": "Open",
          "onclick": "OpenDoc()"
        },
        {
          "value": "Close",
          "onclick": "CloseDoc()"
        }
      ]
    }
  }
}

To pretty-print an object:

JToken.FromObject(myObject).ToString()

Rotating a two-dimensional array in Python

That's a clever bit.

First, as noted in a comment, in Python 3 zip() returns an iterator, so you need to enclose the whole thing in list() to get an actual list back out, so as of 2020 it's actually:

list(zip(*original[::-1]))

Here's the breakdown:

  • [::-1] - makes a shallow copy of the original list in reverse order. Could also use reversed() which would produce a reverse iterator over the list rather than actually copying the list (more memory efficient).
  • * - makes each sublist in the original list a separate argument to zip() (i.e., unpacks the list)
  • zip() - takes one item from each argument and makes a list (well, a tuple) from those, and repeats until all the sublists are exhausted. This is where the transposition actually happens.
  • list() converts the output of zip() to a list.

So assuming you have this:

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

You first get this (shallow, reversed copy):

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

Next each of the sublists is passed as an argument to zip:

zip([7, 8, 9], [4, 5, 6], [1, 2, 3])

zip() repeatedly consumes one item from the beginning of each of its arguments and makes a tuple from it, until there are no more items, resulting in (after it's converted to a list):

[(7, 4, 1), 
 (8, 5, 2), 
 (9, 6, 3)]

And Bob's your uncle.

To answer @IkeMiguel's question in a comment about rotating it in the other direction, it's pretty straightforward: you just need to reverse both the sequences that go into zip and the result. The first can be achieved by removing the [::-1] and the second can be achieved by throwing a reversed() around the whole thing. Since reversed() returns an iterator over the list, we will need to put list() around that to convert it. With a couple extra list() calls to convert the iterators to an actual list. So:

rotated = list(reversed(list(zip(*original))))

We can simplify that a bit by using the "Martian smiley" slice rather than reversed()... then we don't need the outer list():

rotated = list(zip(*original))[::-1]

Of course, you could also simply rotate the list clockwise three times. :-)

Load image from url

add Internet permission in manifest

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

than create methode as below,

 public static Bitmap getBitmapFromURL(String src) {
    try {
        Log.e("src", src);
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        Log.e("Bitmap", "returned");
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("Exception", e.getMessage());
        return null;
    }
}

now add this in your onCreate method,

 ImageView img_add = (ImageView) findViewById(R.id.img_add);


img_add.setImageBitmap(getBitmapFromURL("http://www.deepanelango.me/wpcontent/uploads/2017/06/noyyal1.jpg"));

this is works for me.

'NOT LIKE' in an SQL query

You have missed out the field name id in the second NOT LIKE. Try:

SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'

The AND in the where clause joins 2 full condition expressions such as id NOT LIKE '1%' and can't be used to list multiple values that the id is 'not like'.

Regarding 'main(int argc, char *argv[])'

argc is the number of command line arguments given to the program at runtime, and argv is an array of arrays of characters (rather, an array of C-strings) containing these arguments. If you know you're not going to need the command line arguments, you can declare your main at taking a void argument, instead:

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

Those are the only two prototypes defined for main as per the standards, but some compilers allow a return type of void as well. More on this on Wikipedia.

Before and After Suite execution hook in jUnit 4.x

The only way I think then to get the functionality you want would be to do something like

import junit.framework.Test;  
import junit.framework.TestResult;  
import junit.framework.TestSuite;  

public class AllTests {  
    public static Test suite() {  
        TestSuite suite = new TestSuite("TestEverything");  
        //$JUnit-BEGIN$  
        suite.addTestSuite(TestOne.class);  
        suite.addTestSuite(TestTwo.class);  
        suite.addTestSuite(TestThree.class);  
        //$JUnit-END$  
     }  

     public static void main(String[] args)  
     {  
        AllTests test = new AllTests();  
        Test testCase = test.suite();  
        TestResult result = new TestResult();  
        setUp();  
        testCase.run(result);  
        tearDown();  
     }  
     public void setUp() {}  
     public void tearDown() {}  
} 

I use something like this in eclipse, so I'm not sure how portable it is outside of that environment

How to determine whether an object has a given property in JavaScript

const data = [{"b":1,"c":100},{"a":1,"b":1,"c":150},{"a":1,"b":2,"c":100},{"a":2,"b":1,"c":13}]

const result = data.reduce((r, e)  => {
  r['a'] += (e['a'] ? e['a'] : 0)
    r['d'] += (e['b'] ? e['b'] : 0)
  r['c'] += (e['c'] ? e['c'] : 0)

  return r
}, {'a':0, 'd':0, 'c':0})

console.log(result)
`result` { a: 4, d: 5, c: 363 }

'JSON' is undefined error in JavaScript in Internet Explorer

<!DOCTYPE html>

Otherwise IE8 is not acting right. Also you should use:

<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />

Why does sed not replace all occurrences?

You should add the g modifier so that sed performs a global substitution of the contents of the pattern buffer:

echo dog dog dos | sed -e 's:dog:log:g'

For a fantastic documentation on sed, check http://www.grymoire.com/Unix/Sed.html. This global flag is explained here: http://www.grymoire.com/Unix/Sed.html#uh-6

The official documentation for GNU sed is available at http://www.gnu.org/software/sed/manual/

How to change the text color of first select option

If the first item is to be used as a placeholder (empty value) and your select is required then you can use the :invalid pseudo-class to target it.

_x000D_
_x000D_
select {_x000D_
  -webkit-appearance: menulist-button;_x000D_
  color: black;_x000D_
}_x000D_
_x000D_
select:invalid {_x000D_
  color: green;_x000D_
}
_x000D_
<select required>_x000D_
  <option value="">Item1</option>_x000D_
  <option value="Item2">Item2</option>_x000D_
  <option value="Item3">Item3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How do I generate random integers within a specific range in Java?

Following code could be used:

ThreadLocalRandom.current().nextInt(rangeStart, rangeEndExclusive)

Set LIMIT with doctrine 2?

$limit=5; // for exemple

$query = $this->getDoctrine()->getEntityManager()->createQuery(
           '// your request')

->setMaxResults($limit);

 $results = $query->getResult();

// Done

css to make bootstrap navbar transparent

Just leaving the default navbar built in with bootstrap works fine.
You just need to add the custom css below, that way everything still works as it should.

HTML:

<nav class="navbar navbar-default">

CSS:

.navbar-default {
    background-color: transparent;
}

Can't choose class as main class in IntelliJ

The documentation you linked actually has the answer in the link associated with the "Java class located out of the source root." Configure your source and test roots and it should work.

https://www.jetbrains.com/idea/webhelp/configuring-content-roots.html

Since you stated that these are tests you should probably go with them marked as Test Source Root instead of Source Root.

Check if a temporary table exists and delete if it exists before creating a temporary table

pmac72 is using GO to break down the query into batches and using an ALTER.

You appear to be running the same batch but running it twice after changing it: DROP... CREATE... edit... DROP... CREATE..

Perhaps post your exact code so we can see what is going on.

How to give the background-image path in CSS?

you can also add inline css for adding image as a background as per below example

<div class="item active" style="background-image: url(../../foo.png);">

Threads vs Processes in Linux

I'd have to agree with what you've been hearing. When we benchmark our cluster (xhpl and such), we always get significantly better performance with processes over threads. </anecdote>

Call method when home button pressed

It took me almost a month to get through this. Just now I solved this issue. In your activity's onPause() you have to include the following if condition:

    if (this.isFinishing()){
        //Insert your finishing code here
    }

The function isFinishing() returns a boolean. True if your App is actually closing, False if your app is still running but for example the screen turns off.

Hope it helps!

Refreshing all the pivot tables in my excel workbook with a macro

Yes.

ThisWorkbook.RefreshAll

Or, if your Excel version is old enough,

Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
    For Each Pivot in Sheet.PivotTables
        Pivot.RefreshTable
        Pivot.Update
    Next
Next

How to set array length in c# dynamically

Does is need to be an array? If you use an ArrayList or one of the other objects available in C#, you won't have this limitation to content with. Hashtable, IDictionnary, IList, etc.. all allow a dynamic number of elements.

How to tell git to use the correct identity (name and email) for a given project?

You need to use the local set command below:

local set

git config user.email [email protected]
git config user.name 'Mahmoud Zalt'

local get

git config --get user.email
git config --get user.name

The local config file is in the project directory: .git/config.

global set

git config --global user.email [email protected]
git config --global user.name 'Mahmoud Zalt'

global get

git config --global --get user.email
git config --global --get user.name

The global config file in in your home directory: ~/.gitconfig.

Remember to quote blanks, etc, for example: 'FirstName LastName'

Installing PHP Zip Extension

On Amazon Linux 2 and PHP 7.4 I finally got PHP-ZIP to install and I hope it helps someone else - by the following (note the yum install command has extra common modules also included you may not need them all):

sudo yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

sudo yum -y install https://rpms.remirepo.net/enterprise/remi-release-7.rpm

sudo yum -y install yum-utils

sudo yum-config-manager --enable remi-php74

sudo yum update

sudo yum install php php-cli php-fpm php-mysqlnd php-zip php-devel php-gd php-mcrypt php-mbstring php-curl php-xml php-pear php-bcmath php-json

sudo pecl install zip

php --modules

sudo systemctl restart httpd

How to install PHP intl extension in Ubuntu 14.04

you could search with aptitude search intl after you can choose the right one, for example sudo aptitude install php-intl and finally sudo service apache2 restart

good Luck!

Close Window from ViewModel

You may treat window as a service (eg. UI service) and pass itself to viewmodel via an interface, as such:

public interface IMainWindowAccess
{
    void Close(bool result);
}

public class MainWindow : IMainWindowAccess
{
    // (...)
    public void Close(bool result)
    {
        DialogResult = result;
        Close();
    }
}

public class MainWindowViewModel
{
    private IMainWindowAccess access;

    public MainWindowViewModel(IMainWindowAccess access)
    {
        this.access = access;
    }

    public void DoClose()
    {
        access.Close(true);
    }
}

This solution have most upsides of passing the view itself to viewmodel without having downside of breaking MVVM, because though physically view is passed to viewmodel, the latter still don't know about the former, it sees only some IMainWindowAccess. So for instance if we wanted to migrate this solution to other platform, it would be only a matter of implementing IMainWindowAccess properly for, say, an Activity.

I'm posting the solution here to propose a different approach than events (though it's actually very similar), because it seems a little bit simpler than events to implement (attaching/detaching etc.), but still aligns nicely with MVVM pattern.

How do I set up Eclipse/EGit with GitHub?

Install Mylyn connector for GitHub from this update site, it provides great integration: you can directly import your repositories using Import > Projects from Git > GitHub. You can set the default repository folder in Preferences > Git.

How do I remove the old history from a git repository?

  1. remove git data, rm .git
  2. git init
  3. add a git remote
  4. force push

How can I include a YAML file inside another?

Includes are not directly supported in YAML as far as I know, you will have to provide a mechanism yourself however, this is generally easy to do.

I have used YAML as a configuration language in my python apps, and in this case often define a convention like this:

>>> main.yml <<<
includes: [ wibble.yml, wobble.yml]

Then in my (python) code I do:

import yaml
cfg = yaml.load(open("main.yml"))
for inc in cfg.get("includes", []):
   cfg.update(yaml.load(open(inc)))

The only down side is that variables in the includes will always override the variables in main, and there is no way to change that precedence by changing where the "includes: statement appears in the main.yml file.

On a slightly different point, YAML doesn't support includes as its not really designed as as exclusively as a file based mark up. What would an include mean if you got it in a response to an AJAX request?

Replace non-ASCII characters with a single space

For you the get the most alike representation of your original string I recommend the unidecode module:

from unidecode import unidecode
def remove_non_ascii(text):
    return unidecode(unicode(text, encoding = "utf-8"))

Then you can use it in a string:

remove_non_ascii("Ceñía")
Cenia

HttpClient - A task was cancelled?

var clientHttp = new HttpClient();
clientHttp.Timeout = TimeSpan.FromMinutes(30);

The above is the best approach for waiting on a large request. You are confused about 30 minutes; it's random time and you can give any time that you want.

In other words, request will not wait for 30 minutes if they get results before 30 minutes. 30 min means request processing time is 30 min. When we occurred error "Task was cancelled", or large data request requirements.

How do I prevent CSS inheritance?

Wrapping with iframe makes parent css obsolete.

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

import java.util.concurrent.TimeUnit;

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {

    private String source;

    @Setup
    public void init() {
        source = "MALE";
    }

    @Benchmark
    public String substring() {
        return source.substring(0, 1);
    }

    @Benchmark
    public String indexOf() {
        return String.valueOf(source.indexOf(0));
    }
}

Results:

+----------------------------------------------------------------------+
| Benchmark                           Mode  Cnt   Score   Error  Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf    avgt    5  23.777 ? 5.788  ns/op |
| StringFirstCharBenchmark.substring  avgt    5  11.305 ? 1.411  ns/op |
+----------------------------------------------------------------------+

Are members of a C++ struct initialized to 0 by default?

I believe the correct answer is that their values are undefined. Often, they are initialized to 0 when running debug versions of the code. This is usually not the case when running release versions.

Auto increment in MongoDB to store sequence of Unique User ID

The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:

var array = db.CollectionName.find({}).sort({ _id: -1 }).limit(1).toArray(); var max = max.length?max[0]+1:1;

Even if an User ID is deleted, this wont create duplicate

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

A JOIN With Additional Conditions Using Query Builder or Eloquent

The sql query sample like this

LEFT JOIN bookings  
    ON rooms.id = bookings.room_type_id
    AND (bookings.arrival = ?
        OR bookings.departure = ?)

Laravel join with multiple conditions

->leftJoin('bookings', function($join) use ($param1, $param2) {
    $join->on('rooms.id', '=', 'bookings.room_type_id');
    $join->on(function($query) use ($param1, $param2) {
        $query->on('bookings.arrival', '=', $param1);
        $query->orOn('departure', '=',$param2);
    });
})

How to get row data by clicking a button in a row in an ASP.NET gridview

<asp:TemplateField>
   <ItemTemplate>
  <asp:LinkButton runat="server" ID="LnKB" Text='edit' OnClick="LnKB_Click"   > 
 </asp:LinkButton>
 </ItemTemplate>
</asp:TemplateField>

  protected void LnKB_Click(object sender, System.EventArgs e)
  {
        LinkButton lb = sender as LinkButton;

        GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
        int x = clickedRow.RowIndex;
        int id = Convert.ToInt32(yourgridviewname.Rows[x].Cells[0].Text);
        lbl.Text = yourgridviewname.Rows[x].Cells[2].Text; 
   }

How to grep a string in a directory and all its subdirectories?

If your grep supports -R, do:

grep -R 'string' dir/

If not, then use find:

find dir/ -type f -exec grep -H 'string' {} +

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

What is the best way to use a HashMap in C++?

Evidence that std::unordered_map uses a hash map in GCC stdlibc++ 6.4

This was mentioned at: https://stackoverflow.com/a/3578247/895245 but in the following answer: What data structure is inside std::map in C++? I have given further evidence of such for the GCC stdlibc++ 6.4 implementation by:

  • GDB step debugging into the class
  • performance characteristic analysis

Here is a preview of the performance characteristic graph described in that answer:

enter image description here

How to use a custom class and hash function with unordered_map

This answer nails it: C++ unordered_map using a custom class type as the key

Excerpt: equality:

struct Key
{
  std::string first;
  std::string second;
  int         third;

  bool operator==(const Key &other) const
  { return (first == other.first
            && second == other.second
            && third == other.third);
  }
};

Hash function:

namespace std {

  template <>
  struct hash<Key>
  {
    std::size_t operator()(const Key& k) const
    {
      using std::size_t;
      using std::hash;
      using std::string;

      // Compute individual hash values for first,
      // second and third and combine them using XOR
      // and bit shifting:

      return ((hash<string>()(k.first)
               ^ (hash<string>()(k.second) << 1)) >> 1)
               ^ (hash<int>()(k.third) << 1);
    }
  };

}

Understanding inplace=True

The way I use it is

# Have to assign back to dataframe (because it is a new copy)
df = df.some_operation(inplace=False) 

Or

# No need to assign back to dataframe (because it is on the same copy)
df.some_operation(inplace=True)

CONCLUSION:

 if inplace is False
      Assign to a new variable;
 else
      No need to assign

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

The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1.


Just for completeness:

x += y is not always doing an in-place operation, there are (at least) three exceptions:

  • If x doesn't implement an __iadd__ method then the x += y statement is just a shorthand for x = x + y. This would be the case if x was something like an int.

  • If __iadd__ returns NotImplemented, Python falls back to x = x + y.

  • The __iadd__ method could theoretically be implemented to not work in place. It'd be really weird to do that, though.

As it happens your bs are numpy.ndarrays which implements __iadd__ and return itself so your second loop modifies the original array in-place.

You can read more on this in the Python documentation of "Emulating Numeric Types".

These [__i*__] methods are called to implement the augmented arithmetic assignments (+=, -=, *=, @=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y) . Otherwise, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y. In certain situations, augmented assignment can result in unexpected errors (see Why does a_tuple[i] += ["item"] raise an exception when the addition works?), but this behavior is in fact part of the data model.

INSERT SELECT statement in Oracle 11G

for inserting data into table you can write

insert into tablename values(column_name1,column_name2,column_name3);

but write the column_name in the sequence as per sequence in table ...

Replace multiple strings at once

You could use the replace method of the String object with a function in the second parameter:

First Method (using a find and replace Object)

var findreplace = {"<" : "&lt;", ">" : "&gt;", "\n" : "<br/>"};

textarea = textarea.replace(new RegExp("(" + Object.keys(findreplace).map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return findreplace[s]});

jsfiddle

Second method (using two arrays, find and replace)

var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];

textarea = textarea.replace(new RegExp("(" + find.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return replace[find.indexOf(s)]});

jsfiddle

Desired function:

function str_replace($f, $r, $s){
   return $s.replace(new RegExp("(" + $f.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return $r[$f.indexOf(s)]});
}

$textarea = str_replace($find, $replace, $textarea);

EDIT

This function admits a String or an Array as parameters:

function str_replace($f, $r, $s){
    return $s.replace(new RegExp("(" + (typeof($f) === "string" ? $f.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&") : $f.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|")) + ")", "g"), typeof($r) === "string" ? $r : typeof($f) === "string" ? $r[0] : function(i){ return $r[$f.indexOf(i)]});
}

Detect whether there is an Internet connection available on Android

I check for both Wi-fi and Mobile internet as follows...

private boolean haveNetworkConnection() {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;
    }
    return haveConnectedWifi || haveConnectedMobile;
}

Obviously, It could easily be modified to check for individual specific connection types, e.g., if your app needs the potentially higher speeds of Wi-fi to work correctly etc.

Function overloading in Python: Missing

As unwind noted, keyword arguments with default values can go a long way.

I'll also state that in my opinion, it goes against the spirit of Python to worry a lot about what types are passed into methods. In Python, I think it's more accepted to use duck typing -- asking what an object can do, rather than what it is.

Thus, if your method may accept a string or a tuple, you might do something like this:

def print_names(names):
    """Takes a space-delimited string or an iterable"""
    try:
        for name in names.split(): # string case
            print name
    except AttributeError:
        for name in names:
            print name

Then you could do either of these:

print_names("Ryan Billy")
print_names(("Ryan", "Billy"))

Although an API like that sometimes indicates a design problem.

concatenate variables

Note that if strings has spaces then quotation marks are needed at definition and must be chopped while concatenating:

rem The retail files set
set FILES_SET="(*.exe *.dll"

rem The debug extras files set
set DEBUG_EXTRA=" *.pdb"

rem Build the DEBUG set without any
set FILES_SET=%FILES_SET:~1,-1%%DEBUG_EXTRA:~1,-1%

rem Append the closing bracket
set FILES_SET=%FILES_SET%)

echo %FILES_SET%

Cheers...

What's the best way to store Phone number in Django models

You might actually look into the internationally standardized format E.164, recommended by Twilio for example (who have a service and an API for sending SMS or phone-calls via REST requests).

This is likely to be the most universal way to store phone numbers, in particular if you have international numbers work with.

1. Phone by PhoneNumberField

You can use phonenumber_field library. It is port of Google's libphonenumber library, which powers Android's phone number handling https://github.com/stefanfoulis/django-phonenumber-field

In model:

from phonenumber_field.modelfields import PhoneNumberField

class Client(models.Model, Importable):
    phone = PhoneNumberField(null=False, blank=False, unique=True)

In form:

from phonenumber_field.formfields import PhoneNumberField
class ClientForm(forms.Form):
    phone = PhoneNumberField()

Get phone as string from object field:

    client.phone.as_e164 

Normolize phone string (for tests and other staff):

    from phonenumber_field.phonenumber import PhoneNumber
    phone = PhoneNumber.from_string(phone_number=raw_phone, region='RU').as_e164

2. Phone by regexp

One note for your model: E.164 numbers have a max character length of 15.

To validate, you can employ some combination of formatting and then attempting to contact the number immediately to verify.

I believe I used something like the following on my django project:

class ReceiverForm(forms.ModelForm):
    phone_number = forms.RegexField(regex=r'^\+?1?\d{9,15}$', 
                                error_message = ("Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."))

EDIT

It appears that this post has been useful to some folks, and it seems worth it to integrate the comment below into a more full-fledged answer. As per jpotter6, you can do something like the following on your models as well:

models.py:

from django.core.validators import RegexValidator

class PhoneModel(models.Model):
    ...
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list

PHP list of specific files in a directory

You should use glob.

glob('*.xml')

More about using glob and advanced filtering:

http://domexception.blogspot.fi/2013/08/php-using-functional-programming-for.html

How to cancel a local git commit

Use below command:

$ git reset HEAD~1

After this you also able to view files what revert back like below response.

Unstaged changes after reset:
M   application/config/config.php
M   application/config/database.php

Is there a way to compile node.js source files?

javascript does not not have a compiler like for example Java/C(You can compare it more to languages like PHP for example). If you want to write compiled code you should read the section about addons and learn C. Although this is rather complex and I don't think you need to do this but instead just write javascript.

Save the plots into a PDF

Never mind got the way to do it.

def plotGraph(X,Y):
     fignum = random.randint(0,sys.maxint)
     fig = plt.figure(fignum)
     ### Plotting arrangements ###
     return fig

------ plotting module ------

----- mainModule ----

 import matplotlib.pyplot as plt
 ### tempDLStats, tempDLlabels are the argument
 plot1 = plotGraph(tempDLstats, tempDLlabels)
 plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
 plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
 plt.show()
 plot1.savefig('plot1.png')
 plot2.savefig('plot2.png')
 plot3.savefig('plot3.png')

----- mainModule -----

difference between primary key and unique key

Unique key :- It should be used when you have to give unique value.In the case of unique key it means null values are also allowed.Unique keys are those keys which are unique and non similar in that column like for example your pet name.it can be nothing like null and if you are asking in context of database then it must be noted that every null is different from another null in the database.EXCEPT-SQL Server where null=null is true


primary key :- It should be used when you have to give uniquely identify a row.primary is key which unique for every row in a database constraint is that it doesn't allow null in it.so, you might have seen that the database have a column which is auto increment and it is the primary key of the table. plus it can be used as a foreign key in another table.example can be orderId on a order Table,billId in a bill Table.

now coming back to situation when to use it:-

1) primary key in the column which can not be null in the table and you are using as foreign key in another table for creating relationship

2) unique key in table where it doesn't affect in table or in the whole database whether you take the null for the particular column like snacks in the restaurant it is possible you don't take snacks in a restaurant

How to install APK from PC?

Just connect the device to the PC with a USB cable, then copy the .apk file to the device. On the device, touch the APK file in the file explorer to install it.

You could also offer the .apk on your website. People can download it, then touch it to install.

Relative path in HTML

The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.

If the URL of your website is: http://www.example.com/mywebsite/ then starting at the root level starts above the "mywebsite" folder path.

regular expression for anything but an empty string

^(?!\s*$).+

will match any string that contains at least one non-space character.

So

if (Regex.IsMatch(subjectString, @"^(?!\s*$).+")) {
    // Successful match
} else {
    // Match attempt failed
}

should do this for you.

^ anchors the search at the start of the string.

(?!\s*$), a so-called negative lookahead, asserts that it's impossible to match only whitespace characters until the end of the string.

.+ will then actually do the match. It will match anything (except newline) up to the end of the string. If you want to allow newlines, you'll have to set the RegexOptions.Singleline option.


Left over from the previous version of your question:

^\s*$

matches strings that contain only whitespace (or are empty).

The exact opposite:

^\S+$

matches only strings that consist of only non-whitespace characters, one character minimum.

How to submit a form when the return key is pressed?

Since display: none buttons and inputs won't work in Safari and IE, I found that the easiest way, requiring no extra javascript hacks, is to simply add an absolutely positioned <button /> to the form and place it far off screen.

<form action="" method="get">
  <input type="text" name="name" />
  <input type="password" name="password" />
  <div class="yourCustomDiv"/>
  <button style="position:absolute;left:-10000px;right:9990px"/>
</form>

This works in the current version of all major browsers as of September 2016.

Obviously its reccomended (and more semantically correct) to just style the <button/> as desired.

How to add a default include path for GCC in Linux?

A gcc spec file can do the job, however all users on the machine will be affected.

See here

JUnit Testing Exceptions

An adventage of use ExpectedException Rule (version 4.7) is that you can test exception message and not only the expected exception.

And using Matchers, you can test the part of message you are interested:

exception.expectMessage(containsString("income: -1000.0"));

Laravel Eloquent "WHERE NOT IN"

You can use this example for dynamically calling the Where NOT IN

$user = User::where('company_id', '=', 1)->select('id)->get()->toArray();

$otherCompany = User::whereNotIn('id', $user)->get();

docker container ssl certificates

I am trying to do something similar to this. As commented above, I think you would want to build a new image with a custom Dockerfile (using the image you pulled as a base image), ADD your certificate, then RUN update-ca-certificates. This way you will have a consistent state each time you start a container from this new image.

# Dockerfile
FROM some-base-image:0.1
ADD you_certificate.crt:/container/cert/path
RUN update-ca-certificates

Let's say a docker build against that Dockerfile produced IMAGE_ID. On the next docker run -d [any other options] IMAGE_ID, the container started by that command will have your certificate info. Simple and reproducible.

$.ajax( type: "POST" POST method to php

You need to use data: {title: title} to POST it correctly.

In the PHP code you need to echo the value instead of returning it.

Python - IOError: [Errno 13] Permission denied:

It looks like you're trying to replace the extension with the following code:

if (myFile[-4:] == ".asm"):
    newFile = myFile[:4]+".hack"

However, you appear to have the array indexes mixed up. Try the following:

if (myFile[-4:] == ".asm"):
    newFile = myFile[:-4]+".hack"

Note the use of -4 instead of just 4 in the second line of code. This explains why your program is trying to create /Use.hack, which is the first four characters of your file name (/Use), with .hack appended to it.

C# find highest array value and index

Finds the biggest and the smallest number in the array:

int[] arr = new int[] {35,28,20,89,63,45,12};
int big = 0;
int little = 0;

for (int i = 0; i < arr.Length; i++)
{
    Console.WriteLine(arr[i]);

    if (arr[i] > arr[0])
    {
        big = arr[i];
    }
    else
    {
        little = arr[i];

    }
}

Console.WriteLine("most big number inside of array is " + big);
Console.WriteLine("most little number inside of array is " + little);

Allowing Untrusted SSL Certificates with HttpClient

For Xamarin Android this was the only solution that worked for me: another stack overflow post

If you are using AndroidClientHandler, you need to supply a SSLSocketFactory and a custom implementation of HostnameVerifier with all checks disabled. To do this, you’ll need to subclass AndroidClientHandler and override the appropriate methods.

internal class BypassHostnameVerifier : Java.Lang.Object, IHostnameVerifier
{
    public bool Verify(string hostname, ISSLSession session)
    {
        return true;
    }
}
 
internal class InsecureAndroidClientHandler : AndroidClientHandler
{
    protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
    {
        return SSLCertificateSocketFactory.GetInsecure(1000, null);
    }
 
    protected override IHostnameVerifier GetSSLHostnameVerifier(HttpsURLConnection connection)
    {
        return new BypassHostnameVerifier();
    }
}

And then

var httpClient = new System.Net.Http.HttpClient(new InsecureAndroidClientHandler());

Get Image Height and Width as integer values?

Try like this:

list($width, $height) = getimagesize('path_to_image');

Make sure that:

  1. You specify the correct image path there
  2. The image has read access
  3. Chmod image dir to 755

Also try to prefix path with $_SERVER["DOCUMENT_ROOT"], this helps sometimes when you are not able to read files.

How to change css property using javascript

Just for the info, this can be done with CSS only with just minor HTML and CSS changes

HTML:

<div class="left">
    Hello
</div>
<div class="right">
    Hello2
</div>
<div class="center">
       <div class="left1">
           Bye
    </div>
       <div class="right1">
           Bye1
    </div>    
</div>

CSS:

.left, .right{
    margin:10px;
    float:left;
    border:1px solid red;
    height:60px;
    width:60px
}
.left:hover, .right:hover{
    border:1px solid blue;
}
.right{
     float :right;
}
.center{
    float:left;
    height:60px;
    width:160px
}

.center .left1, .center .right1{
    margin:10px;
    float:left;
    border:1px solid green;
    height:60px;
    width:58px;
    display:none;
}
.left:hover ~ .center .left1 {
    display:block;
}

.right:hover ~ .center .right1 {
    display:block;
}

and the DEMO: http://jsfiddle.net/pavloschris/y8LKM/

Defining TypeScript callback type

I just found something in the TypeScript language specification, it's fairly easy. I was pretty close.

the syntax is the following:

public myCallback: (name: type) => returntype;

In my example, it would be

class CallbackTest
{
    public myCallback: () => void;

    public doWork(): void
    {
        //doing some work...
        this.myCallback(); //calling callback
    }
}

Get output parameter value in ADO.NET

For anyone looking to do something similar using a reader with the stored procedure, note that the reader must be closed to retrieve the output value.

using (SqlConnection conn = new SqlConnection())
{
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add parameters
    SqlParameter outputParam = cmd.Parameters.Add("@ID", SqlDbType.Int);
    outputParam.Direction = ParameterDirection.Output;

    conn.Open();

    using(IDataReader reader = cmd.ExecuteReader())
    {
        while(reader.Read())
        {
            //read in data
        }
    }
    // reader is closed/disposed after exiting the using statement
    int id = outputParam.Value;
}

Multiple values in single-value context

No, you cannot directly access the first value.

I suppose a hack for this would be to return an array of values instead of "item" and "err", and then just do item, _ := Get(1)[0] but I would not recommend this.

Using Default Arguments in a Function

Optional arguments only work at the end of a function call. There is no way to specify a value for $y in your function without also specifying $x. Some languages support this via named parameters (VB/C# for example), but not PHP.

You can emulate this if you use an associative array for parameters instead of arguments -- i.e.

function foo(array $args = array()) {
    $x = !isset($args['x']) ? 'default x value' : $args['x'];
    $y = !isset($args['y']) ? 'default y value' : $args['y'];

    ...
}

Then call the function like so:

foo(array('y' => 'my value'));

How to use Python to login to a webpage and retrieve cookies for later usage?

import urllib, urllib2, cookielib

username = 'myuser'
password = 'mypassword'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()

resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

Download a file from HTTPS using download.file()

127 means command not found

In your case, curl command was not found. Therefore it means, curl was not found.

You need to install/reinstall CURL. That's all. Get latest version for your OS from http://curl.haxx.se/download.html

Close RStudio before installation.

Concatenate two slices in Go

append( ) function and spread operator

Two slices can be concatenated using append method in the standard golang library. Which is similar to the variadic function operation. So we need to use ...

package main

import (
    "fmt"
)

func main() {
    x := []int{1, 2, 3}
    y := []int{4, 5, 6}
    z := append([]int{}, append(x, y...)...)
    fmt.Println(z)
}

output of the above code is: [1 2 3 4 5 6]

How to get a variable type in Typescript?

I have checked a variable if it is a boolean or not as below

console.log(isBoolean(this.myVariable));

Similarly we have

isNumber(this.myVariable);
isString(this.myvariable);

and so on.

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

How to add a hook to the application context initialization event?

Spring has some standard events which you can handle.

To do that, you must create and register a bean that implements the ApplicationListener interface, something like this:

package test.pack.age;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class ApplicationListenerBean implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
            // now you can do applicationContext.getBean(...)
            // ...
        }
    }
}

You then register this bean within your servlet.xml or applicationContext.xml file:

<bean id="eventListenerBean" class="test.pack.age.ApplicationListenerBean" />

and Spring will notify it when the application context is initialized.

In Spring 3 (if you are using this version), the ApplicationListener class is generic and you can declare the event type that you are interested in, and the event will be filtered accordingly. You can simplify a bit your bean code like this:

public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        // now you can do applicationContext.getBean(...)
        // ...
    }
}