Programs & Examples On #Msas

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Below worked for me:

When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/

Error Message : Cannot find or open the PDB file

  1. Please check if the setting Generate Debug Info is Yes which under Project Propeties > Configuration Properties > Linker > Debugging tab. If not, try to change it to Yes.

  2. Those perticular pdb's ( for ntdll.dll, mscoree.dll, kernel32.dll, etc ) are for the windows API and shouldn't be needed for simple apps. However, if you cannot find pdb's for your own compiled projects, I suggest making sure the Project Properties > Configuration Properties > Debugging > Working Directory uses the value from Project Properties > Configuration Properties > General > Output Directory .

  3. You need to run Visual c++ in "Run as Administrator" mode.Right click on the executable and click "Run as Administrator"

Creating a data frame from two vectors using cbind

Vectors and matrices can only be of a single type and cbind and rbind on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.

(Note that in your rbind example, the promotion happens within the c call:

> c(10, "[]", "[[1,2]]")
[1] "10"      "[]"      "[[1,2]]"

If you want a rectangular structure where the columns can be different types, you want a data.frame. Any of the following should get you what you want:

> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
  v1 v2      v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ v1: num  10 20
 $ v2: Factor w/ 1 level "[]": 1 1
 $ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using specifically the data.frame version of cbind)

> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c(10, 20)              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using cbind, but making the first a data.frame so that it combines as data.frames do):

> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c.10..20.              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

How to capture the "virtual keyboard show/hide" event in Android?

2020 Update

This is now possible:

On Android 11, you can do

view.setWindowInsetsAnimationCallback(object : WindowInsetsAnimation.Callback {
    override fun onEnd(animation: WindowInsetsAnimation) {
        super.onEnd(animation)
        val showingKeyboard = view.rootWindowInsets.isVisible(WindowInsets.Type.ime())
        // now use the boolean for something
    }
})

You can also listen to the animation of showing/hiding the keyboard and do a corresponding transition.

I recommend reading Android 11 preview and the corresponding documentation

Before Android 11

However, this work has not been made available in a Compat version, so you need to resort to hacks.

You can get the window insets and if the bottom insets are bigger than some value you find to be reasonably good (by experimentation), you can consider that to be showing the keyboard. This is not great and can fail in some cases, but there is no framework support for that.

This is a good answer on this exact question https://stackoverflow.com/a/36259261/372076. Alternatively, here's a page giving some different approaches to achieve this pre Android 11:

https://developer.salesforce.com/docs/atlas.en-us.noversion.service_sdk_android.meta/service_sdk_android/android_detecting_keyboard.htm


Note

This solution will not work for soft keyboards and onConfigurationChanged will not be called for soft (virtual) keyboards.


You've got to handle configuration changes yourself.

http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange

Sample:

// from the link above
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    
    // Checks whether a hardware keyboard is available
    if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
        Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
    } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
        Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
    }
}

Then just change the visibility of some views, update a field, and change your layout file.

Spring Resttemplate exception handling

I have handled this as below:

try {
  response = restTemplate.postForEntity(requestUrl, new HttpEntity<>(requestBody, headers), String.class);
} catch (HttpStatusCodeException ex) {
  response = new ResponseEntity<String>(ex.getResponseBodyAsString(), ex.getResponseHeaders(), ex.getStatusCode());
}

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Warning! There's a numbers of errors on the Sun JPA 2 example and the resulting pasted content in Pascal's answer. Please consult this post.

This post and the Sun Java EE 6 JPA 2 example really held back my comprehension of JPA 2. After plowing through the Hibernate and OpenJPA manuals and thinking that I had a good understanding of JPA 2, I still got confused afterwards when returning to this post.

Handling a timeout error in python sockets

from foo import * 

adds all the names without leading underscores (or only the names defined in the modules __all__ attribute) in foo into your current module.

In the above code with from socket import * you just want to catch timeout as you've pulled timeout into your current namespace.

from socket import * pulls in the definitions of everything inside of socket but doesn't add socket itself.

try:
    # socketstuff
except timeout:
    print 'caught a timeout'

Many people consider import * problematic and try to avoid it. This is because common variable names in 2 or more modules that are imported in this way will clobber one another.

For example, consider the following three python files:

# a.py
def foo():
    print "this is a's foo function"

# b.py
def foo():
    print "this is b's foo function"

# yourcode.py
from a import *
from b import *
foo()

If you run yourcode.py you'll see just the output "this is b's foo function".

For this reason I'd suggest either importing the module and using it or importing specific names from the module:

For example, your code would look like this with explicit imports:

import socket
from socket import AF_INET, SOCK_DGRAM

def main():
    client_socket = socket.socket(AF_INET, SOCK_DGRAM)
    client_socket.settimeout(1)
    server_host = 'localhost'
    server_port = 1234
    while(True):
        client_socket.sendto('Message', (server_host, server_port))
        try:
            reply, server_address_info = client_socket.recvfrom(1024)
            print reply
        except socket.timeout:
            #more code

Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.

Concatenate strings from several rows using Pandas groupby

For me the above solutions were close but added some unwanted /n's and dtype:object, so here's a modified version:

df.groupby(['name', 'month'])['text'].apply(lambda text: ''.join(text.to_string(index=False))).str.replace('(\\n)', '').reset_index()

How do I delete multiple rows in Entity Framework (without foreach)

Entity Framework Core

3.1 3.0 2.2 2.1 2.0 1.1 1.0

using (YourContext context = new YourContext ())
{
    var widgets = context.Widgets.Where(w => w.WidgetId == widgetId);
    context.Widgets.RemoveRange(widgets);
    context.SaveChanges();
}

Summary:

Removes the given collection of entities from the context underlying the set with each entity being put into the Deleted state such that it will be deleted from the database when SaveChanges is called.

Remarks:

Note that if System.Data.Entity.Infrastructure.DbContextConfiguration.AutoDetectChangesEnabled is set to true (which is the default), then DetectChanges will be called once before delete any entities and will not be called again. This means that in some situations RemoveRange may perform significantly better than calling Remove multiple times would do. Note that if any entity exists in the context in the Added state, then this method will cause it to be detached from the context. This is because an Added entity is assumed not to exist in the database such that trying to delete it does not make sense.

How to get only filenames within a directory using c#?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetNameOfFiles
{
    public class Program
    {
        static void Main(string[] args)
        {
           string[] fileArray = Directory.GetFiles(@"YOUR PATH");
           for (int i = 0; i < fileArray.Length; i++)
           {

               Console.WriteLine(fileArray[i]);
           }
            Console.ReadLine();
        }
    }
}

Android Room - simple select query - Cannot access database on the main thread

Database access on main thread locking the UI is the error, like Dale said.

--EDIT 2--

Since many people may come across this answer... The best option nowadays, generally speaking, is Kotlin Coroutines. Room now supports it directly (currently in beta). https://kotlinlang.org/docs/reference/coroutines-overview.html https://developer.android.com/jetpack/androidx/releases/room#2.1.0-beta01

--EDIT 1--

For people wondering... You have other options. I recommend taking a look into the new ViewModel and LiveData components. LiveData works great with Room. https://developer.android.com/topic/libraries/architecture/livedata.html

Another option is the RxJava/RxAndroid. More powerful but more complex than LiveData. https://github.com/ReactiveX/RxJava

--Original answer--

Create a static nested class (to prevent memory leak) in your Activity extending AsyncTask.

private static class AgentAsyncTask extends AsyncTask<Void, Void, Integer> {

    //Prevent leak
    private WeakReference<Activity> weakActivity;
    private String email;
    private String phone;
    private String license;

    public AgentAsyncTask(Activity activity, String email, String phone, String license) {
        weakActivity = new WeakReference<>(activity);
        this.email = email;
        this.phone = phone;
        this.license = license;
    }

    @Override
    protected Integer doInBackground(Void... params) {
        AgentDao agentDao = MyApp.DatabaseSetup.getDatabase().agentDao();
        return agentDao.agentsCount(email, phone, license);
    }

    @Override
    protected void onPostExecute(Integer agentsCount) {
        Activity activity = weakActivity.get();
        if(activity == null) {
            return;
        }

        if (agentsCount > 0) {
            //2: If it already exists then prompt user
            Toast.makeText(activity, "Agent already exists!", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(activity, "Agent does not exist! Hurray :)", Toast.LENGTH_LONG).show();
            activity.onBackPressed();
        }
    }
}

Or you can create a final class on its own file.

Then execute it in the signUpAction(View view) method:

new AgentAsyncTask(this, email, phone, license).execute();

In some cases you might also want to hold a reference to the AgentAsyncTask in your activity so you can cancel it when the Activity is destroyed. But you would have to interrupt any transactions yourself.

Also, your question about the Google's test example... They state in that web page:

The recommended approach for testing your database implementation is writing a JUnit test that runs on an Android device. Because these tests don't require creating an activity, they should be faster to execute than your UI tests.

No Activity, no UI.

SQL Server 2008: How to query all databases sizes?

All this examples work fine on most of my database servers. However if you have 1 server with multiple instances and all those servers those query's give you no result.

For instance the first query gives a result like:

name    DataFileSizeMB  LogFileSizeMB
master  NULL    NULL
tempdb  NULL    NULL
model   NULL    NULL
msdb    NULL    NULL

So the databases are selected from sys.databases, however the table sys.master_files seems to be empty or gives no result.

Even a simple query as select * from sys.master_files has a result of 0 records. You don't receive any errors but no records are found. On my servers with only 1 database instance this works fine.

bash: mkvirtualenv: command not found

Use this procedure to create virtual env in ubuntu

Step 1

Install pip

   sudo apt-get install python-pip

step 2

Install virtualenv

   sudo pip install virtualenv

step 3

Create a dir to store your virtualenvs (I use ~/.virtualenvs)

   mkdir ~/.virtualenvs

or use this command to install specific version of python in env

virtualenv -p /usr/bin/python3.6 venv

step 4

   sudo pip install virtualenvwrapper

step 5

   sudo nano ~/.bashrc

step 6

Add this two line code at the end of the bashrc file

  export WORKON_HOME=~/.virtualenvs
  source /usr/local/bin/virtualenvwrapper.sh

step 7

Open new terminal (recommended)

step 8

Create a new virtualenv

  mkvirtualenv myawesomeproject

step 9

To load or switch between virtualenvs, use the workon command:

  workon myawesomeproject

step 10

To exit your new virtualenv, use

 deactivate

and make sure using pip vs pip3

OR follow the steps below to install virtual environment using python3

Install env

python3 -m venv my-project-env

and activate your virtual environment using the following command:

source my-project-env/bin/activate

or if you want particular python version

virtualenv --python=python3.7.5 myenv

Powershell import-module doesn't find modules

I think that the Import-Module is trying to find the module in the default directory C:\Windows\System32\WindowsPowerShell\v1.0\Modules.

Try to put the full path, or copy it to C:\Windows\System32\WindowsPowerShell\v1.0\Modules

How to strip comma in Python string

Use replace method of strings not strip:

s = s.replace(',','')

An example:

>>> s = 'Foo, bar'
>>> s.replace(',',' ')
'Foo  bar'
>>> s.replace(',','')
'Foo bar'
>>> s.strip(',') # clears the ','s at the start and end of the string which there are none
'Foo, bar'
>>> s.strip(',') == s
True

Where is the application.properties file in a Spring Boot project?

You will need to add the application.properties file in your classpath.

If you are using Maven or Gradle, you can just put the file under src/main/resources.
If you are not using Maven or any other build tools, put that under your src folder and you should be fine.

Then you can just add an entry server.port = xxxx in the properties file.

How to disable phone number linking in Mobile Safari?

I too have this problem: Safari and other mobile browsers transform the VAT IDs into phone numbers. So I want a clean method to avoid it on a single element, not the whole page (or site).
I'm sharing a possible solution I found, it is suboptimal but still it is pretty viable: I put, inside the number I don't want to become a tel: link, the &#8288; HTML entity which is the Word-Joiner invisible character. I tried to stay more semantic (well, at least a sort of) by putting this char in some meaning spot, e.g. for the VAT ID I chose to put it between the different groups of digit according to its format so for an Italian VAT I wrote: 0613605&#8288;048&#8288;8 which renders in 0613605⁠048⁠8 and it is not transformed in a telephone number.

Generating unique random numbers (integers) between 0 and 'x'

I think, this is the most human approach (with using break from while loop), I explained it's mechanism in comments.

function generateRandomUniqueNumbersArray (limit) {

    //we need to store these numbers somewhere
    const array = new Array();
    //how many times we added a valid number (for if statement later)
    let counter = 0;

    //we will be generating random numbers until we are satisfied
    while (true) {

        //create that number
        const newRandomNumber = Math.floor(Math.random() * limit);

        //if we do not have this number in our array, we will add it
        if (!array.includes(newRandomNumber)) {
            array.push(newRandomNumber);
            counter++;
        }

        //if we have enought of numbers, we do not need to generate them anymore
        if (counter >= limit) {
            break;
        }
    }

    //now hand over this stuff
    return array;
}

You can of course add different limit (your amount) to the last 'if' statement, if you need less numbers, but be sure, that it is less or equal to the limit of numbers itself - otherwise it will be infinite loop.

Java generating non-repeating random numbers

HashSet<Integer>hashSet=new HashSet<>();
Random random = new Random();
//now add random number to this set
while(true)
{
    hashSet.add(random.nextInt(1000));
    if(hashSet.size()==1000)
        break;
}

Find size of object instance in bytes in c#

Simplest way is: int size = *((int*)type.TypeHandle.Value + 1)

I know this is implementation detail but GC relies on it and it needs to be as close to start of the methodtable for efficiency plus taking into consideration how GC code complex is nobody will dare to change it in future. In fact it works for every minor/major versions of .net framework+.net core. (Currently unable to test for 1.0)
If you want more reliable way, emit a struct in a dynamic assembly with [StructLayout(LayoutKind.Auto)] with exact same fields in same order, take its size with sizeof IL instruction. You may want to emit a static method within struct which simply returns this value. Then add 2*IntPtr.Size for object header. This should give you exact value.
But if your class derives from another class, you need to find each size of base class seperatly and add them + 2*Inptr.Size again for header. You can do this by getting fields with BindingFlags.DeclaredOnly flag.
Arrays and strings just adds that size its length * element size. For cumulative size of aggreagate objects you need to implement more sophisticated solution which involves visiting every field and inspect its contents.

Convert pandas dataframe to NumPy array

Two ways to convert the data-frame to its Numpy-array representation.

  • mah_np_array = df.as_matrix(columns=None)

  • mah_np_array = df.values

Doc: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.as_matrix.html

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

Quick summary, you can do either:

  1. Include the JavaFX modules via --module-path and --add-modules like in José's answer.

    OR

  2. Once you have JavaFX libraries added to your project (either manually or via maven/gradle import), add the module-info.java file similar to the one specified in this answer. (Note that this solution makes your app modular, so if you use other libraries, you will also need to add statements to require their modules inside the module-info.java file).


This answer is a supplement to Jose's answer.

The situation is this:

  1. You are using a recent Java version, e.g. 13.
  2. You have a JavaFX application as a Maven project.
  3. In your Maven project you have the JavaFX plugin configured and JavaFX dependencies setup as per Jose's answer.
  4. You go to the source code of your main class which extends Application, you right-click on it and try to run it.
  5. You get an IllegalAccessError involving an "unnamed module" when trying to launch the app.

Excerpt for a stack trace generating an IllegalAccessError when trying to run a JavaFX app from Intellij Idea:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x45069d0e) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x45069d0e
    at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
    at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
    at org.jewelsea.demo.javafx.springboot.Main.start(Main.java:13)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application org.jewelsea.demo.javafx.springboot.Main

OK, now you are kind of stuck and have no clue what is going on.

What has actually happened is this:

  1. Maven has successfully downloaded the JavaFX dependencies for your application, so you don't need to separately download the dependencies or install a JavaFX SDK or module distribution or anything like that.
  2. Idea has successfully imported the modules as dependencies to your project, so everything compiles OK and all of the code completion and everything works fine.

So it seems everything should be OK. BUT, when you run your application, the code in the JavaFX modules is failing when trying to use reflection to instantiate instances of your application class (when you invoke launch) and your FXML controller classes (when you load FXML). Without some help, this use of reflection can fail in some cases, generating the obscure IllegalAccessError. This is due to a Java module system security feature which does not allow code from other modules to use reflection on your classes unless you explicitly allow it (and the JavaFX application launcher and FXMLLoader both require reflection in their current implementation in order for them to function correctly).

This is where some of the other answers to this question, which reference module-info.java, come into the picture.

So let's take a crash course in Java modules:

The key part is this:

4.9. Opens

If we need to allow reflection of private types, but we don't want all of our code exposed, we can use the opens directive to expose specific packages.

But remember, this will open the package up to the entire world, so make sure that is what you want:

module my.module { opens com.my.package; }

So, perhaps you don't want to open your package to the entire world, then you can do:

4.10. Opens … To

Okay, so reflection is great sometimes, but we still want as much security as we can get from encapsulation. We can selectively open our packages to a pre-approved list of modules, in this case, using the opens…to directive:

module my.module { opens com.my.package to moduleOne, moduleTwo, etc.; }

So, you end up creating a src/main/java/module-info.java class which looks like this:

module org.jewelsea.demo.javafx.springboot {
    requires javafx.fxml;
    requires javafx.controls;
    requires javafx.graphics;
    opens org.jewelsea.demo.javafx.springboot to javafx.graphics,javafx.fxml;
}

Where, org.jewelsea.demo.javafx.springboot is the name of the package which contains the JavaFX Application class and JavaFX Controller classes (replace this with the appropriate package name for your application). This tells the Java runtime that it is OK for classes in the javafx.graphics and javafx.fxml to invoke reflection on the classes in your org.jewelsea.demo.javafx.springboot package. Once this is done, and the application is compiled and re-run things will work fine and the IllegalAccessError generated by JavaFX's use of reflection will no longer occur.

But what if you don't want to create a module-info.java file

If instead of using the the Run button in the top toolbar of IDE to run your application class directly, you instead:

  1. Went to the Maven window in the side of the IDE.
  2. Chose the javafx maven plugin target javafx.run.
  3. Right-clicked on that and chose either Run Maven Build or Debug....

Then the app will run without the module-info.java file. I guess this is because the maven plugin is smart enough to dynamically include some kind of settings which allows the app to be reflected on by the JavaFX classes even without a module-info.java file, though I don't know how this is accomplished.

To get that setting transferred to the Run button in the top toolbar, right-click on the javafx.run Maven target and choose the option to Create Run/Debug Configuration for the target. Then you can just choose Run from the top toolbar to execute the Maven target.

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

Detect change to selected date with bootstrap-datepicker

Here is my code for that:

$('#date-daily').datepicker().on('changeDate', function(e) {
    //$('#other-input').val(e.format(0,"dd/mm/yyyy"));
    //alert(e.date);
    //alert(e.format(0,"dd/mm/yyyy"));
    //console.log(e.date); 
});

Just uncomment the one you prefer. The first option changes the value of other input element. The second one alerts the date with datepicker default format. The third one alerts the date with your own custom format. The last option outputs to log (default format date).

It's your choice to use the e.date , e.dates (for múltiple date input) or e.format(...).

here some more info

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

In this case a[4] is the 5th integer in the array a, ap is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap now holds 45 and when you try to de-reference it (by doing *ap) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.

You should do ap = &(a[4]); or ap = a + 4;

In c array names decays to pointer, so a points to the 1st element of the array.
In this way, a is equivalent to &(a[0]).

Is there any way to show a countdown on the lockscreen of iphone?

A today extension would be the most fitting solution.

Also you could do something on the lock screen with local notifications queued up to fire at regular intervals showing the latest countdown value.

Convert datetime object to a String of date only in Python

The sexiest version by far is with format strings.

from datetime import datetime

print(f'{datetime.today():%Y-%m-%d}')

Daemon Threads Explanation

When your second thread is non-Daemon, your application's primary main thread cannot quit because its exit criteria is being tied to the exit also of non-Daemon thread(s). Threads cannot be forcibly killed in python, therefore your app will have to really wait for the non-Daemon thread(s) to exit. If this behavior is not what you want, then set your second thread as daemon so that it won't hold back your application from exiting.

PHP Fatal error: Cannot redeclare class

It actually means that class is already declared in the page and you are trying to recreate it.

A simple technique is as follow.

I solved the issue with the following. Hope this will help you a bit.

if(!class_exists("testClassIfExist"))
{
    require_once("testClassIfExist.php");
}

Default instance name of SQL Server Express

If you navigate to where you have installed SQLExpress, e.g.

C:\Program Files\Microsoft SQL Server\110\Tools\Binn

You can run SQLLocalDB.exe and get a list of the all instances installed on your machine.

C:\Program Files\Microsoft SQL Server\110\Tools\Binn>SqlLocalDB.exe info
MSSQLLocalDB
ProjectsV12
v11.0

Then you can get further information on the instance.

C:\Program Files\Microsoft SQL Server\110\Tools\Binn>SqlLocalDB.exe info MSSQLLocalDB Name: MSSQLLocalDB
Version: 13.0.1601.5
Shared name:
Owner: Domain\User
Auto-create: Yes
State: Stopped
Last start time: 22/09/2016 10:19:33
Instance pipe name:

How to perform string interpolation in TypeScript?

Just use special `

var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;

You can see more examples here.

How to call same method for a list of objects?

It seems like there would be a more Pythonic way of doing this, but I haven't found it yet.

I use "map" sometimes if I'm calling the same function (not a method) on a bunch of objects:

map(do_something, a_list_of_objects)

This replaces a bunch of code that looks like this:

 do_something(a)
 do_something(b)
 do_something(c)
 ...

But can also be achieved with a pedestrian "for" loop:

  for obj in a_list_of_objects:
       do_something(obj)

The downside is that a) you're creating a list as a return value from "map" that's just being throw out and b) it might be more confusing that just the simple loop variant.

You could also use a list comprehension, but that's a bit abusive as well (once again, creating a throw-away list):

  [ do_something(x) for x in a_list_of_objects ]

For methods, I suppose either of these would work (with the same reservations):

map(lambda x: x.method_call(), a_list_of_objects)

or

[ x.method_call() for x in a_list_of_objects ]

So, in reality, I think the pedestrian (yet effective) "for" loop is probably your best bet.

how to change class name of an element by jquery

Instead of removeClass and addClass, you can also do it like this:

$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer');

Representing EOF in C code?

I've read all the comments. It's interesting to notice what happens when you print out this:

printf("\nInteger =    %d\n", EOF);             //OUTPUT = -1
printf("Decimal =    %d\n", EOF);               //OUTPUT = -1
printf("Octal =  %o\n", EOF);                   //OUTPUT = 37777777777
printf("Hexadecimal =  %x\n", EOF);             //OUTPUT = ffffffff
printf("Double and float =  %f\n", EOF);        //OUTPUT = 0.000000
printf("Long double =  %Lf\n", EOF);            //OUTPUT = 0.000000
printf("Character =  %c\n", EOF);               //OUTPUT = nothing

As we can see here, EOF is NOT a character (whatsoever).

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

Try this if nothing works incase of permission error, this will solve it.

sudo chown user -R env

as an example for my case

sudo chown ubuntu -R venv

How can I make a DateTimePicker display an empty string?

Obfuscating the value by using the CustomFormat property, using checkbox cbEnableEndDate as the flag to indicate whether other code should ignore the value:

If dateTaskEnd > Date.FromOADate(0) Then
    dtTaskEnd.Format = DateTimePickerFormat.Custom
    dtTaskEnd.CustomFormat = "yyyy-MM-dd"
    dtTaskEnd.Value = dateTaskEnd 
    dtTaskEnd.Enabled = True
    cbEnableEndDate.Checked = True
Else
    dtTaskEnd.Format = DateTimePickerFormat.Custom
    dtTaskEnd.CustomFormat = " "
    dtTaskEnd.Value = Date.FromOADate(0)
    dtTaskEnd.Enabled = False
    cbEnableEndDate.Checked = False
End If

What is the right way to debug in iPython notebook?

Just type import pdb in jupyter notebook, and then use this cheatsheet to debug. It's very convenient.

c --> continue, s --> step, b 12 --> set break point at line 12 and so on.

Some useful links: Python Official Document on pdb, Python pdb debugger examples for better understanding how to use the debugger commands.

Some useful screenshots: enter image description hereenter image description here

'tsc command not found' in compiling typescript

Non-admin solution

I do not have admin privileges since this machine was issued by my job.

  • get path of where node modules are being installed and copy to clipboard
    • npm config get prefix | clip
    • don't have clip? just copy output from npm config get prefix
  • add copied path to environment variables
    • my preferred method (Windows)
    • (Ctrl + R), paste rundll32 sysdm.cpl,EditEnvironmentVariables
    • under User Variables, double-click on Path > New > Paste copied path

Strict Standards: Only variables should be assigned by reference PHP 5.4

It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.

Embed an External Page Without an Iframe?

You could load the external page with jquery:

<script>$("#testLoad").load("http://www.somesite.com/somepage.html");</script>
<div id="testLoad"></div>
//would this help

How do I get the total number of unique pairs of a set in the database?

TLDR; The formula is n(n-1)/2 where n is the number of items in the set.

Explanation:

To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA), you can calculate the summation of 1 + 2 + ... + (n-1) where n is the number of items in the set.

The reasoning is as follows, say you have 4 items:

A
B
C
D

The number of items that can be paired with A is 3, or n-1:

AB
AC
AD

It follows that the number of items that can be paired with B is n-2 (because B has already been paired with A):

BC
BD

and so on...

(n-1) + (n-2) + ... + (n-(n-1))

which is the same as

1 + 2 + ... + (n-1)

or

n(n-1)/2

Reading settings from app.config or web.config in .NET

Just for completeness, there's another option available for web projects only: System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]

The benefit of this is that it doesn't require an extra reference to be added, so it may be preferable for some people.

Get the new record primary key ID from MySQL insert query?

i used return $this->db->insert_id(); for Codeigniter

How to remove close button on the jQuery UI dialog?

For the deactivating the class, the short code:

$(".ui-dialog-titlebar-close").hide();

may be used.

How to delete all data from solr and hbase

Use the "match all docs" query in a delete by query command: :

You must also commit after running the delete so, to empty the index, run the following two commands:

curl http://localhost:8983/solr/update --data '<delete><query>*:*</query></delete>' -H 'Content-type:text/xml; charset=utf-8'

curl http://localhost:8983/solr/update --data '<commit/>' -H 'Content-type:text/xml; charset=utf-8'

Angular 4 Pipe Filter

I know this is old, but i think i have good solution. Comparing to other answers and also comparing to accepted, mine accepts multiple values. Basically filter object with key:value search parameters (also object within object). Also it works with numbers etc, cause when comparing, it converts them to string.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'filter'})
export class Filter implements PipeTransform {
    transform(array: Array<Object>, filter: Object): any {
        let notAllKeysUndefined = false;
        let newArray = [];

        if(array.length > 0) {
            for (let k in filter){
                if (filter.hasOwnProperty(k)) {
                    if(filter[k] != undefined && filter[k] != '') {
                        for (let i = 0; i < array.length; i++) {
                            let filterRule = filter[k];

                            if(typeof filterRule === 'object') {
                                for(let fkey in filterRule) {
                                    if (filter[k].hasOwnProperty(fkey)) {
                                        if(filter[k][fkey] != undefined && filter[k][fkey] != '') {
                                            if(this.shouldPushInArray(array[i][k][fkey], filter[k][fkey])) {
                                                newArray.push(array[i]);
                                            }
                                            notAllKeysUndefined = true;
                                        }
                                    }
                                }
                            } else {
                                if(this.shouldPushInArray(array[i][k], filter[k])) {
                                    newArray.push(array[i]);
                                }
                                notAllKeysUndefined = true;
                            }
                        }
                    }
                }
            }
            if(notAllKeysUndefined) {
                return newArray;
            }
        }

        return array;
    }

    private shouldPushInArray(item, filter) {
        if(typeof filter !== 'string') {
            item = item.toString();
            filter = filter.toString();
        }

        // Filter main logic
        item = item.toLowerCase();
        filter = filter.toLowerCase();
        if(item.indexOf(filter) !== -1) {
            return true;
        }
        return false;
    }
}

Making a button invisible by clicking another button in HTML

To get an element by its ID, use this:

document.getElementById("p2")

Instead of:

document.getElementsByName("p2")

So the final product would be:

document.getElementsById("p2").style.visibility = "hidden";

How to open a page in a new window or tab from code-behind

You can use scriptmanager.registerstartupscript to call a JavaScript function.

Inside that function, you can open a new window.

How do I determine scrollHeight?

You can also use:

$('#test').context.scrollHeight

How do I create a foreign key in SQL Server?

If you want to create two table's columns into a relationship by using a query try the following:

Alter table Foreign_Key_Table_name add constraint 
Foreign_Key_Table_name_Columnname_FK
Foreign Key (Column_name) references 
Another_Table_name(Another_Table_Column_name)

Check if instance is of a type

A little more compact than the other answers if you want to use c as a TForm:

if(c is TForm form){
    form.DoStuff();
}

How to install Guest addition in Mac OS as guest and Windows machine as host

You need to update your virtualbox sw. On new version, there is VBoxDarwinAdditions.pkg included in a additions iso image, in older versions is missing.

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

In Linux(Ubuntu) just install the driver like so:

sudo apt-get install php-pgsql

This will install the driver with using your php current version.

Get Android Device Name

I solved this by getting the Bluetooth name, but not from the BluetoothAdapter (that needs Bluetooth permission).

Here's the code:

Settings.Secure.getString(getContentResolver(), "bluetooth_name");

No extra permissions needed.

Check if a string is a date value

Here's a minimalist version.

var isDate = function (date) {
    return!!(function(d){return(d!=='Invalid Date'&&!isNaN(d))})(new Date(date));
}

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

What works for me was right-click on the .ps1 file and then properties. Click the "UNBLOCK" button. Works great fir me after spending hours trying to change the policies.

Exiting from python Command Line

I recommend you exit the Python interpreter with Ctrl-D. This is the old ASCII code for end-of-file or end-of-transmission.

Fit Image in ImageButton in Android

I'm using android:scaleType="fitCenter" with satisfaction.

Python Finding Prime Factors

This question was the first link that popped up when I googled "python prime factorization". As pointed out by @quangpn88, this algorithm is wrong (!) for perfect squares such as n = 4, 9, 16, ... However, @quangpn88's fix does not work either, since it will yield incorrect results if the largest prime factor occurs 3 or more times, e.g., n = 2*2*2 = 8 or n = 2*3*3*3 = 54.

I believe a correct, brute-force algorithm in Python is:

def largest_prime_factor(n):
    i = 2
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
    return n

Don't use this in performance code, but it's OK for quick tests with moderately large numbers:

In [1]: %timeit largest_prime_factor(600851475143)
1000 loops, best of 3: 388 µs per loop

If the complete prime factorization is sought, this is the brute-force algorithm:

def prime_factors(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return factors

Dynamically updating plot in matplotlib

I know I'm late to answer this question, but for your issue you could look into the "joystick" package. I designed it for plotting a stream of data from the serial port, but it works for any stream. It also allows for interactive text logging or image plotting (in addition to graph plotting). No need to do your own loops in a separate thread, the package takes care of it, just give the update frequency you wish. Plus the terminal remains available for monitoring commands while plotting. See http://www.github.com/ceyzeriat/joystick/ or https://pypi.python.org/pypi/joystick (use pip install joystick to install)

Just replace np.random.random() by your real data point read from the serial port in the code below:

import joystick as jk
import numpy as np
import time

class test(jk.Joystick):
    # initialize the infinite loop decorator
    _infinite_loop = jk.deco_infinite_loop()

    def _init(self, *args, **kwargs):
        """
        Function called at initialization, see the doc
        """
        self._t0 = time.time()  # initialize time
        self.xdata = np.array([self._t0])  # time x-axis
        self.ydata = np.array([0.0])  # fake data y-axis
        # create a graph frame
        self.mygraph = self.add_frame(jk.Graph(name="test", size=(500, 500), pos=(50, 50), fmt="go-", xnpts=10000, xnptsmax=10000, xylim=(None, None, 0, 1)))

    @_infinite_loop(wait_time=0.2)
    def _generate_data(self):  # function looped every 0.2 second to read or produce data
        """
        Loop starting with the simulation start, getting data and
    pushing it to the graph every 0.2 seconds
        """
        # concatenate data on the time x-axis
        self.xdata = jk.core.add_datapoint(self.xdata, time.time(), xnptsmax=self.mygraph.xnptsmax)
        # concatenate data on the fake data y-axis
        self.ydata = jk.core.add_datapoint(self.ydata, np.random.random(), xnptsmax=self.mygraph.xnptsmax)
        self.mygraph.set_xydata(t, self.ydata)

t = test()
t.start()
t.stop()

How to sort an STL vector?

this is my approach to solve this generally. It extends the answer from Steve Jessop by removing the requirement to set template arguments explicitly and adding the option to also use functoins and pointers to methods (getters)

#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>

using namespace std;

template <typename T, typename U>
struct CompareByGetter {
    U (T::*getter)() const;
    CompareByGetter(U (T::*getter)() const) : getter(getter) {};
    bool operator()(const T &lhs, const T &rhs) {
        (lhs.*getter)() < (rhs.*getter)();
    }
};

template <typename T, typename U>
CompareByGetter<T,U> by(U (T::*getter)() const) {
    return CompareByGetter<T,U>(getter);
}

//// sort_by
template <typename T, typename U>
struct CompareByMember {
    U T::*field;
    CompareByMember(U T::*f) : field(f) {}
    bool operator()(const T &lhs, const T &rhs) {
        return lhs.*field < rhs.*field;
    }
};

template <typename T, typename U>
CompareByMember<T,U> by(U T::*f) {
    return CompareByMember<T,U>(f);
}

template <typename T, typename U>
struct CompareByFunction {
    function<U(T)> f;
    CompareByFunction(function<U(T)> f) : f(f) {}
    bool operator()(const T& a, const T& b) const {
        return f(a) < f(b);
    }
};

template <typename T, typename U>
CompareByFunction<T,U> by(function<U(T)> f) {
    CompareByFunction<T,U> cmp{f};
    return cmp;
}

struct mystruct {
    double x,y,z;
    string name;
    double length() const {
        return sqrt( x*x + y*y + z*z );
    }
};

ostream& operator<< (ostream& os, const mystruct& ms) {
    return os << "{ " << ms.x << ", " << ms.y << ", " << ms.z << ", " << ms.name << " len: " << ms.length() << "}";
}

template <class T>
ostream& operator<< (ostream& os, std::vector<T> v) {
    os << "[";
    for (auto it = begin(v); it != end(v); ++it) {
        if ( it != begin(v) ) {
            os << " ";
        }
        os << *it;
    }
    os << "]";
    return os;
}

void sorting() {
    vector<mystruct> vec1 = { {1,1,0,"a"}, {0,1,2,"b"}, {-1,-5,0,"c"}, {0,0,0,"d"} };

    function<string(const mystruct&)> f = [](const mystruct& v){return v.name;};

    cout << "unsorted  " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(&mystruct::x) );
    cout << "sort_by x " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(&mystruct::length));
    cout << "sort_by len " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(f) );
    cout << "sort_by name " << vec1 << endl;
}

Apache and Node.js on the Same Server

Great question!

There are many websites and free web apps implemented in PHP that run on Apache, lots of people use it so you can mash up something pretty easy and besides, its a no-brainer way of serving static content. Node is fast, powerful, elegant, and a sexy tool with the raw power of V8 and a flat stack with no in-built dependencies.

I also want the ease/flexibility of Apache and yet the grunt and elegance of Node.JS, why can't I have both?

Fortunately with the ProxyPass directive in the Apache httpd.conf its not too hard to pipe all requests on a particular URL to your Node.JS application.

ProxyPass /node http://localhost:8000

Also, make sure the following lines are NOT commented out so you get the right proxy and submodule to reroute http requests:

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Then run your Node app on port 8000!

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Apache!\n');
}).listen(8000, '127.0.0.1');

Then you can access all Node.JS logic using the /node/ path on your url, the rest of the website can be left to Apache to host your existing PHP pages:

enter image description here

Now the only thing left is convincing your hosting company let your run with this configuration!!!

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

This is all you need:

  1. Right-click on your project, select Maven -> Remove Maven Nature.

  2. Open you terminal, navgate to your project folder and run mvn eclipse:clean

  3. Right click on your Project and select Configure -> Convert into Maven Project

  4. Right click on your Project and select Maven -> Update Project

What exactly is an instance in Java?

The Literal meaning of instance is "an example or single occurrence of something." which is very closer to the Instance in Java terminology.

Java follows dynamic loading, which is not like C language where the all code is copied into the RAM at runtime. Lets capture this with an example.

   class A
    {
    int x=0;
    public static void main(String [] args)    
     {
    int y=0;
    y=y+1;
    x=x+1;
     }   

    }

Let us compile and run this code.

step 1: javac A.class (.class file is generated which is byte code)

step 2: java A (.class file is converted into executable code)

During the step 2,The main method and the static elements are loaded into the RAM for execution. In the above scenario, No issue until the line y=y+1. But whenever x=x+1 is executed, the run time error will be thrown as the JVM does not know what the x is which is declared outside the main method(non-static).

So If by some means the content of .class file is available in the memory for CPU to execute, there is no more issue.

This is done through creating the Object and the keyword NEW does this Job.

"The concept of reserving memory in the RAM for the contents of hard disk (here .class file) at runtime is called Instance "

The Object is also called the instance of the class.

How do I filter query objects by date range in Django?

Use

Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"])

Or if you are just trying to filter month wise:

Sample.objects.filter(date__year='2011', 
                      date__month='01')

Edit

As Bernhard Vallant said, if you want a queryset which excludes the specified range ends you should consider his solution, which utilizes gt/lt (greater-than/less-than).

Converting 'ArrayList<String> to 'String[]' in Java

List <String> list = ...
String[] array = new String[list.size()];
int i=0;
for(String s: list){
  array[i++] = s;
}

How to get current time and date in Android

Actually, it's safer to set the current timezone set on the device with Time.getCurrentTimezone(), or else you will get the current time in UTC.

Time today = new Time(Time.getCurrentTimezone());
today.setToNow();

Then, you can get all the date fields you want, like, for example:

textViewDay.setText(today.monthDay + "");             // Day of the month (1-31)
textViewMonth.setText(today.month + "");              // Month (0-11)
textViewYear.setText(today.year + "");                // Year 
textViewTime.setText(today.format("%k:%M:%S"));  // Current time

See android.text.format.Time class for all the details.

UPDATE

As many people are pointing out, Google says this class has a number of issues and is not supposed to be used anymore:

This class has a number of issues and it is recommended that GregorianCalendar is used instead.

Known issues:

For historical reasons when performing time calculations all arithmetic currently takes place using 32-bit integers. This limits the reliable time range representable from 1902 until 2037.See the wikipedia article on the Year 2038 problem for details. Do not rely on this behavior; it may change in the future. Calling switchTimezone(String) on a date that cannot exist, such as a wall time that was skipped due to a DST transition, will result in a date in 1969 (i.e. -1, or 1 second before 1st Jan 1970 UTC). Much of the formatting / parsing assumes ASCII text and is therefore not suitable for use with non-ASCII scripts.

Best Practices: working with long, multiline strings in PHP?

I like this method a little more for Javascript but it seems worth including here because it has not been mentioned yet.

$var = "pizza";

$text = implode(" ", [
  "I love me some",
  "really large",
  $var,
  "pies.",
]);

// "I love me some really large pizza pies."

For smaller things, I find it is often easier to work with array structures compared to concatenated strings.

Related: implode vs concat performance

Quicksort with Python

Here's an easy implementation:-

def quicksort(array):
            if len(array) < 2:
                  return array
            else:
                  pivot= array[0]
                  less = [i for i in array[1:] if i <= pivot]

                  greater = [i for i in array[1:] if i > pivot]

                  return quicksort(less) + [pivot] + quicksort(greater)

print(quicksort([10, 5, 2, 3]))

How do I install Keras and Theano in Anaconda Python on Windows?

In windows with anaconda, just go on conda prompt and use this command

conda install --channel https://conda.anaconda.org/conda-forge keras

Django - filtering on foreign key properties

Asset.objects.filter( project__name__contains="Foo" )

Android ADB devices unauthorized

In sequence:

    adb kill-server
  • in your DEVICE SETUP, go to developer-options end disable usb-debugging

  • press REVOKE USB debugging authorizations, click OK

  • enable usb-debugging

    adb start-server
    

SELECT with a Replace()

This will work:

SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'

How to convert byte[] to InputStream?

ByteArrayInputStream extends InputStream:

InputStream myInputStream = new ByteArrayInputStream(myBytes); 

Decompile an APK, modify it and then recompile it

I know this question is answered still, I would like to pass an information how to get source code from apk with out dexjar.

There is an online decompiler for android apks

  1. Upload apk from local machine
  2. Wait some moments
  3. Download source code in zip format

I don't know how reliable is this.

@darkheir Answer is the manual way to do decompile apk. It helps us to understand different phases in Apk creation.

Once you have source code , follow the step mentioned in the accepted answer

Report so many ads on this links Another online Apk De-compiler @Andrew Rukin : http://www.javadecompilers.com/apk

Still worth. Hats Off to creators.

Subtracting two lists in Python

c = [i for i in b if i not in a]

Why did my Git repo enter a detached HEAD state?

try

git reflog 

this gives you a history of how your HEAD and branch pointers where moved in the past.

e.g. :

88ea06b HEAD@{0}: checkout: moving from DEVELOPMENT to remotes/origin/SomeNiceFeature e47bf80 HEAD@{1}: pull origin DEVELOPMENT: Fast-forward

the top of this list is one reasone one might encounter a DETACHED HEAD state ... checking out a remote tracking branch.

Git pull till a particular commit

You can also pull the latest commit and just undo until the commit you desire:

git pull origin master
git reset --hard HEAD~1

Replace master with your desired branch.

Use git log to see to which commit you would like to revert:

git log

Personally, this has worked for me better.

Basically, what this does is pulls the latest commit, and you manually revert commits one by one. Use git log in order to see commit history.

Good points: Works as advertised. You don't have to use commit hash or pull unneeded branches.

Bad points: You need to revert commits on by one.

WARNING: Commit/stash all your local changes, because with --hard you are going to lose them. Use at your own risk!

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

I could find this solution and is working fine:

cd /Applications/Python\ 3.7/
./Install\ Certificates.command

Convert a Map<String, String> to a POJO

@Hamedz if use many data, use Jackson to convert light data, use apache... TestCase:

import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; public class TestPerf { public static final int LOOP_MAX_COUNT = 1000; public static void main(String[] args) { Map<String, Object> map = new HashMap<>(); map.put("success", true); map.put("number", 1000); map.put("longer", 1000L); map.put("doubler", 1000D); map.put("data1", "testString"); map.put("data2", "testString"); map.put("data3", "testString"); map.put("data4", "testString"); map.put("data5", "testString"); map.put("data6", "testString"); map.put("data7", "testString"); map.put("data8", "testString"); map.put("data9", "testString"); map.put("data10", "testString"); runBeanUtilsPopulate(map); runJacksonMapper(map); } private static void runBeanUtilsPopulate(Map<String, Object> map) { long t1 = System.currentTimeMillis(); for (int i = 0; i < LOOP_MAX_COUNT; i++) { try { TestClass bean = new TestClass(); BeanUtils.populate(bean, map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } long t2 = System.currentTimeMillis(); System.out.println("BeanUtils t2-t1 = " + String.valueOf(t2 - t1)); } private static void runJacksonMapper(Map<String, Object> map) { long t1 = System.currentTimeMillis(); for (int i = 0; i < LOOP_MAX_COUNT; i++) { ObjectMapper mapper = new ObjectMapper(); TestClass testClass = mapper.convertValue(map, TestClass.class); } long t2 = System.currentTimeMillis(); System.out.println("Jackson t2-t1 = " + String.valueOf(t2 - t1)); } @Data @AllArgsConstructor @NoArgsConstructor public static class TestClass { private Boolean success; private Integer number; private Long longer; private Double doubler; private String data1; private String data2; private String data3; private String data4; private String data5; private String data6; private String data7; private String data8; private String data9; private String data10; } }

Controller not a function, got undefined, while defining controllers globally

If you're using routes (high probability) and your config has a reference to a controller in a module that's not declared as dependency then initialisation might fail too.

E.g assuming you've configured ngRoute for your app, like

angular.module('yourModule',['ngRoute'])
.config(function($routeProvider, $httpProvider) { ... });

Be careful in the block that declares the routes,

.when('/resourcePath', { 
templateUrl: 'resource.html',
controller: 'secondModuleController' //lives in secondModule
});

Declare secondModule as a dependency after 'ngRoute' should resolve the issue. I know I had this problem.

Safely casting long to int in Java

A new method has been added with Java 8 to do just that.

import static java.lang.Math.toIntExact;

long foo = 10L;
int bar = toIntExact(foo);

Will throw an ArithmeticException in case of overflow.

See: Math.toIntExact(long)

Several other overflow safe methods have been added to Java 8. They end with exact.

Examples:

  • Math.incrementExact(long)
  • Math.subtractExact(long, long)
  • Math.decrementExact(long)
  • Math.negateExact(long),
  • Math.subtractExact(int, int)

Oracle - How to generate script from sql developer

If you want to see DDL for the objects, you can use

select dbms_metadata.get_ddl('OBJECT_TYPE','OBJECT_NAME','OBJECT_OWNER') 
  from dual
/

For example this will give you the DDL script for emp table.

select dbms_metadata.get_ddl('TABLE','EMP','HR') 
  from dual
/

You may need to set the long type format to big number. For packages, you need to access dba_source, user_source, all_source tables. You can query for object name and type to see what code is stored.

How does tuple comparison work in Python?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.

See Common Sequence Operations:

Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.

Also Value Comparisons for further details:

Lexicographical comparison between built-in collections works as follows:

  • For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, [1,2] == (1,2) is false because the type is not the same).
  • Collections that support order comparison are ordered the same as their first unequal elements (for example, [1,2,x] <= [1,2,y] has the same value as x <= y). If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] < [1,2,3] is true).

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] < [1,2,3] returns True).

Note 1: < and > do not mean "smaller than" and "greater than" but "is before" and "is after": so (0, 1) "is before" (1, 0).

Note 2: tuples must not be considered as vectors in a n-dimensional space, compared according to their length.

Note 3: referring to question https://stackoverflow.com/questions/36911617/python-2-tuple-comparison: do not think that a tuple is "greater" than another only if any element of the first is greater than the corresponding one in the second.

Java Comparator class to sort arrays

[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]

Here's a complete example using Java 8:

import java.util.*;

public class Test {

    public static void main(String args[]) {

        int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };

        Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
                                      .reversed());

        System.out.println(Arrays.deepToString(twoDim));
    }
}

Output:

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

For Java 7 you can do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return Integer.compare(o2[0], o1[0]);
    }
});

If you unfortunate enough to work on Java 6 or older, you'd do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return ((Integer) o2[0]).compareTo(o1[0]);
    }
});

Undefined reference to main - collect2: ld returned 1 exit status

I my case I found out the void for the main function declaration was missing.

I was previously using Visual Studio in Windows and this was never a problem, so I thought I might leave it out now too.

phpmyadmin.pma_table_uiprefs doesn't exist

Clear your cookies

When using PHPMyAdmin configured with multiple databases, one having the phpmyadmin table and another not having it; phpmyadmin will store preferences for the database with the table in your cookies then try to load them with the database that doesn't have the table.

To test, try using an incognito window.

Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?

Even in base Python you can do the computation in generic form

result = sum(x**2 for x in some_vector) ** 0.5

x ** 2 is surely not an hack and the computation performed is the same (I checked with cpython source code). I actually find it more readable (and readability counts).

Using instead x ** 0.5 to take the square root doesn't do the exact same computations as math.sqrt as the former (probably) is computed using logarithms and the latter (probably) using the specific numeric instruction of the math processor.

I often use x ** 0.5 simply because I don't want to add math just for that. I'd expect however a specific instruction for the square root to work better (more accurately) than a multi-step operation with logarithms.

Save the plots into a PDF

Never mind got the way to do it.

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

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

----- mainModule ----

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

----- mainModule -----

How to get the PID of a process by giving the process name in Mac OS X ?

ps -o ppid=$(ps -ax | grep nameOfProcess | awk '{print $1}')

Prints out the changing process pid and then the parent PID. You can then kill the parent, or you can use that parentPID in the following command to get the name of the parent process:

ps -p parentPID -o comm=

For me the parent was 'login' :\

List all virtualenv

If you are using virtualenv or Python 3's built in venv the above answers might not work.

If you are on Linux, just locate the activate script that is always present inside a env.

locate -b '\activate' | grep "/home"

This will grab all Python virtual environments present inside your home directory.

See Demo Here

CSS align images and text on same line

You can either use (on the h4 elements, as they are block by default)

display: inline-block;

Or you can float the elements to the left/rght

float: left;

Just don't forget to clear the floats after

clear: left;

More visual example for the float left/right option as shared below by @VSB:

_x000D_
_x000D_
<h4> _x000D_
    <div style="float:left;">Left Text</div>_x000D_
    <div style="float:right;">Right Text</div>_x000D_
    <div style="clear: left;"/>_x000D_
</h4>
_x000D_
_x000D_
_x000D_

Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

Selenium C# WebDriver: Wait until element is present

We can achieve that like this:

public static IWebElement WaitForObject(IWebDriver DriverObj, By by, int TimeOut = 30)
{
    try
    {
        WebDriverWait Wait1 = new WebDriverWait(DriverObj, TimeSpan.FromSeconds(TimeOut));
        var WaitS = Wait1.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.PresenceOfAllElementsLocatedBy(by));
        return WaitS[0];
    }
    catch (NoSuchElementException)
    {
        Reports.TestStep("Wait for Element(s) with xPath was failed in current context page.");
        throw;
    }
}

What is the simplest way to SSH using Python?

You can code it yourself using Paramiko, as suggested above. Alternatively, you can look into Fabric, a python application for doing all the things you asked about:

Fabric is a Python library and command-line tool designed to streamline deploying applications or performing system administration tasks via the SSH protocol. It provides tools for running arbitrary shell commands (either as a normal login user, or via sudo), uploading and downloading files, and so forth.

I think this fits your needs. It is also not a large library and requires no server installation, although it does have dependencies on paramiko and pycrypt that require installation on the client.

The app used to be here. It can now be found here.

* The official, canonical repository is git.fabfile.org
* The official Github mirror is GitHub/bitprophet/fabric

There are several good articles on it, though you should be careful because it has changed in the last six months:

Deploying Django with Fabric

Tools of the Modern Python Hacker: Virtualenv, Fabric and Pip

Simple & Easy Deployment with Fabric and Virtualenv


Later: Fabric no longer requires paramiko to install:

$ pip install fabric
Downloading/unpacking fabric
  Downloading Fabric-1.4.2.tar.gz (182Kb): 182Kb downloaded
  Running setup.py egg_info for package fabric
    warning: no previously-included files matching '*' found under directory 'docs/_build'
    warning: no files found matching 'fabfile.py'
Downloading/unpacking ssh>=1.7.14 (from fabric)
  Downloading ssh-1.7.14.tar.gz (794Kb): 794Kb downloaded
  Running setup.py egg_info for package ssh
Downloading/unpacking pycrypto>=2.1,!=2.4 (from ssh>=1.7.14->fabric)
  Downloading pycrypto-2.6.tar.gz (443Kb): 443Kb downloaded
  Running setup.py egg_info for package pycrypto
Installing collected packages: fabric, ssh, pycrypto
  Running setup.py install for fabric
    warning: no previously-included files matching '*' found under directory 'docs/_build'
    warning: no files found matching 'fabfile.py'
    Installing fab script to /home/hbrown/.virtualenvs/fabric-test/bin
  Running setup.py install for ssh
  Running setup.py install for pycrypto
...
Successfully installed fabric ssh pycrypto
Cleaning up...

This is mostly cosmetic, however: ssh is a fork of paramiko, the maintainer for both libraries is the same (Jeff Forcier, also the author of Fabric), and the maintainer has plans to reunite paramiko and ssh under the name paramiko. (This correction via pbanka.)

Parse HTML in Android

We all know that programming have endless possibilities.There are numbers of solutions available for a single problem so i think all of the above solutions are perfect and may be helpful for someone but for me this one save my day..

So Code goes like this

  private void getWebsite() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        final StringBuilder builder = new StringBuilder();

        try {
          Document doc = Jsoup.connect("http://www.ssaurel.com/blog").get();
          String title = doc.title();
          Elements links = doc.select("a[href]");

          builder.append(title).append("\n");

          for (Element link : links) {
            builder.append("\n").append("Link : ").append(link.attr("href"))
            .append("\n").append("Text : ").append(link.text());
          }
        } catch (IOException e) {
          builder.append("Error : ").append(e.getMessage()).append("\n");
        }

        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            result.setText(builder.toString());
          }
        });
      }
    }).start();
  }

You just have to call the above function in onCreate Method of your MainActivity

I hope this one is also helpful for you guys.

Also read the original blog at Medium

apc vs eaccelerator vs xcache

It may be important to point out the current stable, unstable and dev versions of each (including date):

APC

http://pecl.php.net/package/apc

dev        dev          2013-09-12
3.1.14     beta         2013-01-02
3.1.9      stable       2011-05-14

Xcache

http://xcache.lighttpd.net/

dev/3.2     dev        2013-12-13
dev/3.1     dev        2013-11-05
3.1.0       stable     2013-10-10
3.0.4       stable     2013-10-10

eAccelerator

https://github.com/eaccelerator/eaccelerator

dev         dev        2012-08-16
0.9.6-rc1   unstable   2010-01-26
0.9.5.1     stable     2007-05-16

Strip HTML from Text JavaScript

For escape characters also this will work using pattern matching:

myString.replace(/((&lt)|(<)(?:.|\n)*?(&gt)|(>))/gm, '');

Serializing/deserializing with memory stream

This code works for me:

public void Run()
{
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());
}

Where the types are like this:

[Serializable]
public enum DogColor
{
    Brown,
    Black,
    Mottled
}

[Serializable]
public class Dog
{
    public String Name
    {
        get; set;
    }

    public DogColor Color
    {
        get;set;
    }

    public override String ToString()
    {
        return String.Format("Dog: {0}/{1}", Name, Color);
    }
}

and the utility methods are:

public static MemoryStream SerializeToStream(object o)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;
}

public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;
}

Difference Between ViewResult() and ActionResult()

ActionResult is an abstract class.

ViewResult derives from ActionResult. Other derived classes include JsonResult and PartialViewResult.

You declare it this way so you can take advantage of polymorphism and return different types in the same method.

e.g:

public ActionResult Foo()
{
   if (someCondition)
     return View(); // returns ViewResult
   else
     return Json(); // returns JsonResult
}

Bash script - variable content as a command to run

You just need to do:

#!/bin/bash
count=$(cat last_queries.txt | wc -l)
$(perl test.pl test2 $count)

However, if you want to call your Perl command later, and that's why you want to assign it to a variable, then:

#!/bin/bash
count=$(cat last_queries.txt | wc -l)
var="perl test.pl test2 $count" # You need double quotes to get your $count value substituted.

...stuff...

eval $var

As per Bash's help:

~$ help eval
eval: eval [arg ...]
    Execute arguments as a shell command.

    Combine ARGs into a single string, use the result as input to the shell,
    and execute the resulting commands.

    Exit Status:
    Returns exit status of command or success if command is null.

Create SQLite database in android

If you want to keep the database between uninstalls you have to put it on the SD Card. This is the only place that won't be deleted at the moment your app is deleted. But in return it can be deleted by the user every time.

If you put your DB on the SD Card you can't use the SQLiteOpenHelper anymore, but you can use the source and the architecture of this class to get some ideas on how to implement the creation, updating and opening of a databse.

How to get sp_executesql result into a variable?

This worked for me:

DECLARE @SQL NVARCHAR(4000)

DECLARE @tbl Table (
    Id int,
    Account varchar(50),
    Amount int
) 

-- Lots of code to Create my dynamic sql statement

insert into @tbl EXEC sp_executesql @SQL

select * from @tbl

Why not use tables for layout in HTML?

Using DIV, you can easily switch things. For example, you could make this :

Menu | Content

Content | Menu

Menu
----
Content

It's easy to change it in CSS, not in HTML. You can also provide several styles (right handed, left handed, special for little screen).

In CSS, you can also hide the menu in a special stylesheet used for printing.

Another good thing, is that your content is always in the same order in the code (the menu first, the content after) even if visually it's presented otherwise.

Split string on the first white space occurrence

If you only care about the space character (and not tabs or other whitespace characters) and only care about everything before the first space and everything after the first space, you can do it without a regular expression like this:

str.substr(0,str.indexOf(' ')); // "72"
str.substr(str.indexOf(' ')+1); // "tocirah sneab"

Note that if there is no space at all, then the first line will return an empty string and the second line will return the entire string. Be sure that is the behavior that you want in that situation (or that that situation will not arise).

Better way to check if a Path is a File or a Directory?

After combining the suggestions from the other answers, I realized I came up with about the same thing as Ronnie Overby's answer. Here are some tests to point out some things to think about:

  1. folders can have "extensions": C:\Temp\folder_with.dot
  2. files cannot end with a directory separator (slash)
  3. There are technically two directory separators which are platform specific -- i.e. may or may not be slashes (Path.DirectorySeparatorChar and Path.AltDirectorySeparatorChar)

Tests (Linqpad)

var paths = new[] {
    // exists
    @"C:\Temp\dir_test\folder_is_a_dir",
    @"C:\Temp\dir_test\is_a_dir_trailing_slash\",
    @"C:\Temp\dir_test\existing_folder_with.ext",
    @"C:\Temp\dir_test\file_thats_not_a_dir",
    @"C:\Temp\dir_test\notadir.txt",
    // doesn't exist
    @"C:\Temp\dir_test\dne_folder_is_a_dir",
    @"C:\Temp\dir_test\dne_folder_trailing_slash\",
    @"C:\Temp\dir_test\non_existing_folder_with.ext",
    @"C:\Temp\dir_test\dne_file_thats_not_a_dir",
    @"C:\Temp\dir_test\dne_notadir.txt",        
};

foreach(var path in paths) {
    IsFolder(path/*, false*/).Dump(path);
}

Results

C:\Temp\dir_test\folder_is_a_dir
  True 
C:\Temp\dir_test\is_a_dir_trailing_slash\
  True 
C:\Temp\dir_test\existing_folder_with.ext
  True 
C:\Temp\dir_test\file_thats_not_a_dir
  False 
C:\Temp\dir_test\notadir.txt
  False 
C:\Temp\dir_test\dne_folder_is_a_dir
  True 
C:\Temp\dir_test\dne_folder_trailing_slash\
  True 
C:\Temp\dir_test\non_existing_folder_with.ext
  False (this is the weird one)
C:\Temp\dir_test\dne_file_thats_not_a_dir
  True 
C:\Temp\dir_test\dne_notadir.txt
  False 

Method

/// <summary>
/// Whether the <paramref name="path"/> is a folder (existing or not); 
/// optionally assume that if it doesn't "look like" a file then it's a directory.
/// </summary>
/// <param name="path">Path to check</param>
/// <param name="assumeDneLookAlike">If the <paramref name="path"/> doesn't exist, does it at least look like a directory name?  As in, it doesn't look like a file.</param>
/// <returns><c>True</c> if a folder/directory, <c>false</c> if not.</returns>
public static bool IsFolder(string path, bool assumeDneLookAlike = true)
{
    // https://stackoverflow.com/questions/1395205/better-way-to-check-if-path-is-a-file-or-a-directory
    // turns out to be about the same as https://stackoverflow.com/a/19596821/1037948

    // check in order of verisimilitude

    // exists or ends with a directory separator -- files cannot end with directory separator, right?
    if (Directory.Exists(path)
        // use system values rather than assume slashes
        || path.EndsWith("" + Path.DirectorySeparatorChar)
        || path.EndsWith("" + Path.AltDirectorySeparatorChar))
        return true;

    // if we know for sure that it's an actual file...
    if (File.Exists(path))
        return false;

    // if it has an extension it should be a file, so vice versa
    // although technically directories can have extensions...
    if (!Path.HasExtension(path) && assumeDneLookAlike)
        return true;

    // only works for existing files, kinda redundant with `.Exists` above
    //if( File.GetAttributes(path).HasFlag(FileAttributes.Directory) ) ...; 

    // no idea -- could return an 'indeterminate' value (nullable bool)
    // or assume that if we don't know then it's not a folder
    return false;
}

Angular ng-if="" with multiple arguments

For people looking to do if statements with multiple 'or' values.

<div ng-if="::(a || b || c || d || e || f)"><div>

jQuery - Getting form values for ajax POST

var data={
 userName: $('#userName').val(),
 email: $('#email').val(),
 //add other properties similarly
}

and

$.ajax({
        type: "POST",
        url: "http://rt.ja.com/includes/register.php?submit=1",
        data: data

        success: function(html)
        {   
            //alert(html);
            $('#userError').html(html);
            $("#userError").html(userChar);
            $("#userError").html(userTaken);
        }
    });

You dont have to bother about anything else. jquery will handle the serialization etc. also you can append the submit query string parameter submit=1 into the data json object.

Repeat each row of data.frame the number of times specified in a column

Use expandRows() from the splitstackshape package:

library(splitstackshape)
expandRows(df, "freq")

Simple syntax, very fast, works on data.frame or data.table.

Result:

    var1 var2
1      a    d
2      b    e
2.1    b    e
3      c    f
3.1    c    f
3.2    c    f

Calculating arithmetic mean (one type of average) in Python

Use statistics.mean:

import statistics
print(statistics.mean([1,2,4])) # 2.3333333333333335

It's available since Python 3.4. For 3.1-3.3 users, an old version of the module is available on PyPI under the name stats. Just change statistics to stats.

How to get current user who's accessing an ASP.NET application?

The quick answer is User = System.Web.HttpContext.Current.User

Ensure your web.config has the following authentication element.

<configuration>
    <system.web>
        <authentication mode="Windows" />
        <authorization>
            <deny users="?"/>
        </authorization>
    </system.web>
</configuration>

Further Reading: Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application

jQuery UI Alert Dialog as a replacement for alert()

As mentioned by nux and micheg79 a node is left behind in the DOM after the dialog closes.

This can also be cleaned up simply by adding:

$(this).dialog('destroy').remove();

to the close method of the dialog. Example adding this line to eidylon's answer:

function jqAlert(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
            }
        },
        close: function() { onCloseCallback();
                           /* Cleanup node(s) from DOM */
                           $(this).dialog('destroy').remove();
                          }
    });
}

EDIT: I had problems getting callback function to run and found that I had to add parentheses () to onCloseCallback to actually trigger the callback. This helped me understand why: In JavaScript, does it make a difference if I call a function with parentheses?

Getting results between two dates in PostgreSQL

Looking at the dates for which it doesn't work -- those where the day is less than or equal to 12 -- I'm wondering whether it's parsing the dates as being in YYYY-DD-MM format?

Is there a command to undo git init?

In windows, type rmdir .git or rmdir /s .git if the .git folder has subfolders.

If your git shell isn't setup with proper administrative rights (i.e. it denies you when you try to rmdir), you can open a command prompt (possibly as administrator--hit the windows key, type 'cmd', right click 'command prompt' and select 'run as administrator) and try the same commands.

rd is an alternative form of the rmdir command. http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/rmdir.mspx?mfr=true

Python foreach equivalent

For a dict we can use a for loop to iterate through the index, key and value:

dictionary = {'a': 0, 'z': 25}
for index, (key, value) in enumerate(dictionary.items()):
     ## Code here ##

Java Date - Insert into database

VALUES ('"+user+"' , '"+FirstTest+"'  , '"+LastTest+"'..............etc)

You can use it to insert variables into sql query.

Convert from MySQL datetime to another format with PHP

If you're looking for a way to normalize a date into MySQL format, use the following

$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );

The line $phpdate = strtotime( $mysqldate ) accepts a string and performs a series of heuristics to turn that string into a unix timestamp.

The line $mysqldate = date( 'Y-m-d H:i:s', $phpdate ) uses that timestamp and PHP's date function to turn that timestamp back into MySQL's standard date format.

(Editor Note: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists)

How can I open a .db file generated by eclipse(android) form DDMS-->File explorer-->data--->data-->packagename-->database?

Download this Sqlite manager its the easiest one to use Sqlite manager

and drag and drop your fetched file on its running instance

only drawback of this Sqlite Manager it stop responding if you run some SQL statement that has Syntax Error in it.

So i Use Firefox Plugin Side by side also which you can find at FireFox addons

What is the difference between XAMPP or WAMP Server & IIS?

In addition to the above, WAMP supports 64 bit PHP on Windows systems while XAMPP only offers 32 bit versions. This actually made me switch to WAMP on my Windows machine since you need 64 bit PHP 7 to get bigint numbers correctly from MySQL

Why does the C++ STL not provide any "tree" containers?

Probably for the same reason that there is no tree container in boost. There are many ways to implement such a container, and there is no good way to satisfy everyone who would use it.

Some issues to consider:

  • Are the number of children for a node fixed or variable?
  • How much overhead per node? - ie, do you need parent pointers, sibling pointers, etc.
  • What algorithms to provide? - different iterators, search algorithms, etc.

In the end, the problem ends up being that a tree container that would be useful enough to everyone, would be too heavyweight to satisfy most of the people using it. If you are looking for something powerful, Boost Graph Library is essentially a superset of what a tree library could be used for.

Here are some other generic tree implementations:

How to map atan2() to degrees 0-360

Solution using Modulo

A simple solution that catches all cases.

degrees = (degrees + 360) % 360;  // +360 for implementations where mod returns negative numbers

Explanation

Positive: 1 to 180

If you mod any positive number between 1 and 180 by 360, you will get the exact same number you put in. Mod here just ensures these positive numbers are returned as the same value.

Negative: -180 to -1

Using mod here will return values in the range of 180 and 359 degrees.

Special cases: 0 and 360

Using mod means that 0 is returned, making this a safe 0-359 degrees solution.

How to make a div 100% height of the browser window

100vw = 100% of the width of the viewport.

100vh = 100% of the height of the viewport.

If you want to set the div width or height 100% of browser-window-size you should use:

For width: 100vw

For height: 100vh

Or if you want to set it smaller size, use the CSS calc function. Example:

#example {
    width: calc(100vw - 32px)
}

Selenium WebDriver can't find element by link text

Use xpath and text()

driver.findElement(By.Xpath("//strong[contains(text(),'" + service +"')]"));

jQuery: Performing synchronous AJAX requests

As you're making a synchronous request, that should be

function getRemote() {
    return $.ajax({
        type: "GET",
        url: remote_url,
        async: false
    }).responseText;
}

Example - http://api.jquery.com/jQuery.ajax/#example-3

PLEASE NOTE: Setting async property to false is deprecated and in the process of being removed (link). Many browsers including Firefox and Chrome have already started to print a warning in the console if you use this:

Chrome:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Firefox:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/

how to customize `show processlist` in mysql?

You can just capture the output and pass it through a filter, something like:

mysql show processlist
    | grep -v '^\+\-\-'
    | grep -v '^| Id'
    | sort -n -k12

The two greps strip out the header and trailer lines (others may be needed if there are other lines not containing useful information) and the sort is done based on the numeric field number 12 (I think that's right).

This one works for your immediate output:

mysql show processlist
    | grep -v '^\+\-\-'
    | grep -v '^| Id'
    | grep -v  '^[0-9][0-9]* rows in set '
    | grep -v '^ '
    | sort -n -k12

ERROR 2006 (HY000): MySQL server has gone away

If it's reconnecting and getting connection ID 2, the server has almost definitely just crashed.

Contact the server admin and get them to diagnose the problem. No non-malicious SQL should crash the server, and the output of mysqldump certainly should not.

It is probably the case that the server admin has made some big operational error such as assigning buffer sizes of greater than the architecture's address-space limits, or more than virtual memory capacity. The MySQL error-log will probably have some relevant information; they will be monitoring this if they are competent anyway.

In Java, how to find if first character in a string is upper case without regex

There is many ways to do that, but the simplest seems to be the following one:

boolean isUpperCase = Character.isUpperCase("My String".charAt(0));

How to create a custom exception type in Java?

You need to create a class that extends from Exception. It should look like this:

public class MyOwnException extends Exception {
    public MyOwnException () {

    }

    public MyOwnException (String message) {
        super (message);
    }

    public MyOwnException (Throwable cause) {
        super (cause);
    }

    public MyOwnException (String message, Throwable cause) {
        super (message, cause);
    }
}

Your question does not specify if this new exception should be checked or unchecked.

As you can see here, the two types are different:

  • Checked exceptions are meant to flag a problematic situation that should be handled by the developer who calls your method. It should be possible to recover from such an exception. A good example of this is a FileNotFoundException. Those exceptions are subclasses of Exception.

  • Unchecked exceptions are meant to represent a bug in your code, an unexpected situation that you might not be able to recover from. A NullPointerException is a classical example. Those exceptions are subclasses of RuntimeException

Checked exception must be handled by the calling method, either by catching it and acting accordingly, or by throwing it to the calling method. Unchecked exceptions are not meant to be caught, even though it is possible to do so.

Android LinearLayout : Add border with shadow around a LinearLayout

This is so simple:

Create a drawable file with a gradient like this:

for shadow below a view below_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">   
<gradient
    android:startColor="#20000000"
    android:endColor="@android:color/transparent"
    android:angle="270" >
</gradient>
</shape>

for shadow above a view above_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">   
<gradient
    android:startColor="#20000000"
    android:endColor="@android:color/transparent"
    android:angle="90" >
</gradient>
</shape>

and so on for right and left shadow just change the angle of the gradient :)

Why I get 'list' object has no attribute 'items'?

Dictionary does not support duplicate keys- So you will get the last key i.e.a=16 but not the first key a=15

>>>qs = [{u'a': 15L, u'b': 9L, u'a': 16L}]
>>>qs
>>>[{u'a': 16L, u'b': 9L}]
>>>result_list = [int(v) for k,v in qs[0].items()]
>>>result_list
>>>[16, 9]

How to duplicate a whole line in Vim?

Do this:

First, yy to copy the current line, and then p to paste.

How to create an empty R vector to add new items

I've also seen

x <- {}

Now you can concatenate or bind a vector of any dimension to x

rbind(x, 1:10)
cbind(x, 1:10)
c(x, 10)

Browser: Identifier X has already been declared

The problem solved when I don't use any declaration like var, let or const

Retrieving subfolders names in S3 bucket from boto3

Below piece of code returns ONLY the 'subfolders' in a 'folder' from s3 bucket.

import boto3
bucket = 'my-bucket'
#Make sure you provide / in the end
prefix = 'prefix-name-with-slash/'  

client = boto3.client('s3')
result = client.list_objects(Bucket=bucket, Prefix=prefix, Delimiter='/')
for o in result.get('CommonPrefixes'):
    print 'sub folder : ', o.get('Prefix')

For more details, you can refer to https://github.com/boto/boto3/issues/134

How to remove indentation from an unordered list item?

Add this to your CSS:

ul { list-style-position: inside; }

This will place the li elements in the same indent as other paragraphs and text.

Ref: http://www.w3schools.com/cssref/pr_list-style-position.asp

Send FormData with other field in AngularJS

Using $resource in AngularJS you can do:

task.service.js

$ngTask.factory("$taskService", [
    "$resource",
    function ($resource) {
        var taskModelUrl = 'api/task/';
        return {
            rest: {
                taskUpload: $resource(taskModelUrl, {
                    id: '@id'
                }, {
                    save: {
                        method: "POST",
                        isArray: false,
                        headers: {"Content-Type": undefined},
                        transformRequest: angular.identity
                    }
                })
            }
        };
    }
]);

And then use it in a module:

task.module.js

$ngModelTask.controller("taskController", [
    "$scope",
    "$taskService",
    function (
        $scope,
        $taskService,
    ) {
    $scope.saveTask = function (name, file) {
        var newTask,
            payload = new FormData();
        payload.append("name", name);
        payload.append("file", file);
        newTask = $taskService.rest.taskUpload.save(payload);
        // check if exists
    }
}

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

Where are the Properties.Settings.Default stored?

They are saved in YOUR_APP.exe.config, the file is saved in the same folder with YOUR_APP.exe file, <userSettings> section:

   <userSettings>
      <ShowGitlabIssues.Properties.Settings>
         <setting name="SavedUserName" serializeAs="String">
            <value />
         </setting>
         <setting name="SavedPassword" serializeAs="String">
            <value />
         </setting>
         <setting name="CheckSave" serializeAs="String">
            <value>False</value>
         </setting>
      </ShowGitlabIssues.Properties.Settings>
   </userSettings>

here is cs code:

public void LoadInfoLogin()
{
    if (Properties.Settings.Default.CheckSave)// chkRemember.Checked)
    {
        txtUsername.Text = Properties.Settings.Default.SaveUserName;
        txtPassword.Text = Properties.Settings.Default.SavePassword;
        chkRemember.Checked = true;
    }
...

show/hide a div on hover and hover out

I found using css opacity is better for a simple show/hide hover, and you can add css3 transitions to make a nice finished hover effect. The transitions will just be dropped by older IE browsers, so it degrades gracefully to.

JS fiddle Demo

CSS

#stuff {
    opacity: 0.0;
    -webkit-transition: all 500ms ease-in-out;
    -moz-transition: all 500ms ease-in-out;
    -ms-transition: all 500ms ease-in-out;
    -o-transition: all 500ms ease-in-out;
    transition: all 500ms ease-in-out;
}
#hover {
    width:80px;
    height:20px;
    background-color:green;
    margin-bottom:15px;
}
#hover:hover + #stuff {
    opacity: 1.0;
}

HTML

<div id="hover">Hover</div>
<div id="stuff">stuff</div>

C# int to enum conversion

You don't need the inheritance. You can do:

(Foo)1 

it will work ;)

Anchor links in Angularjs?

You can also Navigate to HTML id from inside controller

$location.hash('id_in_html');

How do I run all Python unit tests in a directory?

This is an old question, but what worked for me now (in 2019) is:

python -m unittest *_test.py

All my test files are in the same folder as the source files and they end with _test.

Column/Vertical selection with Keyboard in SublimeText 3

In my case (Linux) is alt+shift up/down

 { "keys": ["alt+shift+up"], "command": "select_lines", "args": {"forward": false} },
 { "keys": ["alt+shift+down"], "command": "select_lines", "args": {"forward": true} },    

require(vendor/autoload.php): failed to open stream

First, review route inside index.php

require __DIR__.'/../vendor/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';

in my case the route did not work, I had to review the directories.

How do I get the file extension of a file in Java?

I found a better way to find extension by mixing all above answers

public static String getFileExtension(String fileLink) {

        String extension;
        Uri uri = Uri.parse(fileLink);
        String scheme = uri.getScheme();
        if (scheme != null && scheme.equals(ContentResolver.SCHEME_CONTENT)) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            extension = mime.getExtensionFromMimeType(CoreApp.getInstance().getContentResolver().getType(uri));
        } else {
            extension = MimeTypeMap.getFileExtensionFromUrl(fileLink);
        }

        return extension;
    }

public static String getMimeType(String fileLink) {
        String type = CoreApp.getInstance().getContentResolver().getType(Uri.parse(fileLink));
        if (!TextUtils.isEmpty(type)) return type;
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        return mime.getMimeTypeFromExtension(FileChooserUtil.getFileExtension(fileLink));
    }

Do sessions really violate RESTfulness?

HTTP transaction, basic access authentication, is not suitable for RBAC, because basic access authentication uses the encrypted username:password every time to identify, while what is needed in RBAC is the Role the user wants to use for a specific call. RBAC does not validate permissions on username, but on roles.

You could tric around to concatenate like this: usernameRole:password, but this is bad practice, and it is also inefficient because when a user has more roles, the authentication engine would need to test all roles in concatenation, and that every call again. This would destroy one of the biggest technical advantages of RBAC, namely a very quick authorization-test.

So that problem cannot be solved using basic access authentication.

To solve this problem, session-maintaining is necessary, and that seems, according to some answers, in contradiction with REST.

That is what I like about the answer that REST should not be treated as a religion. In complex business cases, in healthcare, for example, RBAC is absolutely common and necessary. And it would be a pity if they would not be allowed to use REST because all REST-tools designers would treat REST as a religion.

For me there are not many ways to maintain a session over HTTP. One can use cookies, with a sessionId, or a header with a sessionId.

If someone has another idea I will be glad to hear it.

How to select all instances of a variable and edit variable name in Sublime

This worked for me. Put your cursor at the beginning of the word you want to replace, then

CtrlK, CtrlD, CtrlD ...

That should select as many instances of the word as you like, then you can just type the replacement.

Jackson how to transform JsonNode to ArrayNode without casting?

I would assume at the end of the day you want to consume the data in the ArrayNode by iterating it. For that:

Iterator<JsonNode> iterator = datasets.withArray("datasets").elements();
while (iterator.hasNext()) 
        System.out.print(iterator.next().toString() + " "); 

or if you're into streams and lambda functions:

import com.google.common.collect.Streams;
Streams.stream(datasets.withArray("datasets").elements())
    .forEach( item -> System.out.print(item.toString()) )

Get all files that have been modified in git branch

The accepted answer - git diff --name-only <notMainDev> $(git merge-base <notMainDev> <mainDev>) - is very close, but I noticed that it got the status wrong for deletions. I added a file in a branch, and yet this command (using --name-status) gave the file I deleted "A" status and the file I added "D" status.

I had to use this command instead:

git diff --name-only $(git merge-base <notMainDev> <mainDev>)

Detecting endianness programmatically in a C++ program

The C++ way has been to use boost, where preprocessor checks and casts are compartmentalized away inside very thoroughly-tested libraries.

The Predef Library (boost/predef.h) recognizes four different kinds of endianness.

The Endian Library was planned to be submitted to the C++ standard, and supports a wide variety of operations on endian-sensitive data.

As stated in answers above, Endianness will be a part of c++20.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

I meet this question when i use intellij 15.0,then i update to 15.02 version. after that, I edit configurations and reset the Default JRE to my own JRE.It works well for me;

Getting datarow values into a string?

I've done this a lot myself. If you just need a comma separated list for all of row values you can do this:

StringBuilder sb = new StringBuilder();
foreach (DataRow row in results.Tables[0].Rows)     
{
    sb.AppendLine(string.Join(",", row.ItemArray));
}

A StringBuilder is the preferred method as string concatenation is significantly slower for large amounts of data.

How do you specify table padding in CSS? ( table, not cell padding )

The easiest/best supported method is to use <table cellspacing="10">

The css way: border-spacing (not supported by IE I don't think)

_x000D_
_x000D_
    <!-- works in firefox, opera, safari, chrome -->_x000D_
    <style type="text/css">_x000D_
    _x000D_
    table.foobar {_x000D_
     border: solid black 1px;_x000D_
     border-spacing: 10px;_x000D_
    }_x000D_
    table.foobar td {_x000D_
     border: solid black 1px;_x000D_
    }_x000D_
    _x000D_
    _x000D_
    </style>_x000D_
    _x000D_
    <table class="foobar" cellpadding="0" cellspacing="0">_x000D_
    <tr><td>foo</td><td>bar</td></tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

Edit: if you just want to pad the cell content, and not space them you can simply use

<table cellpadding="10">

OR

td {
    padding: 10px;
}

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

In my case, the issue was due to WAMP using a different php.ini for CLI than Apache, so your settings made through the WAMP menu don't apply to CLI. Just modify the CLI php.ini and it works.

Is there a Google Keep API?

No there isn't. If you watch the http traffic and dump the page source you can see that there is an API below the covers, but it's not published nor available for 3rd party apps.

Check this link: https://developers.google.com/gsuite/products for updates.

However, there is an unofficial Python API under active development: https://github.com/kiwiz/gkeepapi

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

Although a more optimal solution is to simply recompile as suggested above, that requires access to the source code. In my case, I only had the finished .exe and had to use this solution. It uses CorFlags.exe from the .Net SDK to change the loading characteristics of the application.

  1. Download the .Net Framework SDK (I personally used 3.5, but the version used should be at or above the required .Net for your application.
  2. When installing, all you need is CorLibs.exe, so just check Windows Development Tools.
  3. After installation, find your CorFlags.exe. For my install of the .Net Framework 3.5 SDK, it was at C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin.
  4. Open a command prompt and type path/to/CorFlags.exe path/to/your/exeFile.exe /32Bit+.

You're done! This sets the starting flags for your program so that it starts in 32 bit WOW64 mode, and can therefore access microsoft.jet.oledb.4.0.

What exactly does numpy.exp() do?

exp(x) = e^x where e= 2.718281(approx)

import numpy as np

ar=np.array([1,2,3])
ar=np.exp(ar)
print ar

outputs:

[ 2.71828183  7.3890561  20.08553692]

How can I get the current class of a div with jQuery?

$('#div1').attr('class')

will return a string of the classes. Turn it into an array of class names

var classNames = $('#div1').attr('class').split(' ');

The project type is not supported by this installation

Had the same issue with "The project type is not supported by this installation" for web projects in VS 2010 Premium.

devenv /ResetSkipPkgs

and GUIDs magic did not help.

Same projects were working fine on a neighbor box with VS 2010 Premium.

As it turned out the only difference was that my VS installation was missing the following installed products (can be found in VS About dialog):

  • Microsoft Office Developer Tools
  • Microsoft Visual Studio 2010 SharePoint Developer Tools

Add/Remove programs -> VS 2010 -> Customize -> Check the above products - and the problem was solved.

Using TortoiseSVN via the command line

To enable svn run the TortoiseSVN installation program again, select "Modify" (Allows users to change the way features are installed) and install "command line client tools".

Global javascript variable inside document.ready

declare this

var intro;

outside of $(document).ready() because, $(document).ready() will hide your variable from global scope.

Code

var intro;

$(document).ready(function() {
    if ($('.intro_check').is(':checked')) {
        intro = true;
        $('.intro').wrap('<div class="disabled"></div>');
    };
    $('.intro_check').change(function(){
        if(this.checked) {
            intro = false;
            $('.enabled').removeClass('enabled').addClass('disabled');
        } else {
            intro = true;
            if($('.intro').exists()) {
                $('.disabled').removeClass('disabled').addClass('enabled'); 
            } else {
                $('.intro').wrap('<div class="disabled"></div>');
            }
        }
    });
});

According to @Zakaria comment

Another way:

window.intro = undefined;

$(document).ready(function() {
    if ($('.intro_check').is(':checked')) {
        window.intro = true;
        $('.intro').wrap('<div class="disabled"></div>');
    };
    $('.intro_check').change(function(){
        if(this.checked) {
            window.intro = false;
            $('.enabled').removeClass('enabled').addClass('disabled');
        } else {
            window.intro = true;
            if($('.intro').exists()) {
                $('.disabled').removeClass('disabled').addClass('enabled'); 
            } else {
                $('.intro').wrap('<div class="disabled"></div>');
            }
        }
    });
});

Note

console.log(intro);

outside of DOM ready function (currently you've) will log undefined, but within DOM ready it will give you true/ false.

Your outer console.log execute before DOM ready execute, because DOM ready execute after all resource appeared to DOM i.e after DOM is prepared, so I think you'll always get absurd result.


According to comment of @W0rldart

I need to use it outside of DOM ready function

You can use following approach:

var intro = undefined;

$(document).ready(function() {
    if ($('.intro_check').is(':checked')) {
        intro = true;
        introCheck();
        $('.intro').wrap('<div class="disabled"></div>');
    };
    $('.intro_check').change(function() {
        if (this.checked) {
            intro = true;
        } else {
            intro = false;
        }
        introCheck();
    });

});

function introCheck() {
    console.log(intro);
}

After change the value of intro I called a function that will fire with new value of intro.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

You can use less code, writing this:

    $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name'));

And of course if you want to select more fields, just write a "," and add more:

 $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));

This is very practical when you use a joins complex query

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

You can try,

<div asp-validation-summary="All" class="text-danger"></div>

How do I sort a vector of pairs based on the second element of the pair?

Try swapping the elements of the pairs so you can use std::sort() as normal.

Cross-Origin Read Blocking (CORB)

I had the same problem with my Chrome extension. When I tried to add to my manifest "content_scripts" option this part:

//{
    //  "matches": [ "<all_urls>" ],
    //  "css": [ "myStyles.css" ],
    //  "js": [ "test.js" ]
    //}

And I remove the other part from my manifest "permissons":

"https://*/"

Only when I delete it CORB on one of my XHR reqest disappare.

Worst of all that there are few XHR reqest in my code and only one of them start to get CORB error (why CORB do not appare on other XHR I do not know; why manifest changes coused this error I do not know). That's why I inspected the entire code again and again by few hours and lost a lot of time.

Getting char from string at specified index

char = split_string_to_char(text)(index)

------

Function split_string_to_char(text) As String()

   Dim chars() As String
   For char_count = 1 To Len(text)
      ReDim Preserve chars(char_count - 1)
      chars(char_count - 1) = Mid(text, char_count, 1)
   Next
   split_string_to_char = chars
End Function

How do you set the title color for the new Toolbar?

I struggled with this for a few hours today because all of these answers are kind of out of date now what with MDC and the new theming capabilities I just could not see how to override app:titleTextColor app wide as a style.

The answer is that titleTextColor is available in the styles.xml is you are overriding something that inherits from Widget.AppCompat.Toolbar. Today I think the best choice is supposed to be Widget.MaterialComponents.Toolbar:

<style name="Widget.LL.Toolbar" parent="@style/Widget.MaterialComponents.Toolbar">
     <item name="titleTextAppearance">@style/TextAppearance.LL.Toolbar</item>
     <item name="titleTextColor">@color/white</item>
     <item name="android:background">?attr/colorSecondary</item>
</style>

<style name="TextAppearance.LL.Toolbar" parent="@style/TextAppearance.Widget.AppCompat.Toolbar.Title">
     <item name="android:textStyle">bold</item>
</style>

And in your app theme, specify the toolbarStyle:

<item name="toolbarStyle">@style/Widget.LL.Toolbar</item>

Now you can leave the xml where you specify the tool bar unchanged. For a long time I thought changing the android:textColor in the toolbar title text appearance should be working, but for some reason it does not.

docker : invalid reference format

I had the same issue when I copy-pasted the command. Instead, when I typed-in the entire command, it worked!

Good Luck...

How can you test if an object has a specific property?

Real similar to a javascript check:

foreach($member in $members)
{
    if($member.PropertyName)
    {
        Write $member.PropertyName
    }
    else
    {
        Write "Nope!"
    }
}

nginx - client_max_body_size has no effect

I meet the same problem, but I found it nothing to do with nginx. I am using nodejs as backend server, use nginx as a reverse proxy, 413 code is triggered by node server. node use koa parse the body. koa limit the urlencoded length.

formLimit: limit of the urlencoded body. If the body ends up being larger than this limit, a 413 error code is returned. Default is 56kb.

set formLimit to bigger can solve this problem.

How to convert an OrderedDict into a regular dict in python3

Even though this is a year old question, I would like to say that using dict will not help if you have an ordered dict within the ordered dict. The simplest way that could convert those recursive ordered dict will be

import json
from collections import OrderedDict
input_dict = OrderedDict([('method', 'constant'), ('recursive', OrderedDict([('m', 'c')]))])
output_dict = json.loads(json.dumps(input_dict))
print output_dict

Can Android do peer-to-peer ad-hoc networking?

Here's a bug report on the feature you're requesting.

It's status is "reviewed" but I don't believe it's been implemented yet.

http://code.google.com/p/android/issues/detail?id=82

What is the meaning of {...this.props} in Reactjs

You will use props in your child component

for example

if your now component props is

{
   booking: 4,
   isDisable: false
}

you can use this props in your child compoenet

 <div {...this.props}> ... </div>

in you child component, you will receive all your parent props.

Numpy: Divide each row by a vector element

Pythonic way to do this is ...

np.divide(data.T,vector).T

This takes care of reshaping and also the results are in floating point format. In other answers results are in rounded integer format.

#NOTE: No of columns in both data and vector should match

How to create custom view programmatically in swift having controls text field, button etc

The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.

But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:

customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)

Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.

Android overlay a view ontop of everything?

The best way is ViewOverlay , You can add any drawable as overlay to any view as its overlay since Android JellyBeanMR2(Api 18).

Add mMyDrawable to mMyView as its overlay:

mMyDrawable.setBounds(0, 0, mMyView.getMeasuredWidth(), mMyView.getMeasuredHeight())
mMyView.getOverlay().add(mMyDrawable)

Switching between GCC and Clang/LLVM using CMake

You can use the option command:

option(USE_CLANG "build application with clang" OFF) # OFF is the default

and then wrap the clang-compiler settings in if()s:

if(USE_CLANG)
    SET (...)
    ....
endif(USE_CLANG)

This way it is displayed as an cmake option in the gui-configuration tools.

To make it systemwide you can of course use an environment variable as the default value or stay with Ferruccio's answer.

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

I messed up with my CA files while I setup up goagent proxy. Can't pull data from github, and get the same warning:

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

use Vonc's method, get the certificate from github, and put it into /etc/ssl/certs/ca-certificates.crt, problem solved.

echo -n | openssl s_client -showcerts -connect github.com:443 2>/dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'

How to avoid "Permission denied" when using pip with virtualenv

Solution:

If you created the virtualenv as root, run the following command:

sudo chown -R your_username:your_username path/to/virtuaelenv/

This will probably fix your problem.

Cheers

PHP Converting Integer to Date, reverse of strtotime

Yes you can convert it back. You can try:

date("Y-m-d H:i:s", 1388516401);

The logic behind this conversion from date to an integer is explained in strtotime in PHP:

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

For example, strtotime("1970-01-01 00:00:00") gives you 0 and strtotime("1970-01-01 00:00:01") gives you 1.

This means that if you are printing strtotime("2014-01-01 00:00:01") which will give you output 1388516401, so the date 2014-01-01 00:00:01 is 1,388,516,401 seconds after January 1 1970 00:00:00 UTC.

ES6 modules implementation, how to load a json file

json-loader doesn't load json file if it's array, in this case you need to make sure it has a key, for example

{
    "items": [
    {
      "url": "https://api.github.com/repos/vmg/redcarpet/issues/598",
      "repository_url": "https://api.github.com/repos/vmg/redcarpet",
      "labels_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/labels{/name}",
      "comments_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/comments",
      "events_url": "https://api.github.com/repos/vmg/redcarpet/issues/598/events",
      "html_url": "https://github.com/vmg/redcarpet/issues/598",
      "id": 199425790,
      "number": 598,
      "title": "Just a heads up (LINE SEPARATOR character issue)",
    },
    ..... other items in array .....
]}

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

$data = array( 
    'name'      => $_POST['name'] , 
    'groupname' => $_POST['groupname'], 
    'age'       => $_POST['age']
);

$this->db->where('id', $_POST['id']);

$this->db->update('tbl_user', $data);

Preferred Java way to ping an HTTP URL for availability

here the writer suggests this:

public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) { e.printStackTrace(); }
    return false;
}

Possible Questions

  • Is this really fast enough?Yes, very fast!
  • Couldn’t I just ping my own page, which I want to request anyways? Sure! You could even check both, if you want to differentiate between “internet connection available” and your own servers beeing reachable What if the DNS is down? Google DNS (e.g. 8.8.8.8) is the largest public DNS service in the world. As of 2013 it serves 130 billion requests a day. Let ‘s just say, your app not responding would probably not be the talk of the day.

read the link. its seems very good

EDIT: in my exp of using it, it's not as fast as this method:

public boolean isOnline() {
    NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

they are a bit different but in the functionality for just checking the connection to internet the first method may become slow due to the connection variables.

Magento Product Attribute Get Value

A way that I know of:

$product->getResource()->getAttribute($attribute_code)
        ->getFrontend()->getValue($product)

The calling thread cannot access this object because a different thread owns it

If you encounter this problem and UI Controls were created on a separate worker thread when working with BitmapSource or ImageSource in WPF, call Freeze() method first before passing the BitmapSource or ImageSource as a parameter to any method. Using Application.Current.Dispatcher.Invoke() does not work in such instances

CSS Font "Helvetica Neue"

This font is not standard on all devices. It is installed by default on some Macs, but rarely on PCs and mobile devices.

To use this font on all devices, use a @font-face declaration in your CSS to link to it on your domain if you wish to use it.

@font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); } 
@font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf'); }

Taken from css3.info

How to convert string date to Timestamp in java?

tl;dr

java.sql.Timestamp                  
.valueOf(                           // Class-method parses SQL-style formatted date-time strings.
    "2007-11-11 12:13:14"
)                                   // Returns a `Timestamp` object.
.toInstant()                        // Converts from terrible legacy classes to modern *java.time* class.

java.sql.Timestamp.valueOf parses SQL format

If you can use the full four digits for the year, your input string of 2007-11-11 12:13:14 would be in standard SQL format assuming this value is meant to be in UTC time zone.

The java.sql.Timestamp class has a valueOf method to directly parse such strings.

String input = "2007-11-11 12:13:14" ;
java.sql.Timestamp ts = java.sql.Timestamp.valueOf( input ) ;

java.time

In Java 8 and later, the java.time framework makes it easier to verify the results. The j.s.Timestamp class has a nasty habit of implicitly applying your JVM’s current default timestamp when generating a string representation via its toString method. In contrast, the java.time classes by default use the standard ISO 8601 formats.

System.out.println( "Output: " + ts.toInstant().toString() );

how to convert a string to a bool

If you want to test if a string is a valid Boolean without any thrown exceptions you can try this :

    string stringToBool1 = "true";
    string stringToBool2 = "1";
    bool value1;
    if(bool.TryParse(stringToBool1, out value1))
    {
        MessageBox.Show(stringToBool1 + " is Boolean");
    }
    else
    {
        MessageBox.Show(stringToBool1 + " is not Boolean");
    }

outputis Boolean and the output for stringToBool2 is : 'is not Boolean'

XML Schema How to Restrict Attribute by Enumeration

<xs:element name="price" type="decimal">
<xs:attribute name="currency" type="xs:string" value="(euros|pounds|dollars)" /> 
</element> 

This would eliminate the need for enumeration completely. You could change type to double if required.

Create a text file for download on-the-fly

No need to store it anywhere. Just output the content with the appropriate content type.

<?php
    header('Content-type: text/plain');
?>Hello, world.

Add content-disposition if you wish to trigger a download prompt.

header('Content-Disposition: attachment; filename="default-filename.txt"');

Use a normal link to submit a form

use:

<input type="image" src=".."/>

or:

<button type="send"><img src=".."/> + any html code</button>

plus some CSS

Limit Decimal Places in Android EditText

More elegant way would be using a regular expression ( regex ) as follows:

public class DecimalDigitsInputFilter implements InputFilter {

Pattern mPattern;

public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
    mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

        Matcher matcher=mPattern.matcher(dest);       
        if(!matcher.matches())
            return "";
        return null;
    }

}

To use it do:

editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

[SOLVED]

I only observed this error today, for me the Error code was different though.

SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.

It was occurring randomly and not all the time. but what it noticed is, if it comes for subsequent ajax calls. so i put some delay of 5 seconds between the ajax calls and it resolved.

How to make picturebox transparent?

I've had a similar problem like this. You can not make Transparent picturebox easily such as picture that shown at top of this page, because .NET Framework and VS .NET objects are created by INHERITANCE! (Use Parent Property).

I solved this problem by RectangleShape and with the below code I removed background, if difference between PictureBox and RectangleShape is not important and doesn't matter, you can use RectangleShape easily.

private void CreateBox(int X, int Y, int ObjectType)
{
    ShapeContainer canvas = new ShapeContainer();
    RectangleShape box = new RectangleShape();
    box.Parent = canvas;
    box.Size = new System.Drawing.Size(100, 90);
    box.Location = new System.Drawing.Point(X, Y);
    box.Name = "Box" + ObjectType.ToString();
    box.BackColor = Color.Transparent;
    box.BorderColor = Color.Transparent;
    box.BackgroundImage = img.Images[ObjectType];// Load from imageBox Or any resource
    box.BackgroundImageLayout = ImageLayout.Stretch;
    box.BorderWidth = 0;
    canvas.Controls.Add(box);   // For feature use 
}

Array vs ArrayList in performance

It is pretty obvious that array[10] is faster than array.get(10), as the later internally does the same call, but adds the overhead for the function call plus additional checks.

Modern JITs however will optimize this to a degree, that you rarely have to worry about this, unless you have a very performance critical application and this has been measured to be your bottleneck.

Add an object to a python list

Is your problem similar to this:

l = [[0]] * 4
l[0][0] += 1
print l # prints "[[1], [1], [1], [1]]"

If so, you simply need to copy the objects when you store them:

import copy
l = [copy.copy(x) for x in [[0]] * 4]
l[0][0] += 1
print l # prints "[[1], [0], [0], [0]]"

The objects in question should implement a __copy__ method to copy objects. See the documentation for copy. You may also be interested in copy.deepcopy, which is there as well.

EDIT: Here's the problem:

arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(wM) # appends the wM object to the list
    wM.reset()           # clears  the wM object

You need to append a copy:

import copy
arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(copy.copy(wM)) # appends a copy to the list
    wM.reset()                      # clears the wM object

But I'm still confused as to where wM is coming from. Won't you just be copying the same wM object over and over, except clearing it after the first time so all the rest will be empty? Or does model() modify the wM (which sounds like a terrible design flaw to me)? And why are you throwing away result?

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

This is how I did it. You don't need to delete Java 9 or newer version.

Step 1: Install Java 8

You can download Java 8 from here: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Step 2: After installation of Java 8. Confirm installation of all versions.Type the following command in your terminal.

/usr/libexec/java_home -V

Step 3: Edit .bash_profile

sudo nano ~/.bash_profile

Step 4: Add 1.8 as default. (Add below line to bash_profile file).

export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

Now Press CTRL+X to exit the bash. Press 'Y' to save changes.

Step 5: Reload bash_profile

source ~/.bash_profile

Step 6: Confirm current version of Java

java -version

Using regular expression in css?

You can' just add a class to each of your DIVs and apply the rule to the class in this way:

HTML:

<div class="myclass" id="s1">...</div>
<div class="myclass" id="s2">...</div>

CSS:

//css
.myclass
{
   ...
}