Programs & Examples On #Unhandled exception

An unhandled exception is an Exception that is thrown by execution but is never caught by the program, which results in a Exception Stack.

Why is "throws Exception" necessary when calling a function?

void show() throws Exception
{
    throw new Exception("my.own.Exception");
}

As there is checked exception in show() method , which is not being handled in that method so we use throws keyword for propagating the Exception.

void show2() throws Exception //Why throws is necessary here ?
{
show();
}

Since you are using the show() method in show2() method and you have propagated the exception atleast you should be handling here. If you are not handling the Exception here , then you are using throws keyword. So that is the reason for using throws keyword at the method signature.

Java 8: How do I work with exception throwing methods in streams?

More readable way:

class A {
  void foo() throws MyException() {
    ...
  }
}

Just hide it in a RuntimeException to get it past forEach()

  void bar() throws MyException {
      Stream<A> as = ...
      try {
          as.forEach(a -> {
              try {
                  a.foo();
              } catch(MyException e) {
                  throw new RuntimeException(e);
              }
          });
      } catch(RuntimeException e) {
          throw (MyException) e.getCause();
      }
  }

Although at this point I won't hold against someone if they say skip the streams and go with a for loop, unless:

  • you're not creating your stream using Collection.stream(), i.e. not straight forward translation to a for loop.
  • you're trying to use parallelstream()

What is an unhandled promise rejection?

Try not closing the connection before you send data to your database. Remove client.close(); from your code and it'll work fine.

How to create a popup windows in javafx

The Popup class might be better than the Stage class, depending on what you want. Stage is either modal (you can't click on anything else in your app) or it vanishes if you click elsewhere in your app (because it's a separate window). Popup stays on top but is not modal.

See this Popup Window example.

Visual Studio window which shows list of methods

Microsoft doesn't feel like implementing this useful tool, but if by chance you can have Visual Assist, you have it in VAssistX > Tools > VA Outline. The plugin is not free though.

Authenticating in PHP using LDAP through Active Directory

PHP has libraries: http://ca.php.net/ldap

PEAR also has a number of packages: http://pear.php.net/search.php?q=ldap&in=packages&x=0&y=0

I haven't used either, but I was going to at one point and they seemed like they should work.

Create array of all integers between two numbers, inclusive, in Javascript/jQuery

I highly recommend underscore or lo-dash libraries:

http://underscorejs.org/#range

(Almost completely compatible, apparently lodash runs quicker but underscore has better doco IMHO)

_.range([start], stop, [step])

Both libraries have bunch of very useful utilities.

How to set the environmental variable LD_LIBRARY_PATH in linux

You should add more details about your distribution, for example under Ubuntu the right way to do this is to add a custom .conf file to /etc/ld.so.conf.d, for example

sudo gedit /etc/ld.so.conf.d/randomLibs.conf

inside the file you are supposed to write the complete path to the directory that contains all the libraries that you wish to add to the system, for example

/home/linux/myLocalLibs

remember to add only the path to the dir, not the full path for the file, all the libs inside that path will be automatically indexed.

Save and run sudo ldconfig to update the system with this libs.

ImportError: No module named google.protobuf

To find where the name google clashes .... try this:

python3

then >>> help('google')

... I got info about google-auth:

NAME
    google

PACKAGE CONTENTS
    auth (package)
    oauth2 (package)

Also then try

pip show google-auth

Then

sudo pip3 uninstall google-auth

... and re-try >>> help('google')

I then see protobuf:

NAME
    google

PACKAGE CONTENTS
    protobuf (package)

Multiplication on command line terminal

I have a simple script I use for this:

me@mycomputer:~$ cat /usr/local/bin/c

#!/bin/sh

echo "$*" | sed 's/x/\*/g' | bc -l

It changes x to * since * is a special character in the shell. Use it as follows:

  • c 5x5
  • c 5-4.2 + 1
  • c '(5 + 5) * 30' (you still have to use quotes if the expression contains any parentheses).

Convert timestamp long to normal date format

Let me propose this solution for you. So in your managed bean, do this

public String convertTime(long time){
    Date date = new Date(time);
    Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
    return format.format(date);
}

so in your JSF page, you can do this (assuming foo is the object that contain your time)

<h:dataTable value="#{myBean.convertTime(myBean.foo.time)}" />

If you have multiple pages that want to utilize this method, you can put this in an abstract class and have your managed bean extend this abstract class.

EDIT: Return time with TimeZone

unfortunately, I think SimpleDateFormat will always format the time in local time, so we can't use SimpleDateFormat anymore. So to display time in different TimeZone, we can do this

public String convertTimeWithTimeZome(long time){
    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal.setTimeInMillis(time);
    return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " " 
            + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":"
            + cal.get(Calendar.MINUTE));

}

A better solution is to utilize JodaTime. In my opinion, this API is much better than Calendar (lighter weight, faster and provide more functionality). Plus Calendar.Month of January is 0, that force developer to add 1 to the result, and you have to format the time yourself. Using JodaTime, you can fix all of that. Correct me if I am wrong, but I think JodaTime is incorporated in JDK7

Reset push notification settings for app

Technical Note TN2265: Troubleshooting Push Notifications

The first time a push-enabled app registers for push notifications, iOS asks the user if they wish to receive notifications for that app. Once the user has responded to this alert it is not presented again unless the device is restored or the app has been uninstalled for at least a day.

If you want to simulate a first-time run of your app, you can leave the app uninstalled for a day. You can achieve the latter without actually waiting a day by setting the system clock forward a day or more, turning the device off completely, then turning the device back on.

Update: As noted in the comments below, this solution stopped working since iOS 5.1. I would encourage filing a bug with Apple so they can update their documentation. The current solution seems to be resetting the device's content and settings.

Update: The tech note has been updated with new steps that work correctly as of iOS 7.

  1. Delete your app from the device.
  2. Turn the device off completely and turn it back on.
  3. Go to Settings > General > Date & Time and set the date ahead a day or more.
  4. Turn the device off completely again and turn it back on.

UPDATE as of iOS 9

Simply deleting and reinstalling the app will reset the notification status to notDetermined (meaning prompts will appear).

Thanks to the answer by Gomfucius below: https://stackoverflow.com/a/33247900/704803

How to get the current location in Google Maps Android API v2?

I would rather use FusedLocationApi since OnMyLocationChangeListener is deprecated.

First declare these 3 variables:

private LocationRequest  mLocationRequest;
private GoogleApiClient  mGoogleApiClient;
private LocationListener mLocationListener;

Define methods:

private void initGoogleApiClient(Context context)
{
    mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
    {
        @Override
        public void onConnected(Bundle bundle)
        {
            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(1000);

            setLocationListener();
        }

        @Override
        public void onConnectionSuspended(int i)
        {
            Log.i("LOG_TAG", "onConnectionSuspended");
        }
    }).build();

    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();

}

private void setLocationListener()
{
    mLocationListener = new LocationListener()
    {
        @Override
        public void onLocationChanged(Location location)
        {
            String lat = String.valueOf(location.getLatitude());
            String lon = String.valueOf(location.getLongitude());
            Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
        }
    };

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}

private void removeLocationListener()
{
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}
  • initGoogleApiClient() is used to initialize GoogleApiClient object
  • setLocationListener() is used to setup location change listener
  • removeLocationListener() is used to remove the listener

Call initGoogleApiClient method to start the code working :) Don't forget to remove the listener (mLocationListener) at the end to avoid memory leak issues.

PostgreSQL psql terminal command

psql --pset=format=FORMAT

Great for executing queries from command line, e.g.

psql --pset=format=unaligned -c "select bandanavalue from bandana where bandanakey = 'atlassian.confluence.settings';"

Using CSS to affect div style inside iframe

probably not the way you are thinking. the iframe would have to <link> in the css file too. AND you can't do it even with javascript if it's on a different domain.

Jinja2 template variable if None Object set a default value

Use the none test (not to be confused with Python's None object!):

{% if p is not none %}   
    {{ p.User['first_name'] }}
{% else %}
    NONE
{% endif %}

or:

{{ p.User['first_name'] if p is not none else 'NONE' }}

or if you need an empty string:

{{ p.User['first_name'] if p is not none }}

PhpMyAdmin not working on localhost

All I had to do was load localhost:80/phpmyadmin and then the browser figured it out. After that, localhost/phpmyadmin worked.

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

You can use $timeout to prevent the error.

$timeout(function () {
    var scope = angular.element($("#myController")).scope();
    scope.myMethod(); 
    scope.$scope();
}, 1);

LINQ Group By and select collection

you may also like this

var Grp = Model.GroupBy(item => item.Order.Customer)
      .Select(group => new 
        { 
             Customer = Model.First().Customer, 
             CustomerId= group.Key,  
             Orders= group.ToList() 
       })
      .ToList();

How to return an array from a function?

how can i return a array in a c++ method and how must i declare it? int[] test(void); ??

This sounds like a simple question, but in C++ you have quite a few options. Firstly, you should prefer...

  • std::vector<>, which grows dynamically to however many elements you encounter at runtime, or

  • std::array<> (introduced with C++11), which always stores a number of elements specified at compile time,

...as they manage memory for you, ensuring correct behaviour and simplifying things considerably:

std::vector<int> fn()
{
    std::vector<int> x;
    x.push_back(10);
    return x;
}

std::array<int, 2> fn2()  // C++11
{
    return {3, 4};
}

void caller()
{
    std::vector<int> a = fn();
    const std::vector<int>& b = fn(); // extend lifetime but read-only
                                      // b valid until scope exit/return

    std::array<int, 2> c = fn2();
    const std::array<int, 2>& d = fn2();
}

The practice of creating a const reference to the returned data can sometimes avoid a copy, but normally you can just rely on Return Value Optimisation, or - for vector but not array - move semantics (introduced with C++11).

If you really want to use an inbuilt array (as distinct from the Standard library class called array mentioned above), one way is for the caller to reserve space and tell the function to use it:

void fn(int x[], int n)
{
    for (int i = 0; i < n; ++i)
        x[i] = n;
}

void caller()
{
    // local space on the stack - destroyed when caller() returns
    int x[10];
    fn(x, sizeof x / sizeof x[0]);

    // or, use the heap, lives until delete[](p) called...
    int* p = new int[10];
    fn(p, 10);
}

Another option is to wrap the array in a structure, which - unlike raw arrays - are legal to return by value from a function:

struct X
{
    int x[10];
};

X fn()
{
    X x;
    x.x[0] = 10;
    // ...
    return x;
}

void caller()
{
    X x = fn();
}

Starting with the above, if you're stuck using C++03 you might want to generalise it into something closer to the C++11 std::array:

template <typename T, size_t N>
struct array
{
    T& operator[](size_t n) { return x[n]; }
    const T& operator[](size_t n) const { return x[n]; }
    size_t size() const { return N; }
    // iterators, constructors etc....
  private:
    T x[N];
};

Another option is to have the called function allocate memory on the heap:

int* fn()
{
    int* p = new int[2];
    p[0] = 0;
    p[1] = 1;
    return p;
}

void caller()
{
    int* p = fn();
    // use p...
    delete[] p;
}

To help simplify the management of heap objects, many C++ programmers use "smart pointers" that ensure deletion when the pointer(s) to the object leave their scopes. With C++11:

std::shared_ptr<int> p(new int[2], [](int* p) { delete[] p; } );
std::unique_ptr<int[]> p(new int[3]);

If you're stuck on C++03, the best option is to see if the boost library is available on your machine: it provides boost::shared_array.

Yet another option is to have some static memory reserved by fn(), though this is NOT THREAD SAFE, and means each call to fn() overwrites the data seen by anyone keeping pointers from previous calls. That said, it can be convenient (and fast) for simple single-threaded code.

int* fn(int n)
{
    static int x[2];  // clobbered by each call to fn()
    x[0] = n;
    x[1] = n + 1;
    return x;  // every call to fn() returns a pointer to the same static x memory
}

void caller()
{
    int* p = fn(3);
    // use p, hoping no other thread calls fn() meanwhile and clobbers the values...
    // no clean up necessary...
}

angularjs ng-style: background-image isn't working

The syntax is changed for Angular 2 and above:

[ngStyle]="{'background-image': 'url(path)'}"

Horizontal Scroll Table in Bootstrap/CSS

You can also check for bootstrap datatable plugin as well for above issue.

It will have a large column table scrollable feature with lot of other options

$(document).ready(function() {
    $('#example').dataTable( {
        "scrollX": true
    } );
} );

for more info with example please check out this link

How to add Options Menu to Fragment in Android

You need to use menu.clear() before inflating menus.

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

and

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

Swift - How to hide back button in navigation item?

You may try with the below code

override func viewDidAppear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true
}

Objective-C: Extract filename from path string

Taken from the NSString reference, you can use :

NSString *theFileName = [[string lastPathComponent] stringByDeletingPathExtension];

The lastPathComponent call will return thefile.ext, and the stringByDeletingPathExtension will remove the extension suffix from the end.

How to wait for async method to complete?

just put Wait() to wait until task completed

GetInputReportViaInterruptTransfer().Wait();

VBA Public Array : how to?

Try this:

Dim colHeader(12)
colHeader = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")

Unfortunately the code found online was VB.NET not VBA.

CSS content property: is it possible to insert HTML instead of Text?

Unfortunately, this is not possible. Per the spec:

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).

In other words, for string values this means the value is always treated literally. It is never interpreted as markup, regardless of the document language in use.

As an example, using the given CSS with the following HTML:

<h1 class="header">Title</h1>

... will result in the following output:

<a href="#top">Back</a>Title

Carousel with Thumbnails in Bootstrap 3.0

Just found out a great plugin for this:

http://flexslider.woothemes.com/

Regards

Regular expression [Any number]

if("123".search(/^\d+$/) >= 0){
   // its a number
}

Java - Convert int to Byte Array of 4 Bytes?

int integer = 60;
byte[] bytes = new byte[4];
for (int i = 0; i < 4; i++) {
    bytes[i] = (byte)(integer >>> (i * 8));
}

How do I set the default schema for a user in MySQL

If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-

[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb

Mysql would then open this file for each user account read the credentials and open the selected database.

Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.

Query based on multiple where clauses in Firebase

Frank's answer is good but Firestore introduced array-contains recently that makes it easier to do AND queries.

You can create a filters field to add you filters. You can add as many values as you need. For example to filter by comedy and Jack Nicholson you can add the value comedy_Jack Nicholson but if you also you want to by comedy and 2014 you can add the value comedy_2014 without creating more fields.

{
  "movies": {
    "movie1": {
      "genre": "comedy",
      "name": "As good as it gets",
      "lead": "Jack Nicholson",
      "year": 2014,
      "filters": [
        "comedy_Jack Nicholson",
        "comedy_2014"
      ]
    }
  }
}

How can I emulate a get request exactly like a web browser?

Are you sure the curl module honors ini_set('user_agent',...)? There is an option CURLOPT_USERAGENT described at http://docs.php.net/function.curl-setopt.
Could there also be a cookie tested by the server? That you can handle by using CURLOPT_COOKIE, CURLOPT_COOKIEFILE and/or CURLOPT_COOKIEJAR.

edit: Since the request uses https there might also be error in verifying the certificate, see CURLOPT_SSL_VERIFYPEER.

$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);

Oracle (ORA-02270) : no matching unique or primary key for this column-list error

Most Probably when you have a missing Primary key is not defined from parent table. then It occurs.

Like Add the primary key define in parent as below:

ALTER TABLE "FE_PRODUCT" ADD CONSTRAINT "FE_PRODUCT_PK" PRIMARY KEY ("ID") ENABLE;

Hope this will work.

What are projection and selection?

Simply PROJECTION deals with elimination or selection of columns, while SELECTION deals with elimination or selection of rows.

URL rewriting with PHP

PHP is not what you are looking for, check out mod_rewrite

No value accessor for form control

For UnitTest angular 2 with angular material you have to add MatSelectModule module in imports section.

import { MatSelectModule } from '@angular/material';

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CreateUserComponent ],
      imports : [ReactiveFormsModule,        
        MatSelectModule,
        MatAutocompleteModule,......

      ],
      providers: [.........]
    })
    .compileComponents();
  }));

How to add image in a TextView text?

Try this ..

    txtview.setCompoundDrawablesWithIntrinsicBounds(
                    R.drawable.image, 0, 0, 0);

Also see this.. http://developer.android.com/reference/android/widget/TextView.html

Try this in xml file

    <TextView
        android:id="@+id/txtStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:drawableLeft="@drawable/image"
        android:drawablePadding="5dp"
        android:maxLines="1"
        android:text="@string/name"/>

jQuery click function doesn't work after ajax call?

$('body').delegate('.deletelanguage','click',function(){
    alert("success");
});

or

$('body').on('click','.deletelanguage',function(){
    alert("success");
});

Getting result of dynamic SQL into a variable for sql-server

 vMYQUERY := 'SELECT COUNT(*) FROM ALL_OBJECTS WHERE OWNER = UPPER(''MFI_IDBI2LIVE'') AND OBJECT_TYPE = ''TABLE'' 
    AND OBJECT_NAME  =''' || vTBL_CLIENT_MASTER || '''';
    PRINT_STRING(VMYQUERY);
    EXECUTE IMMEDIATE  vMYQUERY INTO VCOUNTTEMP ;

See full command of running/stopped container in Docker

Use:

docker inspect -f "{{.Path}} {{.Args}} ({{.Id}})" $(docker ps -a -q)

That will display the command path and arguments, similar to docker ps.

How to remove all whitespace from a string?

Another approach can be taken into account

library(stringr)
str_replace_all(" xx yy 11 22  33 ", regex("\\s*"), "")

#[1] "xxyy112233"

\\s: Matches Space, tab, vertical tab, newline, form feed, carriage return

*: Matches at least 0 times

How do I connect to an MDF database file?

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Samples\MyApp\C#\bin\Debug\Login.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");

this is working for me... Is there any way to short the path? like

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=\bin\Debug\Login.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");

How to use setInterval and clearInterval?

Use setTimeout(drawAll, 20) instead. That only executes the function once.

How can I read input from the console using the Scanner class in Java?

You can make a simple program to ask for the user's name and print whatever the reply use inputs.

Or ask the user to enter two numbers and you can add, multiply, subtract, or divide those numbers and print the answers for user inputs just like the behavior of a calculator.

So there you need the Scanner class. You have to import java.util.Scanner;, and in the code you need to use:

Scanner input = new Scanner(System.in);

input is a variable name.

Scanner input = new Scanner(System.in);

System.out.println("Please enter your name: ");
s = input.next(); // Getting a String value

System.out.println("Please enter your age: ");
i = input.nextInt(); // Getting an integer

System.out.println("Please enter your salary: ");
d = input.nextDouble(); // Getting a double

See how this differs: input.next();, i = input.nextInt();, d = input.nextDouble();

According to a String, int and a double varies the same way for the rest. Don't forget the import statement at the top of your code.

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

Reading a file line by line in Go

import (
     "bufio"
     "os"
)

var (
    reader = bufio.NewReader(os.Stdin)
)

func ReadFromStdin() string{
    result, _ := reader.ReadString('\n')
    witl := result[:len(result)-1]
    return witl
}

Here is an example with function ReadFromStdin() it's like fmt.Scan(&name) but its takes all strings with blank spaces like: "Hello My Name Is ..."

var name string = ReadFromStdin()

println(name)

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

The query below will result in dd/mm/yy format.

select  LEFT(convert(varchar(10), @date, 103),6) + Right(Year(@date)+ 1,2)

SVN how to resolve new tree conflicts when file is added on two branches

What if the incoming changes are the ones you want? I'm unable to run svn resolve --accept theirs-full

svn resolve --accept base

CSS pseudo elements in React

Depending if you only need a couple attributes to be styled inline you can do something like this solution (and saves you from having to install a special package or create an extra element):

https://stackoverflow.com/a/42000085

<span class="something" datacustomattribute="">
  Hello
</span>
.something::before {
  content: attr(datascustomattribute);
  position: absolute;
}

Note that the datacustomattribute must start with data and be all lowercase to satisfy React.

Update index after sorting data-frame

df.sort() is deprecated, use df.sort_values(...): https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

Then follow joris' answer by doing df.reset_index(drop=True)

How to solve a pair of nonlinear equations using Python?

Short answer: use fsolve

As mentioned in other answers the simplest solution to the particular problem you have posed is to use something like fsolve:

from scipy.optimize import fsolve
from math import exp

def equations(vars):
    x, y = vars
    eq1 = x+y**2-4
    eq2 = exp(x) + x*y - 3
    return [eq1, eq2]

x, y =  fsolve(equations, (1, 1))

print(x, y)

Output:

0.6203445234801195 1.8383839306750887

Analytic solutions?

You say how to "solve" but there are different kinds of solution. Since you mention SymPy I should point out the biggest difference between what this could mean which is between analytic and numeric solutions. The particular example you have given is one that does not have an (easy) analytic solution but other systems of nonlinear equations do. When there are readily available analytic solutions SymPY can often find them for you:

from sympy import *

x, y = symbols('x, y')
eq1 = Eq(x+y**2, 4)
eq2 = Eq(x**2 + y, 4)

sol = solve([eq1, eq2], [x, y])

Output:

?? ?  5   v17? ?3   v17?    v17   1?  ? ?  5   v17? ?3   v17?    1   v17?  ? ?  3   v13? ?v13   5?  1   v13?  ? ?5   v13? ?  v13   3?  1   v13??
??-?- - - ---?·?- - ---?, - --- - -?, ?-?- - + ---?·?- + ---?, - - + ---?, ?-?- - + ---?·?--- + -?, - + ---?, ?-?- - ---?·?- --- - -?, - - ---??
?? ?  2    2 ? ?2    2 ?     2    2?  ? ?  2    2 ? ?2    2 ?    2    2 ?  ? ?  2    2 ? ? 2    2?  2    2 ?  ? ?2    2 ? ?   2    2?  2    2 ??

Note that in this example SymPy finds all solutions and does not need to be given an initial estimate.

You can evaluate these solutions numerically with evalf:

soln = [tuple(v.evalf() for v in s) for s in sol]
[(-2.56155281280883, -2.56155281280883), (1.56155281280883, 1.56155281280883), (-1.30277563773199, 2.30277563773199), (2.30277563773199, -1.30277563773199)]

Precision of numeric solutions

However most systems of nonlinear equations will not have a suitable analytic solution so using SymPy as above is great when it works but not generally applicable. That is why we end up looking for numeric solutions even though with numeric solutions: 1) We have no guarantee that we have found all solutions or the "right" solution when there are many. 2) We have to provide an initial guess which isn't always easy.

Having accepted that we want numeric solutions something like fsolve will normally do all you need. For this kind of problem SymPy will probably be much slower but it can offer something else which is finding the (numeric) solutions more precisely:

from sympy import *

x, y = symbols('x, y')
nsolve([Eq(x+y**2, 4), Eq(exp(x)+x*y, 3)], [x, y], [1, 1])
?0.620344523485226?
?                 ?
?1.83838393066159 ?

With greater precision:

nsolve([Eq(x+y**2, 4), Eq(exp(x)+x*y, 3)], [x, y], [1, 1], prec=50)
?0.62034452348522585617392716579154399314071550594401?
?                                                    ?
? 1.838383930661594459049793153371142549403114879699 ?

Corrupted Access .accdb file: "Unrecognized Database Format"

Try to create a new database and import every table, query etc into this new database. With this import Access recreates all the objects from scratch. If there is some sort of corruption in an object, it should be solved.

If you're Lucky only the corrupted item(s) will be lost, if any.

How to set image name in Dockerfile?

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

version: '2'

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

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

docker build -t dude/man:v2 .

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

Create a SQL query to retrieve most recent records

Add an auto incrementing Primary Key to each record, for example, UserStatusId.

Then your query could look like this:

select * from UserStatus where UserStatusId in
(
    select max(UserStatusId) from UserStatus group by User
)

Date User Status Notes

Proper Linq where clauses

The second one would be more efficient as it just has one predicate to evaluate against each item in the collection where as in the first one, it's applying the first predicate to all items first and the result (which is narrowed down at this point) is used for the second predicate and so on. The results get narrowed down every pass but still it involves multiple passes.

Also the chaining (first method) will work only if you are ANDing your predicates. Something like this x.Age == 10 || x.Fat == true will not work with your first method.

Eclipse plugin for generating a class diagram

Assuming that you meant to state 'Class Diagram' instead of 'Project Hierarchy', I've used the following Eclipse plug-ins to generate Class Diagrams at various points in my professional career:

  • ObjectAid. My current preference.
  • EclipseUML from Omondo. Only commercial versions appear to be available right now. The class diagram in your question, is most likely generated by this plugin.

Obligatory links

The listed tools will not generate class diagrams from source code, or atleast when I used them quite a few years back. You can use them to handcraft class diagrams though.

  • UMLet. I used this several years back. Appears to be in use, going by the comments in the Eclipse marketplace.
  • Violet. This supports creation of other types of UML diagrams in addition to class diagrams.

Related questions on StackOverflow

  1. Is there a free Eclipse plugin that creates a UML diagram out of Java classes / packages?

Except for ObjectAid and a few other mentions, most of the Eclipse plug-ins mentioned in the listed questions may no longer be available, or would work only against older versions of Eclipse.

How are echo and print different in PHP?

They are:

  • print only takes one parameter, while echo can have multiple parameters.
  • print returns a value (1), so can be used as an expression.
  • echo is slightly faster.

Spring Boot Java Config Set Session Timeout

  • Spring Boot version 1.0: server.session.timeout=1200
  • Spring Boot version 2.0: server.servlet.session.timeout=10m
    NOTE: If a duration suffix is not specified, seconds will be used.

Print execution time of a shell command

Don't forget that there is a difference between bash's builtin time (which should be called by default when you do time command) and /usr/bin/time (which should require you to call it by its full path).

The builtin time always prints to stderr, but /usr/bin/time will allow you to send time's output to a specific file, so you do not interfere with the executed command's stderr stream. Also, /usr/bin/time's format is configurable on the command line or by the environment variable TIME, whereas bash's builtin time format is only configured by the TIMEFORMAT environment variable.

$ time factor 1234567889234567891 # builtin
1234567889234567891: 142662263 8653780357

real    0m3.194s
user    0m1.596s
sys 0m0.004s
$ /usr/bin/time factor 1234567889234567891
1234567889234567891: 142662263 8653780357
1.54user 0.00system 0:02.69elapsed 57%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+215minor)pagefaults 0swaps
$ /usr/bin/time -o timed factor 1234567889234567891 # log to file `timed`
1234567889234567891: 142662263 8653780357
$ cat timed
1.56user 0.02system 0:02.49elapsed 63%CPU (0avgtext+0avgdata 0maxresident)k
0inputs+0outputs (0major+217minor)pagefaults 0swaps

What is Java Servlet?

What is a Servlet?

  • A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request.
  • Basically servlets are usually used to implement web applications - but there are also various frameworks which operate on top of servlets (e.g. Struts) to give a higher-level abstraction than the "here's an HTTP request, write to this HTTP response" level which servlets provide.
  • Servlets run in a servlet container which handles the networking side (e.g. parsing an HTTP request, connection handling etc). One of the best-known open source servlet containers is Tomcat.

  • In a request/response paradigm, a web server can serve only static pages to the client

  • To serve dynamic pages, a we require Servlets.
  • Servlet is nothing but a Java program
  • This Java program doesn’t have a main method. It only has some callback methods.
  • How does the web server communicate to the servlet? Via container or Servlet engine.
  • Servlet lives and dies within a web container.
  • Web container is responsible for invoking methods in a servlets. It knows what callback methods the Servlet has.

Flow of Request

  • Client sends HTTP request to Web server
  • Web server forwards that HTTP request to web container.
  • Since Servlet can not understand HTTP, its a Java program, it only understands objects, so web container converts that request into valid request object
  • Web container spins a thread for each request
  • All the business logic goes inside doGet() or doPost() callback methods inside the servlets
  • Servlet builds a Java response object and sends it to the container. It converts that to HTTP response again to send it to the client

How does the Container know which Servlet client has requested for?

  • There’s a file called web.xml
  • This is the master file for a web container
  • You have information about servlet in this file-

    • servlets
      • Servlet-name
      • Servlet-class
    • servlet-mappings- the path like /Login or /Notifications is mapped here in
      • Servlet-name
      • url-pattern
    • and so on
  • Every servlet in the web app should have an entry into this file

  • So this lookup happens like- url-pattern -> servlet-name -> servlet-class

How to "install" Servlets? * Well, the servlet objects are inherited from the library- javax.servlet.* . Tomcat and Spring can be used to utilize these objects to fit the use case.

Ref- Watch this on 1.5x- https://www.youtube.com/watch?v=tkFRGdUgCsE . This has an awesome explanation.

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

There are two ways to achieve that:

  • Use -rpath linker option:

gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX -Wl,-rpath=/home/user/.usr/lib

  • Use LD_LIBRARY_PATH environment variable - put this line in your ~/.bashrc file:

    export LD_LIBRARY_PATH=/home/user/.usr/lib

This will work even for a pre-generated binaries, so you can for example download some packages from the debian.org, unpack the binaries and shared libraries into your home directory, and launch them without recompiling.

For a quick test, you can also do (in bash at least):

LD_LIBRARY_PATH=/home/user/.usr/lib ./xxx.out

which has the advantage of not changing your library path for everything else.

Creating multiple objects with different names in a loop to store in an array list

ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
    //get a customerName
    //get an amount
    custArr.add(new Customer(customerName, amount);
}

For this to work... you'll have to fix your constructor...


Assuming your Customer class has variables called name and sale, your constructor should look like this:

public Customer(String customerName, double amount) {
    name = customerName;
    sale = amount;
}

Change your Store class to something more like this:

public class Store {

    private ArrayList<Customer> custArr;

    public new Store() {
        custArr = new ArrayList<Customer>();
    }

    public void addSale(String customerName, double amount) {
        custArr.add(new Customer(customerName, amount));
    }

    public Customer getSaleAtIndex(int index) {
        return custArr.get(index);
    }

    //or if you want the entire ArrayList:
    public ArrayList getCustArr() {
        return custArr;
    }
}

Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes

or use display property with table-cell;

css

.table-layout {
    display:table;
    width:100%;
}
.table-layout .table-cell {
    display:table-cell;
    border:solid 1px #ccc;
}

.fixed-width-200 {
    width:200px;
}

html

<div class="table-layout">
    <div class="table-cell fixed-width-200">
        <p>fixed width div</p>
    </div>
    <div class="table-cell">
        <p>fluid width div</p>    
    </div>
</div>

http://jsfiddle.net/DnGDz/

Skipping error in for-loop

One (dirty) way to do it is to use tryCatch with an empty function for error handling. For example, the following code raises an error and breaks the loop :

for (i in 1:10) {
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
Erreur : Urgh, the iphone is in the blender !

But you can wrap your instructions into a tryCatch with an error handling function that does nothing, for example :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){})
}

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

But I think you should at least print the error message to know if something bad happened while letting your code continue to run :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
ERROR : Urgh, the iphone is in the blender ! 
[1] 8
[1] 9
[1] 10

EDIT : So to apply tryCatch in your case would be something like :

for (v in 2:180){
    tryCatch({
        mypath=file.path("C:", "file1", (paste("graph",names(mydata[columnname]), ".pdf", sep="-")))
        pdf(file=mypath)
        mytitle = paste("anything")
        myplotfunction(mydata[,columnnumber]) ## this function is defined previously in the program
        dev.off()
    }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

You are running locally, meaning that your client runs on the same machine as your server.

Make sure that your Unix user can actually reach/read /var/run/mysqld/mysqld.sock:

ls -als /var
ls -als /var/run
ls -als /var/run/mysqld
ls -als /var/run/mysqld/mysqld.sock

If not, check with your system administrator or database administrator to provide adequate read/execute access to those directories, or move the socket file elsewhere.

How do I size a UITextView to its content?

Did you try [textView sizeThatFits:textView.bounds] ?

Edit: sizeThatFits returns the size but does not actually resize the component. I'm not sure if that's what you want, or if [textView sizeToFit] is more what you were looking for. In either case, I do not know if it will perfectly fit the content like you want, but it's the first thing to try.

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

If you want to pull out only the index values for certain integer-based row-indices, you can do something like the following using the iloc method:

In [28]: temp
Out[28]:
       index                 time  complete
row_0      2  2014-10-22 01:00:00         0
row_1      3  2014-10-23 14:00:00         0
row_2      4  2014-10-26 08:00:00         0
row_3      5  2014-10-26 10:00:00         0
row_4      6  2014-10-26 11:00:00         0

In [29]: temp.iloc[[0,1,4]].index
Out[29]: Index([u'row_0', u'row_1', u'row_4'], dtype='object')

In [30]: temp.iloc[[0,1,4]].index.tolist()
Out[30]: ['row_0', 'row_1', 'row_4']

Setting Django up to use MySQL

settings.py

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'django',
    'USER': 'root',
    'PASSWORD': '*****',
    'HOST': '***.***.***.***',
    'PORT': '3306',
    'OPTIONS': {
        'autocommit': True,
    },
}

}

then:

python manage.py migrate

if success will generate theses tables:

auth_group
auth_group_permissions
auth_permission
auth_user
auth_user_groups
auth_user_user_permissions
django_admin_log
django_content_type
django_migrations
django_session

and u will can use mysql.

this is a showcase example ,test on Django version 1.11.5: Django-pool-showcase

Custom events in jQuery?

I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):

 $("p").bind("myCustomEvent", function(e, myName, myValue){
      $(this).text(myName + ", hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent", [ "John" ]);
    });

jQuery - simple input validation - "empty" and "not empty"

JQuery's :empty selector selects all elements on the page that are empty in the sense that they have no child elements, including text nodes, not all inputs that have no text in them.

Jquery: How to check if an input element has not been filled in.

Here's the code stolen from the above thread:

$('#apply-form input').blur(function()          //whenever you click off an input element
{                   
    if( !$(this).val() ) {                      //if it is blank. 
         alert('empty');    
    }
});

This works because an empty string in JavaScript is a 'falsy value', which basically means if you try to use it as a boolean value it will always evaluate to false. If you want, you can change the conditional to $(this).val() === '' for added clarity. :D

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

Attach the Java Source Code

Hold ctrl key and then click on class of which you want to see the inner working (for ex: String) then you will find there button "Attach Source". Click on it. Then click on External Folder. Then browse to your jdk location, per instance C:\Program Files\Java\jdk1.6.0. That's it.

enter image description here

Can't clone a github repo on Linux via HTTPS

You can manual disable ssl verfiy, and try again. :)

git config --global http.sslverify false

How to find out when an Oracle table was updated the last time

Could you run a checksum of some sort on the result and store that locally? Then when your application queries the database, you can compare its checksum and determine if you should import it?

It looks like you may be able to use the ORA_HASH function to accomplish this.

Update: Another good resource: 10g’s ORA_HASH function to determine if two Oracle tables’ data are equal

How can I clear or empty a StringBuilder?

If you look at the source code for a StringBuilder or StringBuffer the setLength() call just resets an index value for the character array. IMHO using the setLength method will always be faster than a new allocation. They should have named the method 'clear' or 'reset' so it would be clearer.

Turn off constraints temporarily (MS SQL)

You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE

ALTER TABLE foo NOCHECK CONSTRAINT ALL

or

ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column

Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.

Can not connect to local PostgreSQL

psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

I searching the solution for a while. So, this one fixed the issue for me as well (reinit db):

rm -r /usr/local/var/postgres  
initdb /usr/local/var/postgres -E utf8  
pg_ctl -D /usr/local/var/postgres -l logfile start

I use OS X 10.11.3 with brew.

Class type check in TypeScript

You can use the instanceof operator for this. From MDN:

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:

_x000D_
_x000D_
    class Animal {_x000D_
        name;_x000D_
    _x000D_
        constructor(name) {_x000D_
            this.name = name;_x000D_
        }_x000D_
    }_x000D_
    _x000D_
    const animal = new Animal('fluffy');_x000D_
    _x000D_
    // true because Animal in on the prototype chain of animal_x000D_
    console.log(animal instanceof Animal); // true_x000D_
    // Proof that Animal is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
    _x000D_
    // true because Object in on the prototype chain of animal_x000D_
    console.log(animal instanceof Object); _x000D_
    // Proof that Object is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
    _x000D_
    console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
    _x000D_
    
_x000D_
_x000D_
_x000D_

The prototype chain in this example is:

animal > Animal.prototype > Object.prototype

Mount current directory as a volume in Docker on Windows 10

Here is mine which is compatible for both Win10 docker-ce & Win7 docker-toolbox. At las at the time I'm writing this :).

You can notice I prefer use /host_mnt/c instead of c:/ because I sometimes encountered trouble on docker-ce Win 10 with c:/

$WIN_PATH=Convert-Path .

#Convert for docker mount to be OK on Windows10 and Windows 7 Powershell
#Exact conversion is : remove the ":" symbol, replace all "\" by "/", remove last "/" and minor case only the disk letter
#Then for Windows10, add a /host_mnt/" at the begin of string => this way : c:\Users is translated to /host_mnt/c/Users
#For Windows7, add "//" => c:\Users is translated to //c/Users
$MOUNT_PATH=(($WIN_PATH -replace "\\","/") -replace ":","").Trim("/")

[regex]$regex='^[a-zA-Z]/'
$MOUNT_PATH=$regex.Replace($MOUNT_PATH, {$args[0].Value.ToLower()})

#Win 10
if ([Environment]::OSVersion.Version -ge (new-object 'Version' 10,0)) {
$MOUNT_PATH="/host_mnt/$MOUNT_PATH"
}
elseif ([Environment]::OSVersion.Version -ge (new-object 'Version' 6,1)) {
$MOUNT_PATH="//$MOUNT_PATH"
}

docker run -it -v "${MOUNT_PATH}:/tmp/test" busybox ls /tmp/test

How to remove backslash on json_encode() function?

Yes it's possible. Look!

$str = str_replace('\\', '', $str);

But why would you want to?

How to print Unicode character in C++?

This code works in Linux (C++11, geany, g++ 7.4.0):

#include <iostream>

using namespace std;


int utf8_to_unicode(string utf8_code);
string unicode_to_utf8(int unicode);


int main()
{
    cout << unicode_to_utf8(36) << '\t';
    cout << unicode_to_utf8(162) << '\t';
    cout << unicode_to_utf8(8364) << '\t';
    cout << unicode_to_utf8(128578) << endl;

    cout << unicode_to_utf8(0x24) << '\t';
    cout << unicode_to_utf8(0xa2) << '\t';
    cout << unicode_to_utf8(0x20ac) << '\t';
    cout << unicode_to_utf8(0x1f642) << endl;

    cout << utf8_to_unicode("$") << '\t';
    cout << utf8_to_unicode("¢") << '\t';
    cout << utf8_to_unicode("€") << '\t';
    cout << utf8_to_unicode("") << endl;

    cout << utf8_to_unicode("\x24") << '\t';
    cout << utf8_to_unicode("\xc2\xa2") << '\t';
    cout << utf8_to_unicode("\xe2\x82\xac") << '\t';
    cout << utf8_to_unicode("\xf0\x9f\x99\x82") << endl;

    return 0;
}


int utf8_to_unicode(string utf8_code)
{
    unsigned utf8_size = utf8_code.length();
    int unicode = 0;

    for (unsigned p=0; p<utf8_size; ++p)
    {
        int bit_count = (p? 6: 8 - utf8_size - (utf8_size == 1? 0: 1)),
            shift = (p < utf8_size - 1? (6*(utf8_size - p - 1)): 0);

        for (int k=0; k<bit_count; ++k)
            unicode += ((utf8_code[p] & (1 << k)) << shift);
    }

    return unicode;
}


string unicode_to_utf8(int unicode)
{
    string s;

    if (unicode>=0 and unicode <= 0x7f)  // 7F(16) = 127(10)
    {
        s = static_cast<char>(unicode);

        return s;
    }
    else if (unicode <= 0x7ff)  // 7FF(16) = 2047(10)
    {
        unsigned char c1 = 192, c2 = 128;

        for (int k=0; k<11; ++k)
        {
            if (k < 6)  c2 |= (unicode % 64) & (1 << k);
            else c1 |= (unicode >> 6) & (1 << (k - 6));
        }

        s = c1;    s += c2;

        return s;
    }
    else if (unicode <= 0xffff)  // FFFF(16) = 65535(10)
    {
        unsigned char c1 = 224, c2 = 128, c3 = 128;

        for (int k=0; k<16; ++k)
        {
            if (k < 6)  c3 |= (unicode % 64) & (1 << k);
            else if (k < 12) c2 |= (unicode >> 6) & (1 << (k - 6));
            else c1 |= (unicode >> 12) & (1 << (k - 12));
        }

        s = c1;    s += c2;    s += c3;

        return s;
    }
    else if (unicode <= 0x1fffff)  // 1FFFFF(16) = 2097151(10)
    {
        unsigned char c1 = 240, c2 = 128, c3 = 128, c4 = 128;

        for (int k=0; k<21; ++k)
        {
            if (k < 6)  c4 |= (unicode % 64) & (1 << k);
            else if (k < 12) c3 |= (unicode >> 6) & (1 << (k - 6));
            else if (k < 18) c2 |= (unicode >> 12) & (1 << (k - 12));
            else c1 |= (unicode >> 18) & (1 << (k - 18));
        }

        s = c1;    s += c2;    s += c3;    s += c4;

        return s;
    }
    else if (unicode <= 0x3ffffff)  // 3FFFFFF(16) = 67108863(10)
    {
        ;  // actually, there are no 5-bytes unicodes
    }
    else if (unicode <= 0x7fffffff)  // 7FFFFFFF(16) = 2147483647(10)
    {
        ;  // actually, there are no 6-bytes unicodes
    }
    else  ;  // incorrect unicode (< 0 or > 2147483647)

    return "";
}

More:

How can getContentResolver() be called in Android?

Access contentResolver in Kotlin , inside activities, Object classes &... :

Application().contentResolver

Counting the Number of keywords in a dictionary in python

len(yourdict.keys())

or just

len(yourdict)

If you like to count unique words in the file, you could just use set and do like

len(set(open(yourdictfile).read().split()))

Extract a substring according to a pattern

The unglue package provides an alternative, no knowledge about regular expressions is required for simple cases, here we'd do :

# install.packages("unglue")
library(unglue)
string = c("G1:E001", "G2:E002", "G3:E003")
unglue_vec(string,"{x}:{y}", var = "y")
#> [1] "E001" "E002" "E003"

Created on 2019-11-06 by the reprex package (v0.3.0)

More info : https://github.com/moodymudskipper/unglue/blob/master/README.md

How to replace spaces in file names using a bash script

find . -depth -name '* *' \
| while IFS= read -r f ; do mv -i "$f" "$(dirname "$f")/$(basename "$f"|tr ' ' _)" ; done

failed to get it right at first, because I didn't think of directories.

DATEDIFF function in Oracle

We can directly subtract dates to get difference in Days.

    SET SERVEROUTPUT ON ;
    DECLARE
        V_VAR NUMBER;
    BEGIN
         V_VAR:=TO_DATE('2000-01-02', 'YYYY-MM-DD') - TO_DATE('2000-01-01', 'YYYY-MM-DD') ;
         DBMS_OUTPUT.PUT_LINE(V_VAR);
    END;

PHP + curl, HTTP POST sample code?

If the form is using redirects, authentication, cookies, SSL (https), or anything else other than a totally open script expecting POST variables, you are going to start gnashing your teeth really quick. Take a look at Snoopy, which does exactly what you have in mind while removing the need to set up a lot of the overhead.

execute shell command from android

A modification of the code by @CarloCannas:

public static void sudo(String...strings) {
    try{
        Process su = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

        for (String s : strings) {
            outputStream.writeBytes(s+"\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        outputStream.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

(You are welcome to find a better place for outputStream.close())

Usage example:

private static void suMkdirs(String path) {
    if (!new File(path).isDirectory()) {
        sudo("mkdir -p "+path);
    }
}

Update: To get the result (the output to stdout), use:

public static String sudoForResult(String...strings) {
    String res = "";
    DataOutputStream outputStream = null;
    InputStream response = null;
    try{
        Process su = Runtime.getRuntime().exec("su");
        outputStream = new DataOutputStream(su.getOutputStream());
        response = su.getInputStream();

        for (String s : strings) {
            outputStream.writeBytes(s+"\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        res = readFully(response);
    } catch (IOException e){
        e.printStackTrace();
    } finally {
        Closer.closeSilently(outputStream, response);
    }
    return res;
}
public static String readFully(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length = 0;
    while ((length = is.read(buffer)) != -1) {
        baos.write(buffer, 0, length);
    }
    return baos.toString("UTF-8");
}

The utility to silently close a number of Closeables (So?ket may be no Closeable) is:

public class Closer {
// closeAll()
public static void closeSilently(Object... xs) {
    // Note: on Android API levels prior to 19 Socket does not implement Closeable
    for (Object x : xs) {
        if (x != null) {
            try {
                Log.d("closing: "+x);
                if (x instanceof Closeable) {
                    ((Closeable)x).close();
                } else if (x instanceof Socket) {
                    ((Socket)x).close();
                } else if (x instanceof DatagramSocket) {
                    ((DatagramSocket)x).close();
                } else {
                    Log.d("cannot close: "+x);
                    throw new RuntimeException("cannot close "+x);
                }
            } catch (Throwable e) {
                Log.x(e);
            }
        }
    }
}
}

How to iterate (keys, values) in JavaScript?

You can do something like this :

dictionary = {'ab': {object}, 'cd':{object}, 'ef':{object}}
var keys = Object.keys(dictionary);

for(var i = 0; i < keys.length;i++){
   //keys[i] for key
   //dictionary[keys[i]] for the value
}

Converting characters to integers in Java

Character.getNumericValue(c)

The java.lang.Character.getNumericValue(char ch) returns the int value that the specified Unicode character represents. For example, the character '\u216C' (the roman numeral fifty) will return an int with a value of 50.

The letters A-Z in their uppercase ('\u0041' through '\u005A'), lowercase ('\u0061' through '\u007A'), and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A') forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.

This method returns the numeric value of the character, as a nonnegative int value;

-2 if the character has a numeric value that is not a nonnegative integer;

-1 if the character has no numeric value.

And here is the link.

How to programmatically determine the current checked out Git branch

From this answer: https://stackoverflow.com/a/1418022/605356 :

$ git rev-parse --abbrev-ref HEAD
master

Apparently works with Git 1.6.3 or newer.

ORA-12170: TNS:Connect timeout occurred

I was getting the same error while connecting my "hr" user of ORCLPDB which is a pluggable database.

First, get hostname and port number by typing a command lsnrctl status on windows command prompt. In my case, it was 127.0.0.1 with port number as 1521

Second, enter the below command with your hostname and port number:

sqlplus username/password@HostName:Port Number/PluggableDatabaseName.

For example:

sqlplus hr/[email protected]:1521/ORCLPDB.

How to check if std::map contains a key without doing insert?

Your desideratum,map.contains(key), is scheduled for the draft standard C++2a. In 2017 it was implemented by gcc 9.2. It's also in the current clang.

How to print HTML content on click of a button, but not the page?

According to this SO link you can print a specific div with

w=window.open();
w.document.write(document.getElementsByClassName('report_left_inner')[0].innerH??TML);
w.print();
w.close();

How to find when a web page was last updated

For checking the Last Modified header, you can use httpie (docs).

Installation

pip install httpie --user

Usage

$ http -h https://martin-thoma.com/author/martin-thoma/ | grep 'Last-Modified\|Date'
Date: Fri, 06 Jan 2017 10:06:43 GMT
Last-Modified: Fri, 06 Jan 2017 07:42:34 GMT

The Date is important as this reports the server time, not your local time. Also, not every server sends Last-Modified (e.g. superuser seems not to do it).

What happens if you mount to a non-empty mount point with fuse?

You need to make sure that the files on the device mounted by fuse will not have the same paths and file names as files which already existing in the nonempty mountpoint. Otherwise this would lead to confusion. If you are sure, pass -o nonempty to the mount command.

You can try what is happening using the following commands.. (Linux rocks!) .. without destroying anything..

// create 10 MB file 
dd if=/dev/zero of=partition bs=1024 count=10240

// create loopdevice from that file
sudo losetup /dev/loop0 ./partition

// create  filesystem on it
sudo e2mkfs.ext3 /dev/loop0

// mount the partition to temporary folder and create a file
mkdir test
sudo mount -o loop /dev/loop0 test
echo "bar" | sudo tee test/foo

# unmount the device
sudo umount /dev/loop0

# create the file again
echo "bar2" > test/foo

# now mount the device (having file with same name on it) 
# and see what happens
sudo mount -o loop /dev/loop0 test

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You have to set the http header at the http response of your resource. So it needs to be set serverside, you can remove the "HTTP_OPTIONS"-header from your angular HTTP-Post request.

How to check if a stored procedure exists before creating it

I apparently don't have the reputation required to vote or comment, but I just wanted to say that Geoff's answer using EXEC (sp_executesql might be better) is definitely the way to go. Dropping and then re-creating the stored procedure gets the job done in the end, but there is a moment in time where the stored procedure doesn't exist at all, and that can be very bad, especially if this is something that will be run repeatedly. I was having all sorts of problems with my application because a background thread was doing an IF EXISTS DROP...CREATE at the same time another thread was trying to use the stored procedure.

Most simple code to populate JTable from ResultSet

I think this is the Easiest way to populate/model a table with ResultSet.. Download and include rs2xml.jar Get rs2xml.jar in your libraries..

import net.proteanit.sql.DbUtils;

    try
    {
    CreateConnection();
    PreparedStatement st =conn.prepareStatement("Select * from ABC;");
    ResultSet rs = st.executeQuery();
    tblToBeFilled.setModel(DbUtils.resultSetToTableModel(rs));
    conn.close();
    }
    catch(Exception ex)
    {
    JOptionPane.showMessageDialog(null, ex.toString());
    }

Font size of TextView in Android application changes on changing font size from native settings

Also note that if the textSize is set in code, calling textView.setTextSize(X) interprets the number (X) as SP. Use setTextSize(TypedValue.COMPLEX_UNIT_DIP, X) to set values in dp.

Combining two expressions (Expression<Func<T, bool>>)

I needed to achieve the same results, but using something more generic (as the type was not known). Thanks to marc's answer I finally figured out what I was trying to achieve:

    public static LambdaExpression CombineOr(Type sourceType, LambdaExpression exp, LambdaExpression newExp) 
    {
        var parameter = Expression.Parameter(sourceType);

        var leftVisitor = new ReplaceExpressionVisitor(exp.Parameters[0], parameter);
        var left = leftVisitor.Visit(exp.Body);

        var rightVisitor = new ReplaceExpressionVisitor(newExp.Parameters[0], parameter);
        var right = rightVisitor.Visit(newExp.Body);

        var delegateType = typeof(Func<,>).MakeGenericType(sourceType, typeof(bool));
        return Expression.Lambda(delegateType, Expression.Or(left, right), parameter);
    }

Laravel 5.4 create model, controller and migration in single artisan command

Just Try this command on your terminal

php artisan make:model Todo -mcr

Below the output and your Model, Controller with Resource and Migration file will create...

Model created successfully.
Created Migration: 2019_12_25_105305_create_todos_table
Controller created successfully.

Angular - How to apply [ngStyle] conditions

You can use an inline if inside your ngStyle:

[ngStyle]="styleOne?{'background-color': 'red'} : {'background-color': 'blue'}"

A batter way in my opinion is to store your background color inside a variable and then set the background-color as the variable value:

[style.background-color]="myColorVaraible"

How to select a column name with a space in MySQL

I got here with an MS Access problem.

Backticks are good for MySQL, but they create weird errors, like "Invalid Query Name: Query1" in MS Access, for MS Access only, use square brackets:

It should look like this

SELECT Customer.[Customer ID], Customer.[Full Name] ...

Sort Pandas Dataframe by Date

sort method has been deprecated and replaced with sort_values. After converting to datetime object using df['Date']=pd.to_datetime(df['Date'])

df.sort_values(by=['Date'])

Note: to sort in-place and/or in a descending order (the most recent first):

df.sort_values(by=['Date'], inplace=True, ascending=False)

jQuery access input hidden value

Most universal way is to take value by name. It doesn't matter if its input or select form element type.

var value = $('[name="foo"]');

What is the difference between NULL, '\0' and 0?

If NULL and 0 are equivalent as null pointer constants, which should I use? in the C FAQ list addresses this issue as well:

C programmers must understand that NULL and 0 are interchangeable in pointer contexts, and that an uncast 0 is perfectly acceptable. Any usage of NULL (as opposed to 0) should be considered a gentle reminder that a pointer is involved; programmers should not depend on it (either for their own understanding or the compiler's) for distinguishing pointer 0's from integer 0's.

It is only in pointer contexts that NULL and 0 are equivalent. NULL should not be used when another kind of 0 is required, even though it might work, because doing so sends the wrong stylistic message. (Furthermore, ANSI allows the definition of NULL to be ((void *)0), which will not work at all in non-pointer contexts.) In particular, do not use NULL when the ASCII null character (NUL) is desired. Provide your own definition

#define NUL '\0'

if you must.

How to run a C# application at Windows startup?

If you could not set your application autostart you can try to paste this code to manifest

<requestedExecutionLevel  level="asInvoker" uiAccess="false" />

or delete manifest I had found it in my application

Any tools to generate an XSD schema from an XML instance document?

If all you want is XSD, LiquidXML has a free version that does XSDs, and its got a GUI to it so you can tweak the XSD if you like. Anyways nowadays I write my own XSDs by hand, but its all thanks to this app.

http://www.liquid-technologies.com/

How to convert a String into an array of Strings containing one character each

String x = "stackoverflow";
String [] y = x.split("");

Move cursor to end of file in vim

This is quicker:

<ESC>GA

Error: Unfortunately you can't have non-Gradle Java modules and > Android-Gradle modules in one project

The ultimate solution to this error:

SOLUTION 1

Step 1 Go to File -> Invalidate Caches/Restart.

Step 2 Close the project.

Step 3 Go to project folder and delete .idea folder.

Step 4 Delete YourProjectName.iml in project folder.

step 5 You will see a folder below graddle folder, Delete YourProjectName folder (it contains another YourProjectName.iml file).

Step 6 Open Android studio -> open existing project, and then select your project.

**

SOLUTION 2

**

Step 1: Open the Corrupted Project (The one showing error).

Step 2: Open system.gradle file.

step 3: add this line of code include ':app'.

Step 4: click on the sync, to sync the gradle file.

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

According to the comments, the data-type in the datatable is DATE. So you should simply use: "select date_column from table;"

Now if you execute the select you will get back a date data-type, which should be what you need for the .xsd.

Culture-dependent formating of the date should be done in the GUI (most languages have convenient ways to do so), not in the select-statement.

What is a Memory Heap?

You probably mean heap memory, not memory heap.

Heap memory is essentially a large pool of memory (typically per process) from which the running program can request chunks. This is typically called dynamic allocation.

It is different from the Stack, where "automatic variables" are allocated. So, for example, when you define in a C function a pointer variable, enough space to hold a memory address is allocated on the stack. However, you will often need to dynamically allocate space (With malloc) on the heap and then provide the address where this memory chunk starts to the pointer.

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

// I usually do this:

x = "0" ;

if (!!+x) console.log('I am true');
else      console.log('I am false');

// Essentially converting string to integer and then boolean.

How can I uninstall an application using PowerShell?

I will make my own little contribution. I needed to remove a list of packages from the same computer. This is the script I came up with.

$packages = @("package1", "package2", "package3")
foreach($package in $packages){
  $app = Get-WmiObject -Class Win32_Product | Where-Object {
    $_.Name -match "$package"
  }
  $app.Uninstall()
}

I hope this proves to be useful.

Note that I owe David Stetler the credit for this script since it is based on his.

Mac zip compress without __MACOSX folder?

This command did it for me:

zip -r Target.zip Source -x "*.DS_Store"

Target.zip is the zip file to create. Source is the source file/folder to zip up. And the _x parameter specifies the file/folder to not include. If the above doesn't work for whatever reason, try this instead:

zip -r Target.zip Source -x "*.DS_Store" -x "__MACOSX"

C Macro definition to determine big endian or little endian machine?

Code supporting arbitrary byte orders, ready to be put into a file called order32.h:

#ifndef ORDER32_H
#define ORDER32_H

#include <limits.h>
#include <stdint.h>

#if CHAR_BIT != 8
#error "unsupported char size"
#endif

enum
{
    O32_LITTLE_ENDIAN = 0x03020100ul,
    O32_BIG_ENDIAN = 0x00010203ul,
    O32_PDP_ENDIAN = 0x01000302ul,      /* DEC PDP-11 (aka ENDIAN_LITTLE_WORD) */
    O32_HONEYWELL_ENDIAN = 0x02030001ul /* Honeywell 316 (aka ENDIAN_BIG_WORD) */
};

static const union { unsigned char bytes[4]; uint32_t value; } o32_host_order =
    { { 0, 1, 2, 3 } };

#define O32_HOST_ORDER (o32_host_order.value)

#endif

You would check for little endian systems via

O32_HOST_ORDER == O32_LITTLE_ENDIAN

INSERT INTO from two different server database

You cannot directly copy a table into a destination server database from a different database if source db is not in your linked servers. But one way is possible that, generate scripts (schema with data) of the desired table into one table temporarily in the source server DB, then execute the script in the destination server DB to create a table with your data. Finally use INSERT INTO [DESTINATION_TABLE] select * from [TEMPORARY_SOURCE_TABLE]. After getting the data into your destination table drop the temporary one.

I found this solution when I faced the same situation. Hope this helps you too.

How to get milliseconds from LocalDateTime in Java 8

You can use java.sql.Timestamp also to get milliseconds.

LocalDateTime now = LocalDateTime.now();
long milliSeconds = Timestamp.valueOf(now).getTime();
System.out.println("MilliSeconds: "+milliSeconds);

Why specify @charset "UTF-8"; in your CSS file?

One reason to always include a character set specification on every page containing text is to avoid cross site scripting vulnerabilities. In most cases the UTF-8 character set is the best choice for text, including HTML pages.

Rebasing a Git merge commit

  • From your merge commit
  • Cherry-pick the new change which should be easy
  • copy your stuff
  • redo the merge and resolve the conflicts by just copying the files from your local copy ;)

Create a CSS rule / class with jQuery at runtime

You can create style element and insert it into DOM

$("<style type='text/css'> .redbold{ color:#f00; font-weight:bold;} </style>").appendTo("head");
$("<div/>").addClass("redbold").text("SOME NEW TEXT").appendTo("body");

tested on Opera10 FF3.5 iE8 iE6

How should I import data from CSV into a Postgres table using pgAdmin 3?

assuming you have a SQL table called mydata - you can load data from a csv file as follows:

COPY MYDATA FROM '<PATH>/MYDATA.CSV' CSV HEADER;

For more details refer to: http://www.postgresql.org/docs/9.2/static/sql-copy.html

Reading all files in a directory, store them in objects, and send the object

Are you a lazy person like me and love npm module :D then check this out.

npm install node-dir

example for reading files:

var dir = require('node-dir');

dir.readFiles(__dirname,
    function(err, content, next) {
        if (err) throw err;
        console.log('content:', content);  // get content of files
        next();
    },
    function(err, files){
        if (err) throw err;
        console.log('finished reading files:', files); // get filepath 
   });    

How to prevent a browser from storing passwords

You should be able to make a fake hidden password box to prevent it.

_x000D_
_x000D_
<form>_x000D_
  <div style="display:none">_x000D_
    <input type="password" tabindex="-1"/>_x000D_
  </div>_x000D_
  <input type="text" name="username" placeholder="username"/>_x000D_
  <input type="password" name="password" placeholder="password"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Create a remote branch on GitHub

Before creating a new branch always the best practice is to have the latest of repo in your local machine. Follow these steps for error free branch creation.

 1. $ git branch (check which branches exist and which one is currently active (prefixed with *). This helps you avoid creating duplicate/confusing branch name)
 2. $ git branch <new_branch> (creates new branch)
 3. $ git checkout new_branch
 4. $ git add . (After making changes in the current branch)
 5. $ git commit -m "type commit msg here"
 6. $ git checkout master (switch to master branch so that merging with new_branch can be done)
 7. $ git merge new_branch (starts merging)
 8. $ git push origin master (push to the remote server)

I referred this blog and I found it to be a cleaner approach.

Getting the ID of the element that fired an event

Pure JS is simpler

aaa.onclick = handler;
bbb.onclick = handler;

function handler() { 
  var test = this.id; 
  console.log(test) 
}

_x000D_
_x000D_
aaa.onclick = handler;
bbb.onclick = handler;

function handler() { 
  var test = this.id; 
  console.log(test) 
}
_x000D_
<form class="item" id="aaa">
  <input class="title"/>
</form>
<form class="item" id="bbb">
  <input class="title"/>
</form>
_x000D_
_x000D_
_x000D_

"git pull" or "git merge" between master and development branches

If you are not sharing develop branch with anybody, then I would just rebase it every time master updated, that way you will not have merge commits all over your history once you will merge develop back into master. Workflow in this case would be as follows:

> git clone git://<remote_repo_path>/ <local_repo>
> cd <local_repo>
> git checkout -b develop
....do a lot of work on develop
....do all the commits
> git pull origin master
> git rebase master develop

Above steps will ensure that your develop branch will be always on top of the latest changes from the master branch. Once you are done with develop branch and it's rebased to the latest changes on master you can just merge it back:

> git checkout -b master
> git merge develop
> git branch -d develop

Good way to encapsulate Integer.parseInt()

This is an answer to question 8391979, "Does java have a int.tryparse that doesn't throw an exception for bad data? [duplicate]" which is closed and linked to this question.

Edit 2016 08 17: Added ltrimZeroes methods and called them in tryParse(). Without leading zeroes in numberString may give false results (see comments in code). There is now also public static String ltrimZeroes(String numberString) method which works for positive and negative "numbers"(END Edit)

Below you find a rudimentary Wrapper (boxing) class for int with an highly speed optimized tryParse() method (similar as in C#) which parses the string itself and is a little bit faster than Integer.parseInt(String s) from Java:

public class IntBoxSimple {
    // IntBoxSimple - Rudimentary class to implement a C#-like tryParse() method for int
    // A full blown IntBox class implementation can be found in my Github project
    // Copyright (c) 2016, Peter Sulzer, Fürth
    // Program is published under the GNU General Public License (GPL) Version 1 or newer

    protected int _n; // this "boxes" the int value

    // BEGIN The following statements are only executed at the
    // first instantiation of an IntBox (i. e. only once) or
    // already compiled into the code at compile time:
    public static final int MAX_INT_LEN =
            String.valueOf(Integer.MAX_VALUE).length();
    public static final int MIN_INT_LEN =
            String.valueOf(Integer.MIN_VALUE).length();
    public static final int MAX_INT_LASTDEC =
            Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(1));
    public static final int MAX_INT_FIRSTDIGIT =
            Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(0, 1));
    public static final int MIN_INT_LASTDEC =
            -Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(2));
    public static final int MIN_INT_FIRSTDIGIT =
            Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(1,2));
    // END The following statements...

    // ltrimZeroes() methods added 2016 08 16 (are required by tryParse() methods)
    public static String ltrimZeroes(String s) {
        if (s.charAt(0) == '-')
            return ltrimZeroesNegative(s);
        else
            return ltrimZeroesPositive(s);
    }
    protected static String ltrimZeroesNegative(String s) {
        int i=1;
        for ( ; s.charAt(i) == '0'; i++);
        return ("-"+s.substring(i));
    }
    protected static String ltrimZeroesPositive(String s) {
        int i=0;
        for ( ; s.charAt(i) == '0'; i++);
        return (s.substring(i));
    }

    public static boolean tryParse(String s,IntBoxSimple intBox) {
        if (intBox == null)
            // intBoxSimple=new IntBoxSimple(); // This doesn't work, as
            // intBoxSimple itself is passed by value and cannot changed
            // for the caller. I. e. "out"-arguments of C# cannot be simulated in Java.
            return false; // so we simply return false
        s=s.trim(); // leading and trailing whitespace is allowed for String s
        int len=s.length();
        int rslt=0, d, dfirst=0, i, j;
        char c=s.charAt(0);
        if (c == '-') {
            if (len > MIN_INT_LEN) { // corrected (added) 2016 08 17
                s = ltrimZeroesNegative(s);
                len = s.length();
            }
            if (len >= MIN_INT_LEN) {
                c = s.charAt(1);
                if (!Character.isDigit(c))
                    return false;
                dfirst = c-'0';
                if (len > MIN_INT_LEN || dfirst > MIN_INT_FIRSTDIGIT)
                    return false;
            }
            for (i = len - 1, j = 1; i >= 2; --i, j *= 10) {
                c = s.charAt(i);
                if (!Character.isDigit(c))
                    return false;
                rslt -= (c-'0')*j;
            }
            if (len < MIN_INT_LEN) {
                c = s.charAt(i);
                if (!Character.isDigit(c))
                    return false;
                rslt -= (c-'0')*j;
            } else {
                if (dfirst >= MIN_INT_FIRSTDIGIT && rslt < MIN_INT_LASTDEC)
                    return false;
                rslt -= dfirst * j;
            }
        } else {
            if (len > MAX_INT_LEN) { // corrected (added) 2016 08 16
                s = ltrimZeroesPositive(s);
                len=s.length();
            }
            if (len >= MAX_INT_LEN) {
                c = s.charAt(0);
                if (!Character.isDigit(c))
                    return false;
                dfirst = c-'0';
                if (len > MAX_INT_LEN || dfirst > MAX_INT_FIRSTDIGIT)
                    return false;
            }
            for (i = len - 1, j = 1; i >= 1; --i, j *= 10) {
                c = s.charAt(i);
                if (!Character.isDigit(c))
                    return false;
                rslt += (c-'0')*j;
            }
            if (len < MAX_INT_LEN) {
                c = s.charAt(i);
                if (!Character.isDigit(c))
                    return false;
                rslt += (c-'0')*j;
            }
            if (dfirst >= MAX_INT_FIRSTDIGIT && rslt > MAX_INT_LASTDEC)
                return false;
            rslt += dfirst*j;
        }
        intBox._n=rslt;
        return true;
    }

    // Get the value stored in an IntBoxSimple:
    public int get_n() {
        return _n;
    }
    public int v() { // alternative shorter version, v for "value"
        return _n;
    }
    // Make objects of IntBoxSimple (needed as constructors are not public):
    public static IntBoxSimple makeIntBoxSimple() {
        return new IntBoxSimple();
    }
    public static IntBoxSimple makeIntBoxSimple(int integerNumber) {
        return new IntBoxSimple(integerNumber);
    }

    // constructors are not public(!=:
    protected IntBoxSimple() {} {
        _n=0; // default value an IntBoxSimple holds
    }
    protected IntBoxSimple(int integerNumber) {
        _n=integerNumber;
    }
}

Test/example program for class IntBoxSimple:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class IntBoxSimpleTest {
    public static void main (String args[]) {
        IntBoxSimple ibs = IntBoxSimple.makeIntBoxSimple();
        String in = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        do {
            System.out.printf(
                    "Enter an integer number in the range %d to %d:%n",
                        Integer.MIN_VALUE, Integer.MAX_VALUE);
            try { in = br.readLine(); } catch (IOException ex) {}
        } while(! IntBoxSimple.tryParse(in, ibs));
        System.out.printf("The number you have entered was: %d%n", ibs.v());
    }
}

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

There are many way to do the string aggregation, but the easiest is a user defined function. Try this for a way that does not require a function. As a note, there is no simple way without the function.

This is the shortest route without a custom function: (it uses the ROW_NUMBER() and SYS_CONNECT_BY_PATH functions )

SELECT questionid,
       LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,','))
       KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM   (SELECT questionid,
               elementid,
               ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr,
               ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev
        FROM   emp)
GROUP BY questionid
CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid
START WITH curr = 1;

Calling a javascript function in another js file

Please note this only works if the

<script>

tags are in the body and NOT in the head.

So

<head>
...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</head>

=> unknown function fn1()

Fails and

<body>
...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</body>

works.

How to redirect a url in NGINX

Similar to another answer here, but change the http in the rewrite to to $scheme like so:

server {
        listen 80;
        server_name test.com;
        rewrite     ^ $scheme://www.test.com$request_uri? permanent;
}

And edit your main server block server_name variable as following:

server_name  www.test.com;

I had to do this to redirect www.test.com to test.com.

Adding onClick event dynamically using jQuery

Try below approach,

$('#bfCaptchaEntry').on('click', myfunction);

or in case jQuery is not an absolute necessaity then try below,

document.getElementById('bfCaptchaEntry').onclick = myfunction;

However the above method has few drawbacks as it set onclick as a property rather than being registered as handler...

Read more on this post https://stackoverflow.com/a/6348597/297641

What jsf component can render a div tag?

In JSF 2.2 it's possible to use passthrough elements:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:jsf="http://xmlns.jcp.org/jsf">
    ...
    <div jsf:id="id1" />
    ...
</html>

The requirement is to have at least one attribute in the element using jsf namespace.

Ruby: Calling class method from instance

Using self.class.blah is NOT the same as using ClassName.blah when it comes to inheritance.

class Truck
  def self.default_make
    "mac"
  end

  def make1
    self.class.default_make
  end

  def make2
    Truck.default_make
  end
end


class BigTruck < Truck
  def self.default_make
    "bigmac"
  end
end

ruby-1.9.3-p0 :021 > b=BigTruck.new
 => #<BigTruck:0x0000000307f348> 
ruby-1.9.3-p0 :022 > b.make1
 => "bigmac" 
ruby-1.9.3-p0 :023 > b.make2
 => "mac" 

Django CSRF Cookie Not Set

This can also occur if CSRF_COOKIE_SECURE = True is set and you are accessing the site non-securely or if CSRF_COOKIE_HTTPONLY = True is set as stated here and here

How to get primary key column in Oracle?

SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner
FROM all_constraints cons, all_cons_columns cols
WHERE cols.table_name = 'TABLE_NAME'
AND cons.constraint_type = 'P'
AND cons.constraint_name = cols.constraint_name
AND cons.owner = cols.owner
ORDER BY cols.table_name, cols.position;

Make sure that 'TABLE_NAME' is in upper case since Oracle stores table names in upper case.

How to force a script reload and re-execute?

Small tweak to Luke's answer,

 function reloadJs(src) {
    src = $('script[src$="' + src + '"]').attr("src");
    $('script[src$="' + src + '"]').remove();
    $('<script/>').attr('src', src).appendTo('head');
}

and call it like,

reloadJs("myFile.js");

This will not have any path related issues.

How to get row count in sqlite using Android?

c.getCount() returns 1 because the cursor contains a single row (the one with the real COUNT(*)). The count you need is the int value of first row in cursor.

public int getTaskCount(long tasklist_Id) {

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor= db.rawQuery(
        "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
         new String[] { String.valueOf(tasklist_Id) }
    );
    int count = 0;
    if(null != cursor)
        if(cursor.getCount() > 0){
          cursor.moveToFirst();    
          count = cursor.getInt(0);
        }
        cursor.close();
    }

    db.close();
    return count;
}   

Ruby send JSON request

I like this light weight http request client called `unirest'

gem install unirest

usage:

response = Unirest.post "http://httpbin.org/post", 
                        headers:{ "Accept" => "application/json" }, 
                        parameters:{ :age => 23, :foo => "bar" }

response.code # Status code
response.headers # Response headers
response.body # Parsed body
response.raw_body # Unparsed body

What is the use of adding a null key or value to a HashMap in Java?

A null key can also be helpful when the map stores data for UI selections where the map key represents a bean field.

A corresponding null field value would for example be represented as "(please select)" in the UI selection.

Open another page in php

Use something like header( 'Location: /my-other-page.html' ); to redirect. You can't have sent any other data on the page before you do this though.

Should I use @EJB or @Inject

It may also be usefull to understand the difference in term of Session Bean Identity when using @EJB and @Inject. According to the specifications the following code will always be true:

@EJB Cart cart1;
@EJB Cart cart2;
… if (cart1.equals(cart2)) { // this test must return true ...}

Using @Inject instead of @EJB there is not the same.

see also stateless session beans identity for further info

server error:405 - HTTP verb used to access this page is not allowed

In the Facebook app control panel make sure you have a forward slash on the end of any specified URL if you are only specifying a folder name

i.e.

Page Tab URL: http://mypagetabserver.com/custom_tab/

Find all packages installed with easy_install/pip?

The below is a little slow, but it gives a nicely formatted list of packages that pip is aware of. That is to say, not all of them were installed "by" pip, but all of them should be able to be upgraded by pip.

$ pip search . | egrep -B1 'INSTALLED|LATEST'

The reason it is slow is that it lists the contents of the entire pypi repo. I filed a ticket suggesting pip list provide similar functionality but more efficiently.

Sample output: (restricted the search to a subset instead of '.' for all.)

$ pip search selenium | egrep -B1 'INSTALLED|LATEST'

selenium                  - Python bindings for Selenium
  INSTALLED: 2.24.0
  LATEST:    2.25.0
--
robotframework-selenium2library - Web testing library for Robot Framework
  INSTALLED: 1.0.1 (latest)
$

How to use OrderBy with findAll in Spring Data

Yes you can sort using query method in Spring Data.

Ex:ascending order or descending order by using the value of the id field.

Code:

  public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public findAllByOrderByIdAsc();   
}

alternative solution:

    @Repository
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDAO studentDao;

    @Override
    public List<Student> findAll() {
        return studentDao.findAll(orderByIdAsc());
    }
private Sort orderByIdAsc() {
    return new Sort(Sort.Direction.ASC, "id")
                .and(new Sort(Sort.Direction.ASC, "name"));
}
}

Spring Data Sorting: Sorting

Passing Multiple route params in Angular2

As detailed in this answer, mayur & user3869623's answer's are now relating to a deprecated router. You can now pass multiple parameters as follows:

To call router:

this.router.navigate(['/myUrlPath', "someId", "another ID"]);

In routes.ts:

{ path: 'myUrlpath/:id1/:id2', component: componentToGoTo},

How to access full source of old commit in BitBucket?

I was trying to figure out if it's possible to browse the code of an earlier commit like you can on GitHub and it brought me here. I used the information I found here, and after fiddling around with the urls, I actually found a way to browse code of old commits as well.

When you're browsing your code the URL is something like:

https://bitbucket.org/user/repo/src/

and by adding a commit hash at the end like this:

https://bitbucket.org/user/repo/src/a0328cb

You can browse the code at the point of that commit. I don't understand why there's no dropdown box for choosing a commit directly, the feature is already there. Strange.

How to do scanf for single char in C

You have to use a valid variable. ch is not a valid variable for this program. Use char Aaa;

char aaa;
scanf("%c",&Aaa);

Tested and it works.

What are these ^M's that keep showing up in my files in emacs?

Pot the following in your ~/.emacs (or eqiuvalent)

(defun dos2unix ()
  "Replace DOS eolns CR LF with Unix eolns CR"
  (interactive)
    (goto-char (point-min))
      (while (search-forward "\r" nil t) (replace-match "")))

and then you would be able to simply use M-x dos2unix.

How to scan a folder in Java?

Check out Apache Commons FileUtils (listFiles, iterateFiles, etc.). Nice convenience methods for doing what you want and also applying filters.

http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html

Npm install failed with "cannot run in wd"

OP here, I have learned a lot more about node since I first asked this question. Though Dmitry's answer was very helpful, what ultimately did it for me is to install node with the correct permissions.

I highly recommend not installing node using any package managers, but rather to compile it yourself so that it resides in a local directory with normal permissions.

This article provides a very clear step-by-step instruction of how to do so:

https://www.digitalocean.com/community/tutorials/how-to-install-an-upstream-version-of-node-js-on-ubuntu-12-04

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

How to execute a remote command over ssh with arguments?

Reviving an old thread, but this pretty clean approach was not listed.

function mycommand() {
    ssh [email protected] <<+
    cd testdir;./test.sh "$1"
+
}

What is the ellipsis (...) for in this method signature?

The way to use the ellipsis or varargs inside the method is as if it were an array:

public void PrintWithEllipsis(String...setOfStrings) {
    for (String s : setOfStrings)
        System.out.println(s);
}

This method can be called as following:

obj.PrintWithEllipsis(); // prints nothing
obj.PrintWithEllipsis("first"); // prints "first"
obj.PrintWithEllipsis("first", "second"); // prints "first\nsecond"

Inside PrintWithEllipsis, the type of setOfStrings is an array of String. So you could save the compiler some work and pass an array:

String[] argsVar = {"first", "second"};
obj.PrintWithEllipsis(argsVar);

For varargs methods, a sequence parameter is treated as being an array of the same type. So if two signatures differ only in that one declares a sequence and the other an array, as in this example:

void process(String[] s){}
void process(String...s){}

then a compile-time error occurs.

Source: The Java Programming Language specification, where the technical term is variable arity parameter rather than the common term varargs.

Android ListView with onClick items

well in your onitemClick you will send the selected value like deal , and send it in your intent when opening new activity and in your new activity get the sent data and related to selected item will display your data

to get the name from the list

String item = yourData.get(position).getName(); 

to set data in intent

intent.putExtra("Key", item);

to get the data in second activity

getIntent().getExtras().getString("Key")

angular 2 ngIf and CSS transition/animation

update 4.1.0

Plunker

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#400-rc1-2017-02-24

update 2.1.0

Plunker

For more details see Animations at angular.io

import { trigger, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'my-app',
  animations: [
    trigger(
      'enterAnimation', [
        transition(':enter', [
          style({transform: 'translateX(100%)', opacity: 0}),
          animate('500ms', style({transform: 'translateX(0)', opacity: 1}))
        ]),
        transition(':leave', [
          style({transform: 'translateX(0)', opacity: 1}),
          animate('500ms', style({transform: 'translateX(100%)', opacity: 0}))
        ])
      ]
    )
  ],
  template: `
    <button (click)="show = !show">toggle show ({{show}})</button>

    <div *ngIf="show" [@enterAnimation]>xxx</div>
  `
})
export class App {
  show:boolean = false;
}

original

*ngIf removes the element from the DOM when the expression becomes false. You can't have a transition on a non-existing element.

Use instead hidden:

<div class="note" [ngClass]="{'transition':show}" [hidden]="!show">

IF statement: how to leave cell blank if condition is false ("" does not work)

I wanted to add that there is another possibility - to use the function na().

e.g. =if(a2 = 5,"good",na());

This will fill the cell with #N/A and if you chart the column, the data won't be graphed. I know it isn't "blank" as such, but it's another possibility if you have blank strings in your data and "" is a valid option.

Also, count(a:a) will not count cells which have been set to n/a by doing this.

How do I set the size of an HTML text box?

Your markup:

<input type="text" class="resizedTextbox" />

The CSS:

.resizedTextbox {width: 100px; height: 20px}

Keep in mind that text box size is a "victim" of the W3C box model. What I mean by victim is that the height and width of a text box is the sum of the height/width properties assigned above, in addition to the padding height/width, and the border width. For this reason, your text boxes will be slightly different sizes in different browsers depending on the default padding in different browsers. Although different browsers tend to define different padding to text boxes, most reset style sheets don't tend to include <input /> tags in their reset sheets, so this is something to keep in mind.

You can standardize this by defining your own padding. Here is your CSS with specified padding, so the text box looks the same in all browsers:

.resizedTextbox {width: 100px; height: 20px; padding: 1px}

I added 1 pixel padding because some browsers tend to make the text box look too crammed if the padding is 0px. Depending on your design, you may want to add even more padding, but it is highly recommend you define the padding yourself, otherwise you'll be leaving it up to different browsers to decide for themselves. For even more consistency across browsers, you should also define the border yourself.

Hashing a dictionary?

Here is a clearer solution.

def freeze(o):
  if isinstance(o,dict):
    return frozenset({ k:freeze(v) for k,v in o.items()}.items())

  if isinstance(o,list):
    return tuple([freeze(v) for v in o])

  return o


def make_hash(o):
    """
    makes a hash out of anything that contains only list,dict and hashable types including string and numeric types
    """
    return hash(freeze(o))  

get user timezone

On server-side it will be not as accurate as with JavaScript. Meanwhile, sometimes it is required to solve such task. Just to share the possible solution in this case I write this answer.

If you need to determine user's time zone it could be done via Geo-IP services. Some of them providing timezone. For example, this one (http://smart-ip.net/geoip-api) could help:

<?php
$ip     = $_SERVER['REMOTE_ADDR']; // means we got user's IP address 
$json   = file_get_contents( 'http://smart-ip.net/geoip-json/' . $ip); // this one service we gonna use to obtain timezone by IP
// maybe it's good to add some checks (if/else you've got an answer and if json could be decoded, etc.)
$ipData = json_decode( $json, true);

if ($ipData['timezone']) {
    $tz = new DateTimeZone( $ipData['timezone']);
    $now = new DateTime( 'now', $tz); // DateTime object corellated to user's timezone
} else {
   // we can't determine a timezone - do something else...
}

How to capitalize the first letter of a String in Java?

Use this utility method to get all first letter in capital.

String captializeAllFirstLetter(String name) 
{
    char[] array = name.toCharArray();
    array[0] = Character.toUpperCase(array[0]);

    for (int i = 1; i < array.length; i++) {
        if (Character.isWhitespace(array[i - 1])) {
            array[i] = Character.toUpperCase(array[i]);
        }
    }

    return new String(array);
}

Using Regular Expressions to Extract a Value in Java

In addition to Pattern, the Java String class also has several methods that can work with regular expressions, in your case the code will be:

"ab123abc".replaceFirst("\\D*(\\d*).*", "$1")

where \\D is a non-digit character.

Tracing XML request/responses with JAX-WS

Before starting tomcat, set JAVA_OPTS as below in Linux envs. Then start Tomcat. You will see the request and response in the catalina.out file.

export JAVA_OPTS="$JAVA_OPTS -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true"

SQL Server SELECT LAST N Rows

To display last 3 rows without using order by:

select * from Lms_Books_Details where Book_Code not in 
 (select top((select COUNT(*) from Lms_Books_Details ) -3 ) book_code from Lms_Books_Details) 

How do I set session timeout of greater than 30 minutes

If you want to never expire a session use 0 or negative value -1.

<session-config>
    <session-timeout>0</session-timeout>
</session-config>

or mention 1440 it indicates 1440 minutes [24hours * 60 minutes]

<session-config>
  <session-timeout>1440</session-timeout><!-- 24hours -->
</session-config>

Session will be expire after 24hours.

How to disable the ability to select in a DataGridView?

I'd go with this:

private void myDataGridView_SelectionChanged(Object sender, EventArgs e)
{
    dgvSomeDataGridView.ClearSelection();  
}

I don't agree with the broad assertion that no DataGridView should be unselectable. Some UIs are built for tools or touchsreens, and allowing a selection misleads the user to think that selecting will actually get them somewhere.

Setting ReadOnly = true on the control has no impact on whether a cell or row can be selected. And there are visual and functional downsides to setting Enabled = false.

Another option is to set the control selected colors to be exactly what the non-selected colors are, but if you happen to be manipulating the back color of the cell, then this method yields some nasty results as well.

JavaScript: how to change form action attribute value based on selection?

$("#selectsearch").change(function() {
  var action = $(this).val() == "people" ? "user" : "content";
  $("#search-form").attr("action", "/search/" + action);
});

AngularJS $http-post - convert binary to excel file and download

There is no way (to my knowledge) to trigger the download window in your browser from Javascript. The only way to do it is to redirect the browser to a url that streams the file to the browser.

If you can modify your REST service, you might be able to solve it by changing so the POST request doesn't respond with the binary file, but with a url to that file. That'll get you the url in Javascript instead of the binary data, and you can redirect the browser to that url, which should prompt the download without leaving the original page.

How to use confirm using sweet alert?

document.querySelector('#from1').onsubmit = function(e){

 swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!",
    closeOnConfirm: false,
    closeOnCancel: false
 },
 function(isConfirm){

   if (isConfirm){
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");

    } else {
      swal("Cancelled", "Your imaginary file is safe :)", "error");
         e.preventDefault();
    }
 });
};

How to get "GET" request parameters in JavaScript?

You could use jquery.url I did like this:

var xyz = jQuery.url.param("param_in_url");

Check the source code

Updated Source: https://github.com/allmarkedup/jQuery-URL-Parser

C++ Array Of Pointers

For example, if you want an array of int pointers it will be int* a[10]. It means that variable a is a collection of 10 int* s.

EDIT

I guess this is what you want to do:

class Bar
{
};

class Foo
{
public:

    //Takes number of bar elements in the pointer array
    Foo(int size_in);

    ~Foo();
    void add(Bar& bar);
private:

    //Pointer to bar array
    Bar** m_pBarArr;

    //Current fee bar index
    int m_index;
};

Foo::Foo(int size_in) : m_index(0)
{
    //Allocate memory for the array of bar pointers
    m_pBarArr = new Bar*[size_in];
}

Foo::~Foo()
{
    //Notice delete[] and not delete
    delete[] m_pBarArr;
    m_pBarArr = NULL;
}

void Foo::add(Bar &bar)
{
    //Store the pointer into the array. 
    //This is dangerous, you are assuming that bar object
    //is valid even when you try to use it
    m_pBarArr[m_index++] = &bar;
}

How to avoid "StaleElementReferenceException" in Selenium?

Generally this is due to the DOM being updated and you trying to access an updated/new element -- but the DOM's refreshed so it's an invalid reference you have..

Get around this by first using an explicit wait on the element to ensure the update is complete, then grab a fresh reference to the element again.

Here's some psuedo code to illustrate (Adapted from some C# code I use for EXACTLY this issue):

WebDriverWait wait = new WebDriverWait(browser, TimeSpan.FromSeconds(10));
IWebElement aRow = browser.FindElement(By.XPath(SOME XPATH HERE);
IWebElement editLink = aRow.FindElement(By.LinkText("Edit"));

//this Click causes an AJAX call
editLink.Click();

//must first wait for the call to complete
wait.Until(ExpectedConditions.ElementExists(By.XPath(SOME XPATH HERE));

//you've lost the reference to the row; you must grab it again.
aRow = browser.FindElement(By.XPath(SOME XPATH HERE);

//now proceed with asserts or other actions.

Hope this helps!

Python dictionary get multiple values

You can use At from pydash:

from pydash import at
dict = {'a': 1, 'b': 2, 'c': 3}
list = at(dict, 'a', 'b')
list == [1, 2]

apache not accepting incoming connections from outside of localhost

this is what worked for us to get the apache accessible from outside:

sudo iptables -I INPUT 4 -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
sudo service iptables restart

Equivalent of Math.Min & Math.Max for Dates?

How about a DateTime extension method?

public static DateTime MaxOf(this DateTime instance, DateTime dateTime)
{
    return instance > dateTime ? instance : dateTime;
}

Usage:

var maxDate = date1.MaxOf(date2);

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

Center image in table td in CSS

<td align="center">

or via css, which is the preferred method any more...

<td style="text-align: center;">

How to remove all null elements from a ArrayList or String Array?

 for (Iterator<Tourist> itr = tourists.iterator(); itr.hasNext();) {
      if (itr.next() == null) { itr.remove(); }
 }

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

How to stash my previous commit?

If you've not pushed either commit to your remote repository, you could use interactive rebasing to 'reorder' your commits and stash the (new) most recent commit's changes only.

Assuming you have the tip of your current branch (commit 111 in your example) checked out, execute the following:

git rebase -i HEAD~2

This will open your default editor, listing most recent 2 commits and provide you with some instructions. Be very cautious as to what you do here, as you are going to effectively 'rewrite' the history of your repository, and can potentially lose work if you aren't careful (make a backup of the whole repository first if necessary). I've estimated commit hashes/titles below for example

pick 222 commit to be stashed
pick 111 commit to be pushed to remote

# Rebase 111..222 onto 333
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

Reorder the two commits (they are listed oldest => newest) like this:

pick 111 commit to be pushed to remote
pick 222 commit to be stashed

Save and exit, at which point git will do some processing to rewrite the two commits you have changed. Assuming no issues, you should have reversed the order of your two changesets. This can be confirmed with git log --oneline -5 which will output newest-first.

At this point, you can simply do a soft-reset on the most recent commit, and stash your working changes:

git reset --soft HEAD~1
git stash

It's important to mention that this option is only really viable if you have not previously pushed any of these changes to your remote, otherwise it can cause issues for everyone using the repository.

Read file content from S3 bucket with boto3

When you want to read a file with a different configuration than the default one, feel free to use either mpu.aws.s3_read(s3path) directly or the copy-pasted code:

def s3_read(source, profile_name=None):
    """
    Read a file from an S3 source.

    Parameters
    ----------
    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
    profile_name : str, optional
        AWS profile

    Returns
    -------
    content : bytes

    botocore.exceptions.NoCredentialsError
        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
        See https://boto3.readthedocs.io/en/latest/guide/configuration.html
    """
    session = boto3.Session(profile_name=profile_name)
    s3 = session.client('s3')
    bucket_name, key = mpu.aws._s3_path_split(source)
    s3_object = s3.get_object(Bucket=bucket_name, Key=key)
    body = s3_object['Body']
    return body.read()

How to retrieve the hash for the current commit in Git?

Here is another direct-access implementation:

head="$(cat ".git/HEAD")"
while [ "$head" != "${head#ref: }" ]; do
  head="$(cat ".git/${head#ref: }")"
done

This also works over http which is useful for local package archives (I know: for public web sites it's not recommended to make the .git directory accessable):

head="$(curl -s "$baseurl/.git/HEAD")"
while [ "$head" != "${head#ref: }" ]; do
  head="$(curl -s "$baseurl/.git/${head#ref: }")"
done

ADB Driver and Windows 8.1

In Windows 7, 8 or 8.1, in Devices Manager:

  1. Select tree 'Android Device': remove 'Android Composite ADB Interface' [?]
  2. Press on main root of devices tree and call context menu (by right mouse click) and click on 'Update configuration'
  3. After updating your device should appear in 'Other devices'
  4. Select your device, call context menu from it and choose 'Update driver' and perform this updating

How to skip the first n rows in sql query

What about:

SELECT * FROM table LIMIT 50 OFFSET 1

How to check if an element is in an array

Just in case anybody is trying to find if an indexPath is among the selected ones (like in a UICollectionView or UITableView cellForItemAtIndexPath functions):

    var isSelectedItem = false
    if let selectedIndexPaths = collectionView.indexPathsForSelectedItems() as? [NSIndexPath]{
        if contains(selectedIndexPaths, indexPath) {
            isSelectedItem = true
        }
    }

mkdir -p functionality in Python

import os
from os.path import join as join_paths

def mk_dir_recursive(dir_path):

    if os.path.isdir(dir_path):
        return
    h, t = os.path.split(dir_path)  # head/tail
    if not os.path.isdir(h):
        mk_dir_recursive(h)

    new_path = join_paths(h, t)
    if not os.path.isdir(new_path):
        os.mkdir(new_path)

based on @Dave C's answer but with a bug fixed where part of the tree already exists

What is the best free SQL GUI for Linux for various DBMS systems

I'm sticking with DbVisualizer Free until something better comes along.

EDIT/UPDATE: been using https://dbeaver.io/ lately, really enjoying this

Download history stock prices automatically from yahoo finance in python

Extending @Def_Os's answer with an actual demo...

As @Def_Os has already said - using Pandas Datareader makes this task a real fun

In [12]: from pandas_datareader import data

pulling all available historical data for AAPL starting from 1980-01-01

#In [13]: aapl = data.DataReader('AAPL', 'yahoo', '1980-01-01')

# yahoo api is inconsistent for getting historical data, please use google instead.
In [13]: aapl = data.DataReader('AAPL', 'google', '1980-01-01')

first 5 rows

In [14]: aapl.head()
Out[14]:
                 Open       High     Low   Close     Volume  Adj Close
Date
1980-12-12  28.750000  28.875000  28.750  28.750  117258400   0.431358
1980-12-15  27.375001  27.375001  27.250  27.250   43971200   0.408852
1980-12-16  25.375000  25.375000  25.250  25.250   26432000   0.378845
1980-12-17  25.875000  25.999999  25.875  25.875   21610400   0.388222
1980-12-18  26.625000  26.750000  26.625  26.625   18362400   0.399475

last 5 rows

In [15]: aapl.tail()
Out[15]:
                 Open       High        Low      Close    Volume  Adj Close
Date
2016-06-07  99.250000  99.870003  98.959999  99.029999  22366400  99.029999
2016-06-08  99.019997  99.559998  98.680000  98.940002  20812700  98.940002
2016-06-09  98.500000  99.989998  98.459999  99.650002  26419600  99.650002
2016-06-10  98.529999  99.349998  98.480003  98.830002  31462100  98.830002
2016-06-13  98.690002  99.120003  97.099998  97.339996  37612900  97.339996

save all data as CSV file

In [16]: aapl.to_csv('d:/temp/aapl_data.csv')

d:/temp/aapl_data.csv - 5 first rows

Date,Open,High,Low,Close,Volume,Adj Close
1980-12-12,28.75,28.875,28.75,28.75,117258400,0.431358
1980-12-15,27.375001,27.375001,27.25,27.25,43971200,0.408852
1980-12-16,25.375,25.375,25.25,25.25,26432000,0.378845
1980-12-17,25.875,25.999999,25.875,25.875,21610400,0.38822199999999996
1980-12-18,26.625,26.75,26.625,26.625,18362400,0.399475
...

Why do I get access denied to data folder when using adb?

before we start, do you have a rooted phone? if not, I strongly suggest that it's time you make the jump. 99% of the tutorials that help you to do this require that you have a rooted phone (I know b/c I spent about an hour searching for a way to do it without having a rooted phone.. couldn't find any..) also if you think about it, your iPhone also has to be rooted to do this same task. So it's totally reasonable. More about rooting at end of answer.

from your command line type:

adb shell

this takes you to your android shell comand line (you should see something like this: shell@android:/ $ now type:

shell@android:/ $run-as com.domain.yourapp

this should take you directly to the data directory of com.domain.yourapp:

shell@android:/data/data/com.domain.yourapp $ 

if it doesn't (ie if you get an error) then you probably don't have a rooted phone, or you haven't used your root user privileges. To use your root user privileges, type su on the adb command line and see what happens, if you get an error, then you're phone is not rooted. If it's not, root it first then continue these instructions.

from there you can type ls and you'll see all the directories including the dbs:

shell@android:/data/data/com.domain.yourapp $ ls

cache
databases
lib
shared_prefs   

after that you can use sqlite3 to browse the dbase.. if you don't have it installed (you can find it out by typing sqlite3, if you get command not found then you'll have to install it. To install sqlite, follow instructions here.

about rooting: if you've never rooted your phone before, and you're worried about it screwing your phone, I can tell you with full confidence that there is nothing to worry about. there are tonnes of quick and easy phone rooting tutorials for pretty much all the new and old models out there, and you can root your phone even if you have a mac (I rooted my s3 with my mac).

JavaScript, Node.js: is Array.forEach asynchronous?

This is a short asynchronous function to use without requiring third party libs

Array.prototype.each = function (iterator, callback) {
    var iterate = function () {
            pointer++;
            if (pointer >= this.length) {
                callback();
                return;
            }
            iterator.call(iterator, this[pointer], iterate, pointer);
    }.bind(this),
        pointer = -1;
    iterate(this);
};

Array Index Out of Bounds Exception (Java)

for ( i = 0; i < total.length; i++ ); // remove this
{
    if (total[i]!=0)
        System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]);
}

The for loop loops until i=26 (where 26 is total.length) and then your if is executed, going over the bounds of the array. Remove the ; at the end of the for loop.

Disable all table constraints in Oracle

SELECT 'ALTER TABLE '||substr(c.table_name,1,35)|| 
' DISABLE CONSTRAINT '||constraint_name||' ;' 
FROM user_constraints c, user_tables u 
WHERE c.table_name = u.table_name; 

This statement returns the commands which turn off all the constraints including primary key, foreign keys, and another constraints.