Programs & Examples On #Hg git

A tool for communicating changes between mercurial and git.

Path to MSBuild

Poking around the registry, it looks like

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\2.0
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\3.5
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0

may be what you're after; fire up regedit.exe and have a look.

Query via command line (per Nikolay Botev)

reg.exe query "HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0" /v MSBuildToolsPath

Query via PowerShell (per MovGP0)

dir HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\

Environment variables in Mac OS X

There are several places where you can set environment variables.

  • ~/.profile: use this for variables you want to set in all programs launched from the terminal (note that, unlike on Linux, all shells opened in Terminal.app are login shells).
  • ~/.bashrc: this is invoked for shells which are not login shells. Use this for aliases and other things which need to be redefined in subshells, not for environment variables that are inherited.
  • /etc/profile: this is loaded before ~/.profile, but is otherwise equivalent. Use it when you want the variable to apply to terminal programs launched by all users on the machine (assuming they use bash).
  • ~/.MacOSX/environment.plist: this is read by loginwindow on login. It applies to all applications, including GUI ones, except those launched by Spotlight in 10.5 (not 10.6). It requires you to logout and login again for changes to take effect. This file is no longer supported as of OS X 10.8.
  • your user's launchd instance: this applies to all programs launched by the user, GUI and CLI. You can apply changes at any time by using the setenv command in launchctl. In theory, you should be able to put setenv commands in ~/.launchd.conf, and launchd would read them automatically when the user logs in, but in practice support for this file was never implemented. Instead, you can use another mechanism to execute a script at login, and have that script call launchctl to set up the launchd environment.
  • /etc/launchd.conf: this is read by launchd when the system starts up and when a user logs in. They affect every single process on the system, because launchd is the root process. To apply changes to the running root launchd you can pipe the commands into sudo launchctl.

The fundamental things to understand are:

  • environment variables are inherited by a process's children at the time they are forked.
  • the root process is a launchd instance, and there is also a separate launchd instance per user session.
  • launchd allows you to change its current environment variables using launchctl; the updated variables are then inherited by all new processes it forks from then on.

Example of setting an environment variable with launchd:

echo setenv REPLACE_WITH_VAR REPLACE_WITH_VALUE | launchctl

Now, launch your GUI app that uses the variable, and voila!

To work around the fact that ~/.launchd.conf does not work, you can put the following script in ~/Library/LaunchAgents/local.launchd.conf.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>local.launchd.conf</string>
  <key>ProgramArguments</key>
  <array>
    <string>sh</string>
    <string>-c</string>
    <string>launchctl &lt; ~/.launchd.conf</string>    
  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>

Then you can put setenv REPLACE_WITH_VAR REPLACE_WITH_VALUE inside ~/.launchd.conf, and it will be executed at each login.

Note that, when piping a command list into launchctl in this fashion, you will not be able to set environment variables with values containing spaces. If you need to do so, you can call launchctl as follows: launchctl setenv MYVARIABLE "QUOTE THE STRING".

Also, note that other programs that run at login may execute before the launchagent, and thus may not see the environment variables it sets.

Running a Python script from PHP

The above methods seem to be complex. Use my method as a reference.

I have these two files:

  • run.php

  • mkdir.py

Here, I've created an HTML page which contains a GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.

run.php

_x000D_
_x000D_
<html>_x000D_
 <body>_x000D_
  <head>_x000D_
   <title>_x000D_
     run_x000D_
   </title>_x000D_
  </head>_x000D_
_x000D_
   <form method="post">_x000D_
_x000D_
    <input type="submit" value="GO" name="GO">_x000D_
   </form>_x000D_
 </body>_x000D_
</html>_x000D_
_x000D_
<?php_x000D_
 if(isset($_POST['GO']))_x000D_
 {_x000D_
  shell_exec("python /var/www/html/lab/mkdir.py");_x000D_
  echo"success";_x000D_
 }_x000D_
?>
_x000D_
_x000D_
_x000D_

mkdir.py

#!/usr/bin/env python    
import os    
os.makedirs("thisfolder");

What static analysis tools are available for C#?

Aside from the excellent list by madgnome, I would add a duplicate code detector that is based off the command line (but is free):

http://sourceforge.net/projects/duplo/

Make javascript alert Yes/No Instead of Ok/Cancel

You can use jQuery UI Dialog.

These libraries create HTML elements that look and behave like a dialog box, allowing you to put anything you want (including form elements or video) in the dialog.

optional parameters in SQL Server stored proc?

2014 and above at least you can set a default and it will take that and NOT error when you do not pass that parameter. Partial Example: the 3rd parameter is added as optional. exec of the actual procedure with only the first two parameters worked fine

exec getlist 47,1,0

create procedure getlist
   @convId int,
   @SortOrder int,
   @contestantsOnly bit = 0
as

How do you push a tag to a remote repository using Git?

git push --follow-tags

This is a sane option introduced in Git 1.8.3:

git push --follow-tags

It pushes both commits and only tags that are both:

  • annotated
  • reachable (an ancestor) from the pushed commits

This is sane because:

It is for those reasons that --tags should be avoided.

Git 2.4 has added the push.followTags option to turn that flag on by default which you can set with:

git config --global push.followTags true

or by adding followTags = true to the [push] section of your ~/.gitconfig file.

CSS content generation before or after 'input' elements

Use tags label and our method for =, is bound to input. If follow the rules of the form, and avoid confusion with tags, use the following:

<style type="text/css">
    label.lab:before { content: 'input: '; }
</style>

or compare (short code):

<style type="text/css">
    div label { content: 'input: '; color: red; }
</style>

form....

<label class="lab" for="single"></label><input name="n" id="single" ...><label for="single"> - simle</label>

or compare (short code):

<div><label></label><input name="n" ...></div>

What does Java option -Xmx stand for?

The -Xmx option changes the maximum Heap Space for the VM. java -Xmx1024m means that the VM can allocate a maximum of 1024 MB. In layman terms this means that the application can use a maximum of 1024MB of memory.

How to calculate age in T-SQL with years, months, and days

There is another method for calculate age is

See below table

    FirstName       LastName    DOB
    sai             krishnan    1991-11-04
    Harish          S A         1998-10-11

For finding age,you can calculate through month

  Select datediff(MONTH,DOB,getdate())/12 as dates from [Organization].[Employee]

Result will be

firstname   dates
sai         27
Harish      20

How to wrap text in textview in Android

Just set layout_with to a definate size, when the text fills the maximum width it will overflow to the next line causing a wrap effect.

<TextView
    android:id="@+id/segmentText"
    android:layout_marginTop="10dp"
    android:layout_below="@+id/segmentHeader"
    android:text="You have the option to record in one go or segments(if you swap options 
    you will loose your current recordings)"
    android:layout_width="300dp"
    android:layout_height="wrap_content"/>

What is the difference between an annotated and unannotated tag?

The big difference is perfectly explained here.

Basically, lightweight tags are just pointers to specific commits. No further information is saved; on the other hand, annotated tags are regular objects, which have an author and a date and can be referred because they have their own SHA key.

If knowing who tagged what and when is relevant for you, then use annotated tags. If you just want to tag a specific point in your development, no matter who and when did that, then lightweight tags are good enough.

Normally you'd go for annotated tags, but it is really up to the Git master of the project.

How to count down in for loop?

In python, when you have an iterable, usually you iterate without an index:

letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
    print(l)

If you need to traverse the iterable in reverse order, you would do:

for l in letters[::-1]:
    print(l)

When for any reason you need the index, you can use enumerate:

for i, l in enumerate(letters, start=1): #start is 0 by default
    print(i,l)

You can enumerate in reverse order too...

for i, l in enumerate(letters[::-1])
    print(i,l)

ON ANOTHER NOTE...

Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map:

If we need to capitilize each letter:

map(str.upper, letters)

Or get the Unicode code of each letter:

map(ord, letters)

Using generic std::function objects with member functions in one class

You can use functors if you want a less generic and more precise control under the hood. Example with my win32 api to forward api message from a class to another class.

IListener.h

#include <windows.h>
class IListener { 
    public:
    virtual ~IListener() {}
    virtual LRESULT operator()(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) = 0;
};

Listener.h

#include "IListener.h"
template <typename D> class Listener : public IListener {
    public:
    typedef LRESULT (D::*WMFuncPtr)(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); 

    private:
    D* _instance;
    WMFuncPtr _wmFuncPtr; 

    public:
    virtual ~Listener() {}
    virtual LRESULT operator()(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) override {
        return (_instance->*_wmFuncPtr)(hWnd, uMsg, wParam, lParam);
    }

    Listener(D* instance, WMFuncPtr wmFuncPtr) {
        _instance = instance;
        _wmFuncPtr = wmFuncPtr;
    }
};

Dispatcher.h

#include <map>
#include "Listener.h"

class Dispatcher {
    private:
        //Storage map for message/pointers
        std::map<UINT /*WM_MESSAGE*/, IListener*> _listeners; 

    public:
        virtual ~Dispatcher() { //clear the map }

        //Return a previously registered callable funtion pointer for uMsg.
        IListener* get(UINT uMsg) {
            typename std::map<UINT, IListener*>::iterator itEvt;
            if((itEvt = _listeners.find(uMsg)) == _listeners.end()) {
                return NULL;
            }
            return itEvt->second;
        }

        //Set a member function to receive message. 
        //Example Button->add<MyClass>(WM_COMMAND, this, &MyClass::myfunc);
        template <typename D> void add(UINT uMsg, D* instance, typename Listener<D>::WMFuncPtr wmFuncPtr) {
            _listeners[uMsg] = new Listener<D>(instance, wmFuncPtr);
        }

};

Usage principles

class Button {
    public:
    Dispatcher _dispatcher;
    //button window forward all received message to a listener
    LRESULT onMessage(HWND hWnd, UINT uMsg, WPARAM w, LPARAM l) {
        //to return a precise message like WM_CREATE, you have just
        //search it in the map.
        return _dispatcher[uMsg](hWnd, uMsg, w, l);
    }
};

class Myclass {
    Button _button;
    //the listener for Button messages
    LRESULT button_listener(HWND hWnd, UINT uMsg, WPARAM w, LPARAM l) {
        return 0;
    }

    //Register the listener for Button messages
    void initialize() {
        //now all message received from button are forwarded to button_listener function 
       _button._dispatcher.add(WM_CREATE, this, &Myclass::button_listener);
    }
};

Good luck and thank to all for sharing knowledge.

javascript - replace dash (hyphen) with a space

I think the problem you are facing is almost this: -

str = str.replace("-", ' ');

You need to re-assign the result of the replacement to str, to see the reflected change.

From MSDN Javascript reference: -

The result of the replace method is a copy of stringObj after the specified replacements have been made.

To replace all the -, you would need to use /g modifier with a regex parameter: -

str = str.replace(/-/g, ' ');

Makefile ifeq logical or

Here more flexible variant: it uses external shell, but allows to check for arbitrary conditions:

ifeq ($(shell test ".$(GCC_MINOR)" = .4  -o  \
                   ".$(GCC_MINOR)" = .5  -o  \
                   ".$(TODAY)"     = .Friday  &&  printf "true"), true)
    CFLAGS += -fno-strict-overflow
endif

How to determine device screen size category (small, normal, large, xlarge) using code?

Thanks for the answers above, that helped me a lot :-) But for those (like me) forced to still support Android 1.5 we can use java reflection for backward compatible:

Configuration conf = getResources().getConfiguration();
int screenLayout = 1; // application default behavior
try {
    Field field = conf.getClass().getDeclaredField("screenLayout");
    screenLayout = field.getInt(conf);
} catch (Exception e) {
    // NoSuchFieldException or related stuff
}
// Configuration.SCREENLAYOUT_SIZE_MASK == 15
int screenType = screenLayout & 15;
// Configuration.SCREENLAYOUT_SIZE_SMALL == 1
// Configuration.SCREENLAYOUT_SIZE_NORMAL == 2
// Configuration.SCREENLAYOUT_SIZE_LARGE == 3
// Configuration.SCREENLAYOUT_SIZE_XLARGE == 4
if (screenType == 1) {
    ...
} else if (screenType == 2) {
    ...
} else if (screenType == 3) {
    ...
} else if (screenType == 4) {
    ...
} else { // undefined
    ...
}

jQuery Set Cursor Position in Text Area

I found a solution that works for me:

$.fn.setCursorPosition = function(position){
    if(this.length == 0) return this;
    return $(this).setSelection(position, position);
}

$.fn.setSelection = function(selectionStart, selectionEnd) {
    if(this.length == 0) return this;
    var input = this[0];

    if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    } else if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }

    return this;
}

$.fn.focusEnd = function(){
    this.setCursorPosition(this.val().length);
            return this;
}

Now you can move the focus to the end of any element by calling:

$(element).focusEnd();

Or you specify the position.

$(element).setCursorPosition(3); // This will focus on the third character.

jQuery checkbox onChange

$('input[type=checkbox]').change(function () {
    alert('changed');
});

mappedBy reference an unknown target entity property

The mappedBy attribute is referencing customer while the property is mCustomer, hence the error message. So either change your mapping into:

/** The collection of stores. */
@OneToMany(mappedBy = "mCustomer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Collection<Store> stores;

Or change the entity property into customer (which is what I would do).

The mappedBy reference indicates "Go look over on the bean property named 'customer' on the thing I have a collection of to find the configuration."

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

Put in head link to google styles

<link href="https://fonts.googleapis.com/icon?family=Material+Icons+Outlined" rel="stylesheet">

and in body something like this

<i class="material-icons-outlined">bookmarks</i>

Specify sudo password for Ansible

Using ansible 2.4.1.0 and the following shall work:

[all]
17.26.131.10
17.26.131.11
17.26.131.12
17.26.131.13
17.26.131.14

[all:vars]
ansible_connection=ssh
ansible_user=per
ansible_ssh_pass=per
ansible_sudo_pass=per

And just run the playbook with this inventory as:

ansible-playbook -i inventory copyTest.yml

Inserting an image with PHP and FPDF

You can't treat a PDF like an HTML document. Images can't "float" within a document and have things flow around them, or flow with surrounding text. FPDF allows you to embed html in a text block, but only because it parses the tags and replaces <i> and <b> and so on with Postscript equivalent commands. It's not smart enough to dynamically place an image.

In other words, you have to specify coordinates (and if you don't, the current location's coordinates will be used anyways).

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

How to install a node.js module without using npm?

These modules can't be installed using npm.

Actually you can install a module by specifying instead of a name a local path. As long as the repository has a valid package.json file it should work.


Type npm -l and a pretty help will appear like so :

CLI:

...
install     npm install <tarball file>
                npm install <tarball url>
                npm install <folder>
                npm install <pkg>
                npm install <pkg>@<tag>
                npm install <pkg>@<version>
                npm install <pkg>@<version range>
                
                Can specify one or more: npm install ./foo.tgz bar@stable /some/folder
                If no argument is supplied and ./npm-shrinkwrap.json is 
                present, installs dependencies specified in the shrinkwrap.
                Otherwise, installs dependencies from ./package.json.

What caught my eyes was: npm install <folder>

In my case I had trouble with mrt module so I did this (in a temporary directory)

  • Clone the repo

       git clone https://github.com/oortcloud/meteorite.git
    
  • And I install it globally with:

       npm install -g ./meteorite
    

Tip:

One can also install in the same manner the repo to a local npm project with:

     npm install ../meteorite

And also one can create a link to the repo, in case a patch in development is needed:

     npm link ../meteorite

Edit:

Nowadays npm supports also github and git repositories (see https://docs.npmjs.com/cli/v6/commands/npm-install), as a shorthand you can run :

npm i github.com:some-user/some-repo

Android failed to load JS bundle

The following made it work for me on Ubuntu 14.04:

cd (App Dir)
react-native start > /dev/null 2>&1 &
adb reverse tcp:8081 tcp:8081

Update: See

Update 2: @scgough We got this error because React Native (RN) was unable to fetch JavaScript from the dev server running on our workstations. You can see why this happens here:

https://github.com/facebook/react-native/blob/42eb5464fd8a65ed84b799de5d4dc225349449be/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.java#L116-L137

If your RN app detects that you're using Genymotion or the emulator it tries to fetch the JavaScript from GENYMOTION_LOCALHOST (10.0.3.2) or EMULATOR_LOCALHOST (10.0.2.2). Otherwise it presumes that you're using a device and it tries to fetch the JavaScript from DEVICE_LOCALHOST (localhost). The problem is that the dev server runs on your workstation's localhost, not the device's, so in order to get it to work you need to either:

How to use Macro argument as string literal?

Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);

Creating JSON on the fly with JObject

Neither dynamic, nor JObject.FromObject solution works when you have JSON properties that are not valid C# variable names e.g. "@odata.etag". I prefer the indexer initializer syntax in my test cases:

JObject jsonObject = new JObject
{
    ["Date"] = DateTime.Now,
    ["Album"] = "Me Against The World",
    ["Year"] = 1995,
    ["Artist"] = "2Pac"
};

Having separate set of enclosing symbols for initializing JObject and for adding properties to it makes the index initializers more readable than classic object initializers, especially in case of compound JSON objects as below:

JObject jsonObject = new JObject
{
    ["Date"] = DateTime.Now,
    ["Album"] = "Me Against The World",
    ["Year"] = 1995,
    ["Artist"] = new JObject
    {
        ["Name"] = "2Pac",
        ["Age"] = 28
    }
};

With object initializer syntax, the above initialization would be:

JObject jsonObject = new JObject
{
    { "Date", DateTime.Now },
    { "Album", "Me Against The World" },
    { "Year", 1995 }, 
    { "Artist", new JObject
        {
            { "Name", "2Pac" },
            { "Age", 28 }
        }
    }
};

What is a "static" function in C?

First: It's generally a bad idea to include a .cpp file in another file - it leads to problems like this :-) The normal way is to create separate compilation units, and add a header file for the included file.

Secondly:

C++ has some confusing terminology here - I didn't know about it until pointed out in comments.

a) static functions - inherited from C, and what you are talking about here. Outside any class. A static function means that it isn't visible outside the current compilation unit - so in your case a.obj has a copy and your other code has an independent copy. (Bloating the final executable with multiple copies of the code).

b) static member function - what Object Orientation terms a static method. Lives inside a class. You call this with the class rather than through an object instance.

These two different static function definitions are completely different. Be careful - here be dragons.

Find directory name with wildcard or similar to "like"

find supports wildcard matches, just add a *:

find / -type d -name "ora10*"

Deploying website: 500 - Internal server error

My first attempt to publish and then run a very simple site serving only HTML produced "The page cannot be displayed because an internal server error has occurred."

The problem: I had the site set to .NET 3.5 in Visual Studio (right click web site project -> Property Pages -> Build), but had the Web Site in Azure configured as .NET 4.0. Oops! I changed it to 3.5 in Azure, and it worked.

How to refresh app upon shaking the device?

You might want to try open source tinybus. With it shake detection is as easy as this.

public class MainActivity extends Activity {

    private Bus mBus;

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

        // Create a bus and attach it to activity
        mBus = TinyBus.from(this).wire(new ShakeEventWire());
    }

    @Subscribe
    public void onShakeEvent(ShakeEvent event) {
        Toast.makeText(this, "Device has been shaken", 
                Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mBus.register(this);
    }

    @Override
    protected void onStop() {
        mBus.unregister(this);
        super.onStop();
    }
}

It uses seismic for shake detection.

How to make an AlertDialog in Flutter?

If you want beautiful and responsive alert dialog then you can use flutter packages like

rflutter alert ,fancy dialog,rich alert,sweet alert dialogs,easy dialog & easy alert

These alerts are good looking and responsive. Among them rflutter alert is the best. currently I am using rflutter alert for my apps.

Comments in Android Layout xml

XML comments start with <!-- and end with -->.

For example:

<!-- This is a comment. -->

C# ListView Column Width Auto

You gave the answer: -2 will autosize the column to the length of the text in the column header, -1 will autosize to the longest item in the column. All according to MSDN. Note though that in the case of -1, you will need to set the column width after adding the item(s). So if you add a new item, you will also need to assign the width property of the column (or columns) that you want to autosize according to data in ListView control.

Split a string into array in Perl

I found this one to be very simple!

my $line = "file1.gz file2.gz file3.gz";

my @abc =  ($line =~ /(\w+[.]\w+)/g);

print $abc[0],"\n";
print $abc[1],"\n";
print $abc[2],"\n";

output:

file1.gz 
file2.gz 
file3.gz

Here take a look at this tutorial to find more on Perl regular expression and scroll down to More matching section.

How to check if a column exists before adding it to an existing table in PL/SQL?

Or, you can ignore the error:

declare
    column_exists exception;
    pragma exception_init (column_exists , -01430);
begin
    execute immediate 'ALTER TABLE db.tablename ADD columnname NVARCHAR2(30)';
    exception when column_exists then null;
end;
/

Is there StartsWith or Contains in t sql with variables?

I would use

like 'Express Edition%'

Example:

DECLARE @edition varchar(50); 
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)

DECLARE @isExpress bit
if @edition like 'Express Edition%'
    set @isExpress = 1;
else
    set @isExpress = 0;

print @isExpress

How do I set the driver's python version in spark?

Please look at the below snippet:

#setting environment variable for pyspark in linux||ubuntu
#goto --- /usr/local/spark/conf
#create a new file named spark-env.sh copy all content of spark-env.sh.template to it
#then add below lines to it, with path to python

PYSPARK_PYTHON="/usr/bin/python3"
PYSPARK_DRIVER_PYTHON="/usr/bin/python3"
PYSPARK_DRIVER_PYTHON_OPTS="notebook --no-browser"
#i was running python 3.6 ||run - 'which python' in terminal to find the path of python

jQuery - How to dynamically add a validation rule

You need to call .validate() before you can add rules this way, like this:

$("#myForm").validate(); //sets up the validator
$("input[id*=Hours]").rules("add", "required");

The .validate() documentation is a good guide, here's the blurb about .rules("add", option):

Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $("form").validate() is called first.

PHP regular expressions: No ending delimiter '^' found in

Your regex pattern needs to be in delimiters:

$numpattern="/^([0-9]+)$/";

How to pick an image from gallery (SD Card) for my app?

public class EMView extends Activity {
ImageView img,img1;
int column_index;
  Intent intent=null;
// Declare our Views, so we can access them later
String logo,imagePath,Logo;
Cursor cursor;
//YOU CAN EDIT THIS TO WHATEVER YOU WANT
private static final int SELECT_PICTURE = 1;

 String selectedImagePath;
//ADDED
 String filemanagerstring;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    img= (ImageView)findViewById(R.id.gimg1);



    ((Button) findViewById(R.id.Button01))
    .setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {

            // in onCreate or any event where your want the user to
            // select a file
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,
                    "Select Picture"), SELECT_PICTURE);


        }
    });
}

//UPDATED
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();

            //OI FILE Manager
            filemanagerstring = selectedImageUri.getPath();

            //MEDIA GALLERY
            selectedImagePath = getPath(selectedImageUri);


            img.setImageURI(selectedImageUri);

           imagePath.getBytes();
           TextView txt = (TextView)findViewById(R.id.title);
           txt.setText(imagePath.toString());


           Bitmap bm = BitmapFactory.decodeFile(imagePath);

          // img1.setImageBitmap(bm);



        }

    }

}

//UPDATED!
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
        .getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
 imagePath = cursor.getString(column_index);

return cursor.getString(column_index);
}

}

jdk7 32 bit windows version to download

As detailed in the Oracle Java SE Support Roadmap

After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive

Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe (64-bit is named jdk-7u80-windows-x64.exe.

Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget to grab the file without signing in.

wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I have tried out all the possible answers from stackOverflow, finally i solved after a week Long search . I have used the coordinate layout and i changed this with linearLayout and my problem is fixed. I dont know possibly the coordinate layout has bugs or anything my mistake.

About the Full Screen And No Titlebar from manifest

To set your App or any individual activity display in Full Screen mode, insert the code

<application 
    android:icon="@drawable/icon" 
    android:label="@string/app_name" 
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen">

in AndroidManifest.xml, under application or activity tab.

two divs the same line, one dynamic width, one fixed

@Yijie; Check the link maybe that's you want http://jsfiddle.net/sandeep/NCkL4/7/

EDIT:

http://jsfiddle.net/sandeep/NCkL4/8/

OR SEE THE FOLLOWING SNIPPET

_x000D_
_x000D_
#parent{_x000D_
    overflow:hidden;_x000D_
    background:yellow;_x000D_
    position:relative;_x000D_
    display:table;_x000D_
}_x000D_
.left{_x000D_
    display:table-cell;_x000D_
}_x000D_
.right{_x000D_
    background:red;_x000D_
    width:50px;_x000D_
    height:100%;_x000D_
    display:table-cell;_x000D_
}_x000D_
body{_x000D_
    margin:0;_x000D_
    padding:0;_x000D_
}
_x000D_
<div id="parent">_x000D_
  <div class="left">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>_x000D_
  <div class="right">fixed</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to specify in crontab by what user to run script?

You can also try using runuser (as root) to run a command as a different user

*/1 * * * * runuser php5 \
            --command="/var/www/web/includes/crontab/queue_process.php \
                       >> /var/www/web/includes/crontab/queue.log 2>&1"

See also: man runuser

Python one-line "for" expression

If you really only need to add the items in one array to another, the '+' operator is already overloaded to do that, incidentally:

a1 = [1,2,3,4,5]
a2 = [6,7,8,9]
a1 + a2
--> [1, 2, 3, 4, 5, 6, 7, 8, 9]

Dynamic creation of table with DOM

var html = "";
    for (var i = 0; i < data.length; i++){
    html +="<tr>"+
            "<td>"+ (i+1) + "</td>"+
            "<td>"+ data[i].name + "</td>"+
            "<td>"+ data[i].number + "</td>"+
            "<td>"+ data[i].city + "</td>"+
            "<td>"+ data[i].hobby + "</td>"+
            "<td>"+ data[i].birthdate + "</td>"+"<td><button data-arrayIndex='"+ i +"' onclick='editData(this)'>Edit</button><button data-arrayIndex='"+ i +"' onclick='deleteData()'>Delete</button></td>"+"</tr>";
}
$("#tableHtml").html(html);

Finding whether a point lies inside a rectangle or not

How is the rectangle represented? Three points? Four points? Point, sides and angle? Two points and a side? Something else? Without knowing that, any attempts to answer your question will have only purely academic value.

In any case, for any convex polygon (including rectangle) the test is very simple: check each edge of the polygon, assuming each edge is oriented in counterclockwise direction, and test whether the point lies to the left of the edge (in the left-hand half-plane). If all edges pass the test - the point is inside. If at least one fails - the point is outside.

In order to test whether the point (xp, yp) lies on the left-hand side of the edge (x1, y1) - (x2, y2), you just need to calculate

D = (x2 - x1) * (yp - y1) - (xp - x1) * (y2 - y1)

If D > 0, the point is on the left-hand side. If D < 0, the point is on the right-hand side. If D = 0, the point is on the line.


The previous version of this answer described a seemingly different version of left-hand side test (see below). But it can be easily shown that it calculates the same value.

... In order to test whether the point (xp, yp) lies on the left-hand side of the edge (x1, y1) - (x2, y2), you need to build the line equation for the line containing the edge. The equation is as follows

A * x + B * y + C = 0

where

A = -(y2 - y1)
B = x2 - x1
C = -(A * x1 + B * y1)

Now all you need to do is to calculate

D = A * xp + B * yp + C

If D > 0, the point is on the left-hand side. If D < 0, the point is on the right-hand side. If D = 0, the point is on the line.

However, this test, again, works for any convex polygon, meaning that it might be too generic for a rectangle. A rectangle might allow a simpler test... For example, in a rectangle (or in any other parallelogram) the values of A and B have the same magnitude but different signs for opposing (i.e. parallel) edges, which can be exploited to simplify the test.

css padding is not working in outlook

To create HTML in email template that is emailer/newsletter, padding/margin is not supporting on email clients. You can take 1x1 size of blank gif image and use it.

<tr>
  <td align="left" valign="top" style="background-color:#7d9aaa;">
    <table width="640" cellspacing="0" cellpadding="0" border="0">
      <tr>
        <td align="left" valign="top" colspan="5"><img style="display:block;" src="images/spacer.gif" width="1" height="10"  alt="" /></td>
      </tr>
      <tr>
        <td align="left" valign="top"><img style="display:block;" src="images/spacer.gif" width="20" height="1"  alt="" /></td>
        <td align="right" valign="top"><font face="arial" color="#ffffff" style="font-size:14px;"><a href="#" style="color:#ffffff; text-decoration:none; cursor:pointer;" target="_blank">Order Confirmation</a></font></td>
        <td align="left" valign="top" width="200"><img style="display:block;" src="images/spacer.gif" width="200" height="1"  alt="" /></td>
        <td align="left" valign="top"><font face="arial" color="#ffffff" style="font-size:14px;">Your Confirmation Number is 260556</font></td>
        <td align="left" valign="top"><img style="display:block;" src="images/spacer.gif" width="20" height="1"  alt="" /></td>
      </tr>
      <tr>
        <td align="left" valign="top" colspan="5"><img style="display:block;" src="images/spacer.gif" width="1" height="10"  alt="" /></td>
      </tr>
    </table>
</td>
</tr>

What is the maximum possible length of a query string?

Although officially there is no limit specified by RFC 2616, many security protocols and recommendations state that maxQueryStrings on a server should be set to a maximum character limit of 1024. While the entire URL, including the querystring, should be set to a max of 2048 characters. This is to prevent the Slow HTTP Request DDOS vulnerability on a web server. This typically shows up as a vulnerability on the Qualys Web Application Scanner and other security scanners.

Please see the below example code for Windows IIS Servers with Web.config:

<system.webServer>
<security>
    <requestFiltering>
        <requestLimits maxQueryString="1024" maxUrl="2048">
           <headerLimits>
              <add header="Content-type" sizeLimit="100" />
           </headerLimits>
        </requestLimits>
     </requestFiltering>
</security>
</system.webServer>

This would also work on a server level using machine.config.

Note: Limiting query string and URL length may not completely prevent Slow HTTP Requests DDOS attack but it is one step you can take to prevent it.

How to get JS variable to retain value after page refresh?

This is possible with window.localStorage or window.sessionStorage. The difference is that sessionStorage lasts for as long as the browser stays open, localStorage survives past browser restarts. The persistence applies to the entire web site not just a single page of it.

When you need to set a variable that should be reflected in the next page(s), use:

var someVarName = "value";
localStorage.setItem("someVarKey", someVarName);

And in any page (like when the page has loaded), get it like:

var someVarName = localStorage.getItem("someVarKey");

.getItem() will return null if no value stored, or the value stored.

Note that only string values can be stored in this storage, but this can be overcome by using JSON.stringify and JSON.parse. Technically, whenever you call .setItem(), it will call .toString() on the value and store that.

MDN's DOM storage guide (linked below), has workarounds/polyfills, that end up falling back to stuff like cookies, if localStorage isn't available.

It wouldn't be a bad idea to use an existing, or create your own mini library, that abstracts the ability to save any data type (like object literals, arrays, etc.).


References:

How can I remove 3 characters at the end of a string in php?

Just do:

echo substr($string, 0, -3);

You don't need to use a strlen call, since, as noted in the substr docs:

If length is given and is negative, then that many characters will be omitted from the end of string

React.js inline style best practices

The style attribute in React expect the value to be an object, ie Key value pair.

style = {} will have another object inside it like {float:'right'} to make it work.

<span style={{float:'right'}}>{'Download Audit'}</span>

Hope this solves the problem

Location of Django logs and errors

Add to your settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

And it will create a file called debug.log in the root of your. https://docs.djangoproject.com/en/1.10/topics/logging/

Differences between Emacs and Vim

VI is always available and will run on the most crippled, single user mode, broken graphics, no keymap, slow link machine - so it's worth knowing how to edit simple files in it just for sysadmin tasks.

Emacs is a complete user interface in an editor. The idea is that you fire up Emacs when you start the machine and never leave it. It's possible to have thousands of sessions present.

Whether learning the capabilities of Emacs are worth it compared to using a GUI editor/IDE and using something like python/awk/etc for extra tasks is up to you.

SQL Server - find nth occurrence in a string

You can use the CHARINDEX and specify the starting location:

DECLARE @x VARCHAR(32) = 'MS-SQL-Server';

SELECT 
  STUFF(STUFF(@x,3 , 0, '/'), 8, 0, '/') InsertString
  ,CHARINDEX('-',LTRIM(RTRIM(@x))) FirstIndexOf
  ,CHARINDEX('-',LTRIM(RTRIM(@x)), (CHARINDEX('-', LTRIM(RTRIM(@x)) )+1)) SecondIndexOf
  ,CHARINDEX('-',@x,CHARINDEX('-',@x, (CHARINDEX('-',@x)+1))+1) ThirdIndexOf
  ,CHARINDEX('-',REVERSE(LTRIM(RTRIM(@x)))) LastIndexOf;
GO

Save Javascript objects in sessionStorage

You can create 2 wrapper methods for saving and retrieving object from session storage.

function saveSession(obj) {
  sessionStorage.setItem("myObj", JSON.stringify(obj));
  return true;
}

function getSession() {
  var obj = {};
  if (typeof sessionStorage.myObj !== "undefined") {
    obj = JSON.parse(sessionStorage.myObj);
  }
  return obj;
}

Use it like this:- Get object, modify some data, and save back.

var obj = getSession();

obj.newProperty = "Prod"

saveSession(obj);

Interface extends another interface but implements its methods

An interface defines behavior. For example, a Vehicle interface might define the move() method.

A Car is a Vehicle, but has additional behavior. For example, the Car interface might define the startEngine() method. Since a Car is also a Vehicle, the Car interface extends the Vehicle interface, and thus defines two methods: move() (inherited) and startEngine().

The Car interface doesn't have any method implementation. If you create a class (Volkswagen) that implements Car, it will have to provide implementations for all the methods of its interface: move() and startEngine().

An interface may not implement any other interface. It can only extend it.

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

How do I make a new line in swift

"\n" is not working everywhere!

For example in email, it adds the exact "\n" into the text instead of a new line if you use it in the custom keyboard like: textDocumentProxy.insertText("\n")

There are another newLine characters available but I can't just simply paste them here (Because they make a new lines).

using this extension:

extension CharacterSet {
    var allCharacters: [Character] {
        var result: [Character] = []
        for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
            for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
                if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
                    result.append(Character(uniChar))
                }
            }
        }
        return result
    }
}

you can access all characters in any CharacterSet. There is a character set called newlines. Use one of them to fulfill your requirements:

let newlines = CharacterSet.newlines.allCharacters
for newLine in newlines {
    print("Hello World \(newLine) This is a new line")
}

Then store the one you tested and worked everywhere and use it anywhere. Note that you can't relay on the index of the character set. It may change.

But most of the times "\n" just works as expected.

How to rename with prefix/suffix?

You could use the rename(1) command:

rename 's/(.*)$/new.$1/' original.filename

Edit: If rename isn't available and you have to rename more than one file, shell scripting can really be short and simple for this. For example, to rename all *.jpg to prefix_*.jpg in the current directory:

for filename in *.jpg; do mv "$filename" "prefix_$filename"; done;

Remove all the elements that occur in one list from another

Performance Comparisons

Comparing the performance of all the answers mentioned here on Python 3.9.1 and Python 2.7.16.

Python 3.9.1

Answers are mentioned in order of performance:

  1. Arkku's set difference using subtraction "-" operation - (91.3 nsec per loop)

    mquadri$ python3 -m timeit -s "l1 = set([1,2,6,8]); l2 = set([2,3,5,8]);" "l1 - l2"
    5000000 loops, best of 5: 91.3 nsec per loop
    
  2. Moinuddin Quadri's using set().difference()- (133 nsec per loop)

    mquadri$ python3 -m timeit -s "l1 = set([1,2,6,8]); l2 = set([2,3,5,8]);" "l1.difference(l2)"
    2000000 loops, best of 5: 133 nsec per loop
    
  3. Moinuddin Quadri's list comprehension with set based lookup- (366 nsec per loop)

     mquadri$ python3 -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "[x for x in l1 if x not in l2]"
     1000000 loops, best of 5: 366 nsec per loop
    
  4. Donut's list comprehension on plain list - (489 nsec per loop)

     mquadri$ python3 -m timeit -s "l1 = [1,2,6,8]; l2 = [2,3,5,8];" "[x for x in l1 if x not in l2]"
     500000 loops, best of 5: 489 nsec per loop
    
  5. Daniel Pryden's generator expression with set based lookup and type-casting to list - (583 nsec per loop) : Explicitly type-casting to list to get the final object as list, as requested by OP. If generator expression is replaced with list comprehension, it'll become same as Moinuddin Quadri's list comprehension with set based lookup.

     mquadri$ mquadri$ python3 -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "list(x for x in l1 if x not in l2)"
     500000 loops, best of 5: 583 nsec per loop
    
  6. Moinuddin Quadri's using filter() and explicitly type-casting to list (need to explicitly type-cast as in Python 3.x, it returns iterator) - (681 nsec per loop)

     mquadri$ python3 -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "list(filter(lambda x: x not in l2, l1))"
     500000 loops, best of 5: 681 nsec per loop
    
  7. Akshay Hazari's using combination of functools.reduce + filter -(3.36 usec per loop) : Explicitly type-casting to list as from Python 3.x it started returned returning iterator. Also we need to import functools to use reduce in Python 3.x

     mquadri$ python3 -m timeit "from functools import reduce; l1 = [1,2,6,8]; l2 = [2,3,5,8];" "list(reduce(lambda x,y : filter(lambda z: z!=y,x) ,l1,l2))"
     100000 loops, best of 5: 3.36 usec per loop
    

Python 2.7.16

Answers are mentioned in order of performance:

  1. Arkku's set difference using subtraction "-" operation - (0.0783 usec per loop)

    mquadri$ python -m timeit -s "l1 = set([1,2,6,8]); l2 = set([2,3,5,8]);" "l1 - l2"
    10000000 loops, best of 3: 0.0783 usec per loop
    
  2. Moinuddin Quadri's using set().difference()- (0.117 usec per loop)

    mquadri$ mquadri$ python -m timeit -s "l1 = set([1,2,6,8]); l2 = set([2,3,5,8]);" "l1.difference(l2)"
    10000000 loops, best of 3: 0.117 usec per loop
    
  3. Moinuddin Quadri's list comprehension with set based lookup- (0.246 usec per loop)

     mquadri$ python -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "[x for x in l1 if x not in l2]"
     1000000 loops, best of 3: 0.246 usec per loop
    
  4. Donut's list comprehension on plain list - (0.372 usec per loop)

     mquadri$ python -m timeit -s "l1 = [1,2,6,8]; l2 = [2,3,5,8];" "[x for x in l1 if x not in l2]"
     1000000 loops, best of 3: 0.372 usec per loop
    
  5. Moinuddin Quadri's using filter() - (0.593 usec per loop)

     mquadri$ python -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "filter(lambda x: x not in l2, l1)"
     1000000 loops, best of 3: 0.593 usec per loop
    
  6. Daniel Pryden's generator expression with set based lookup and type-casting to list - (0.964 per loop) : Explicitly type-casting to list to get the final object as list, as requested by OP. If generator expression is replaced with list comprehension, it'll become same as Moinuddin Quadri's list comprehension with set based lookup.

     mquadri$ python -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "list(x for x in l1 if x not in l2)"
     1000000 loops, best of 3: 0.964 usec per loop
    
  7. Akshay Hazari's using combination of functools.reduce + filter -(2.78 usec per loop)

     mquadri$ python -m timeit "l1 = [1,2,6,8]; l2 = [2,3,5,8];" "reduce(lambda x,y : filter(lambda z: z!=y,x) ,l1,l2)"
     100000 loops, best of 3: 2.78 usec per loop
    

How to reload a div without reloading the entire page?

Use this.

$('#mydiv').load(document.URL +  ' #mydiv');

Note, include a space before the hastag.

How to know which version of Symfony I have?

Maybe the anwswers here are obsolete... in any case, for me running Symfony 4, it is easy Just type symfony -V from the command line.

enter image description here

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

Determine whether an array contains a value

function setFound(){   
 var l = arr.length, textBox1 = document.getElementById("text1");
    for(var i=0; i<l;i++)
    {
     if(arr[i]==searchele){
      textBox1 .value = "Found";
      return;
     }
    }
    textBox1 .value = "Not Found";
return;
}

This program checks whether the given element is found or not. Id text1 represents id of textbox and searchele represents element to be searched (got fron user); if you want index, use i value

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

The "what would you like it to be?" sort

  1. Note the system time.
  2. Sort using Quicksort (or anything else reasonably sensible), omitting the very last swap.
  3. Note the system time.
  4. Calculate the required time. Extended precision arithmetic is a requirement.
  5. Wait the required time.
  6. Perform the last swap.

Not only can it implement any conceivable O(x) value short of infinity, the time taken is provably correct (if you can wait that long).

How to convert FormData (HTML5 object) to JSON

In 2019, this kind of task became super-easy.

JSON.stringify(Object.fromEntries(formData));

Object.fromEntries: Supported in Chrome 73+, Firefox 63+, Safari 12.1

Android Studio doesn't start, fails saying components not installed

One possible solution is to open Android SDK Manager from

C:\Users\%user%\AppData\Local\Android\sdk

Check Android SDK build tool 21.1.1 download and install. Restart Android Studio

How to make a stable two column layout in HTML/CSS

Piece of cake.

Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.

No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.

Voila. Grids FTW.

CMake does not find Visual C++ compiler

I had this issue with CMake GUI and the VS 21019 Community Edition. I think I may have installed CMake before Visual Studio - certainly after I updated CMake 3.15.2 to 3.15.3 the problem went away.

Passive Link in Angular 2 - <a href=""> equivalent

A really simple solution is not to use an A tag - use a span instead:

<span class='link' (click)="doSomething()">Click here</span>

span.link {
  color: blue;
  cursor: pointer;
  text-decoration: underline;
}

Install python 2.6 in CentOS

When I've run into similar situations, I generally avoid the package manager, especially if it would be embarrassing to break something, i.e. a production server. Instead, I would go to Activestate and download their binary package:

https://www.activestate.com/activepython/downloads/

This is installed by running a script which places everything into a folder and does not touch any system files. In fact, you don't even need root permissions to set it up. Then I change the name of the binary to something like apy26, add that folder to the end of the PATH and start coding. If you install packages with apy26 setup.py installor if you use virtualenv and easyinstall, then you have just as flexible a python environment as you need without touching the system standard python.

Edits... Recently I've done some work to build a portable Python binary for Linux that should run on any distro with no external dependencies. This means that any binary shared libraries needed by the portable Python module are part of the build, included in the tarball and installed in Python's private directory structure. This way you can install Python for your application without interfering with the system installed Python.

My github site has a build script which has been thoroughly tested on Ubuntu Lucid 10.04 LTS both 32 and 64 bit installs. I've also built it on Debian Etch but that was a while ago and I can't guarantee that I haven't changed something. The easiest way to do this is you just put your choice of Ubuntu Lucid in a virtual machine, checkout the script with git clone git://github.com/wavetossed/pybuild.git and then run the script.

Once you have it built, use the tarball on any recent Linux distro. There is one little wrinkle with moving it to a directory other than /data1/packages/python272 which is that you have to run the included patchelf to set the interpreter path BEFORE you move the directory. This affects any binaries in /data1/packages/python272/bin

All of this is based on building with RUNPATH and copying the dependent shared libraries. Even though the script is in several files, it is effectively one long shell script arranged in the style of /etc/rc.d directories.

Delete specific values from column with where condition?

You don't want to delete if you're wanting to leave the row itself intact. You want to update the row, and change the column value.

The general form for this would be an UPDATE statement:

UPDATE <table name>
SET
    ColumnA = <NULL, or '', or whatever else is suitable for the new value for the column>
WHERE
    ColumnA = <bad value> /* or any other search conditions */

sqlite copy data from one table to another

I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:

create table destination_old as select * from destination;

drop table destination;

create table destination as select
d.*, s.country
from destination_old d left join source s
on d.id=s.id;

It's safe because you have a copy of destination before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.

Using the pattern above you end up with two country fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old and perhaps using coalesce to retrieve the values from destination_old if the country field in source is null. So for example:

create table destination as select
d.field1, d.field2,...,coalesce(s.country,d.country) country
from destination_old d left join source s
on d.id=s.id;

SVN undo delete before commit

1) do

svn revert . --recursive

2) parse output for errors like

"Failed to revert 'dir1/dir2' -- try updating instead."

3) call svn up for each of error directories:

svn up dir1/dir2

How to apply filters to *ngFor?

I know its an old question, however, I thought it might be helpful to offer another solution.

equivalent of AngularJS of this

<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>

in Angular 2+ you cant use *ngFor and *ngIf on a same element, so it will be following:

<div *ngFor="let item of itemsList">
     <div *ngIf="conditon(item)">
     </div>
</div>

and if you can not use as internal container use ng-container instead. ng-container is useful when you want to conditionally append a group of elements (ie using *ngIf="foo") in your application but don't want to wrap them with another element.

What is the optimal way to compare dates in Microsoft SQL server?

Here is an example:

I've an Order table with a DateTime field called OrderDate. I want to retrieve all orders where the order date is equals to 01/01/2006. there are next ways to do it:

1) WHERE DateDiff(dd, OrderDate, '01/01/2006') = 0
2) WHERE Convert(varchar(20), OrderDate, 101) = '01/01/2006'
3) WHERE Year(OrderDate) = 2006 AND Month(OrderDate) = 1 and Day(OrderDate)=1
4) WHERE OrderDate LIKE '01/01/2006%'
5) WHERE OrderDate >= '01/01/2006'  AND OrderDate < '01/02/2006'

Is found here

check output from CalledProcessError

This will return true only if host responds to ping. Works on windows and linux

def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    NB on windows ping returns true for success and host unreachable
    """
    param = '-n' if platform.system().lower()=='windows' else '-c'
    result = False
    try:
        out = subprocess.check_output(['ping', param, '1', host])
        #ping exit code 0
        if 'Reply from {}'.format(host) in str(out):
            result = True          
    except  subprocess.CalledProcessError:
        #ping exit code not 0
            result = False
    #print(str(out))
    return result

LINQ-to-SQL vs stored procedures?

All these answers leaning towards LINQ are mainly talking about EASE of DEVELOPMENT which is more or less connected to poor quality of coding or laziness in coding. I am like that only.

Some advantages or Linq, I read here as , easy to test, easy to debug etc, but these are no where connected to Final output or end user. This is always going cause the trouble the end user on performance. Whats the point loading many things in memory and then applying filters on in using LINQ?

Again TypeSafety, is caution that "we are careful to avoid wrong typecasting" which again poor quality we are trying to improve by using linq. Even in that case, if anything in database changes, e.g. size of String column, then linq needs to be re-compiled and would not be typesafe without that .. I tried.

Although, we found is good, sweet, interesting etc while working with LINQ, it has shear disadvantage of making developer lazy :) and it is proved 1000 times that it is bad (may be worst) on performance compared to Stored Procs.

Stop being lazy. I am trying hard. :)

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

Set the "long" type of id instead of java.lang.Integer. And add getters and setters to your fields.

Why does the Google Play store say my Android app is incompatible with my own device?

I found an additional way in which this problem occurs:
My LG phone's original OS was Froyo (Android 2.2) and was updated to ICS (Android 4.0.4). But the Google Play Developers' Console shows that it detects my phone as a Froyo device. (Google Play did not allow the app to be downloaded because of the false 'incompatibility', but it somehow still detects the installation.)

The phone's settings, in 'software', shows ICS V4.0.4. It seems that the Google Play server info for the phone is not updated to reflect the ICS update on the device. The app manifest minSDK is set to Honeycomb (3.0), so of course Google Play filters out the app.

Of addition interest:
The app uses In-app Billing V3. The first time through IabHelper allows the app to make purchases through the Google Play service. But after the purchase is made, the purchase is NOT put in the inventory and IabHelper reports no items are owned. Debug messages show a 'purchase failed' result from the purchase even though the Google Play window announces "purchase successful."

filename.whl is not supported wheel on this platform

For my case with dlib installation into my python [Python 3.6.9], I have found that changing WHL file name from dlib-19.8.1-cp36-cp36m-win_amd64.whl to dlib-19.8.1-cp36-none-any.whl works for me.

Here is the way I run pip install to install dlib:

pip3 install dlib-19.8.1-cp36-none-any.whl

However, I still wonder whether there are any alternatives to install of WHL file by pip command without changing the name.

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

If you have a WPF or Silverlight application, make sure that App.xaml has "ApplicationDefinition" as the BuildAction on the File Properties.

Inverse of a matrix using numpy

Another way to do this is to use the numpy matrix class (rather than a numpy array) and the I attribute. For example:

>>> m = np.matrix([[2,3],[4,5]])
>>> m.I
matrix([[-2.5,  1.5],
       [ 2. , -1. ]])

ReferenceError: $ is not defined

Add jQuery library before your script which uses $ or jQuery so that $ can be identified in scripts.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

What HTTP traffic monitor would you recommend for Windows?

Wireshark if you want to see everything going on in the network.

Fiddler if you want to just monitor HTTP/s traffic.

Live HTTP Headers if you're in Firefox and want a quick plugin just to see the headers.

Also FireBug can get you that information too and provides a nice interface when your working on a single page during development. I've used it to monitor AJAX transactions.

How do I write a batch script that copies one directory to another, replaces old files?

Try this:

xcopy %1 %2 /y /e

The %1 and %2 are the source and destination arguments you pass to the batch file. i.e. C:\MyBatchFile.bat C:\CopyMe D:\ToHere

What is /var/www/html?

In the most shared hosts you can't set it.

On a VPS or dedicated server, you can set it, but everything has its price.

On shared hosts, in general you receive a Linux account, something such as /home/(your username)/, and the equivalent of /var/www/html turns to /home/(your username)/public_html/ (or something similar, such as /home/(your username)/www)

If you're accessing your account via FTP, you automatically has accessing the your */home/(your username)/ folder, just find the www or public_html and put your site in it.

If you're using absolute path in the code, bad news, you need to refactor it to use relative paths in the code, at least in a shared host.

Google Play app description formatting

Currently (July 2015), HTML escape sequences (&bull; &#8226;) do not work in browser version of Play Store, they're displayed as text. Though, Play Store app handles them as expected.

So, if you're after the unicode bullet point in your app/update description [that's what's got you here, most likely], just copy-paste the bullet character

PS You can also use unicode input combo to get the character

Linux: CtrlShiftu 2022 Enter or Space

Mac: Hold ? 2022 release ?

Windows: Hold Alt 2022 release Alt

Mac and Windows require some setup, read on Wikipedia

PPS If you're feeling creative, here's a good link with more copypastable symbols, but don't go too crazy, nobody likes clutter in what they read.

django - get() returned more than one topic

get() returned more than one topic -- it returned 2!

The above error indicatess that you have more than one record in the DB related to the specific parameter you passed while querying using get() such as

Model.objects.get(field_name=some_param)

To avoid this kind of error in the future, you always need to do query as per your schema design. In your case you designed a table with a many-to-many relationship so obviously there will be multiple records for that field and that is the reason you are getting the above error.

So instead of using get() you should use filter() which will return multiple records. Such as

Model.objects.filter(field_name=some_param)

Please read about how to make queries in django here.

pandas loc vs. iloc vs. at vs. iat?

df = pd.DataFrame({'A':['a', 'b', 'c'], 'B':[54, 67, 89]}, index=[100, 200, 300])

df

                        A   B
                100     a   54
                200     b   67
                300     c   89
In [19]:    
df.loc[100]

Out[19]:
A     a
B    54
Name: 100, dtype: object

In [20]:    
df.iloc[0]

Out[20]:
A     a
B    54
Name: 100, dtype: object

In [24]:    
df2 = df.set_index([df.index,'A'])
df2

Out[24]:
        B
    A   
100 a   54
200 b   67
300 c   89

In [25]:    
df2.ix[100, 'a']

Out[25]:    
B    54
Name: (100, a), dtype: int64

Placeholder Mixin SCSS/CSS

You're looking for the @content directive:

@mixin placeholder {
  ::-webkit-input-placeholder {@content}
  :-moz-placeholder           {@content}
  ::-moz-placeholder          {@content}
  :-ms-input-placeholder      {@content}  
}

@include placeholder {
    font-style:italic;
    color: white;
    font-weight:100;
}

SASS Reference has more information, which can be found here: http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#mixin-content


As of Sass 3.4, this mixin can be written like so to work both nested and unnested:

@mixin optional-at-root($sel) {
  @at-root #{if(not &, $sel, selector-append(&, $sel))} {
    @content;
  }
}

@mixin placeholder {
  @include optional-at-root('::-webkit-input-placeholder') {
    @content;
  }

  @include optional-at-root(':-moz-placeholder') {
    @content;
  }

  @include optional-at-root('::-moz-placeholder') {
    @content;
  }

  @include optional-at-root(':-ms-input-placeholder') {
    @content;
  }
}

Usage:

.foo {
  @include placeholder {
    color: green;
  }
}

@include placeholder {
  color: red;
}

Output:

.foo::-webkit-input-placeholder {
  color: green;
}
.foo:-moz-placeholder {
  color: green;
}
.foo::-moz-placeholder {
  color: green;
}
.foo:-ms-input-placeholder {
  color: green;
}

::-webkit-input-placeholder {
  color: red;
}
:-moz-placeholder {
  color: red;
}
::-moz-placeholder {
  color: red;
}
:-ms-input-placeholder {
  color: red;
}

How to Free Inode Usage?

It's quite easy for a disk to have a large number of inodes used even if the disk is not very full.

An inode is allocated to a file so, if you have gazillions of files, all 1 byte each, you'll run out of inodes long before you run out of disk.

It's also possible that deleting files will not reduce the inode count if the files have multiple hard links. As I said, inodes belong to the file, not the directory entry. If a file has two directory entries linked to it, deleting one will not free the inode.

Additionally, you can delete a directory entry but, if a running process still has the file open, the inode won't be freed.

My initial advice would be to delete all the files you can, then reboot the box to ensure no processes are left holding the files open.

If you do that and you still have a problem, let us know.

By the way, if you're looking for the directories that contain lots of files, this script may help:

#!/bin/bash
# count_em - count files in all subdirectories under current directory.
echo 'echo $(ls -a "$1" | wc -l) $1' >/tmp/count_em_$$
chmod 700 /tmp/count_em_$$
find . -mount -type d -print0 | xargs -0 -n1 /tmp/count_em_$$ | sort -n
rm -f /tmp/count_em_$$

How can I determine browser window size on server side C#

Here how I solved it using Cookies:

First of all, inside the website main script:

var browserWindowSize = getCookie("_browserWindowSize");
var newSize = $(window).width() + "," + $(window).height();
var reloadForCookieRefresh = false;

if (browserWindowSize == undefined || browserWindowSize == null || newSize != browserWindowSize) {
    setCookie("_browserWindowSize", newSize, 30);
    reloadForCookieRefresh = true;
}

if (reloadForCookieRefresh)
    window.location.reload();

function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

And inside MVC action filter:

public class SetCurrentRequestDataFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // currentRequestService is registered per web request using IoC
        var currentRequestService = iocResolver.Resolve<ICurrentRequestService>();

        if (filterContext.HttpContext.Request.Cookies.AllKeys.Contains("_browserWindowSize"))
        {
            var browserWindowSize = filterContext.HttpContext.Request.Cookies.Get("_browserWindowSize").Value.Split(',');
            currentRequestService.browserWindowWidth = int.Parse(browserWindowSize[0]);
            currentRequestService.browserWindowHeight = int.Parse(browserWindowSize[1]);
        }

    }
}

Change arrow colors in Bootstraps carousel

To customize the colors for the carousel controls, captions, and indicators using Sass you can include these variables

    $carousel-control-color: 
    $carousel-caption-color: 
    $carousel-indicator-active-bg: 

How to set the JSTL variable value in javascript?

<script ...
  function(){
   var someJsVar = "<c:out value='${someJstLVarFromBackend}'/>";

  }
</script>

This works even if you dont have a hidden/non-hidden input field set somewhere in the jsp.

How can I select rows with most recent timestamp for each key value?

For the sake of completeness, here's another possible solution:

SELECT sensorID,timestamp,sensorField1,sensorField2 
FROM sensorTable s1
WHERE timestamp = (SELECT MAX(timestamp) FROM sensorTable s2 WHERE s1.sensorID = s2.sensorID)
ORDER BY sensorID, timestamp;

Pretty self-explaining I think, but here's more info if you wish, as well as other examples. It's from the MySQL manual, but above query works with every RDBMS (implementing the sql'92 standard).

How do I prevent a parent's onclick event from firing when a child anchor is clicked?

e.stopPropagation() is a correct solution, but in case you don't want to attach any event handler to your inner anchor, you can simply attach this handler to your outer div:

e => { e.target === e.currentTarget && window.location = URL; }

MSOnline can't be imported on PowerShell (Connect-MsolService error)

Connects to both Office 365 and Exchange Online in one easy to use script.

REMINDER: You must have the following installed in order to manage Office 365 via PowerShell.

Microsoft Online Services Sign-in Assistant: http://go.microsoft.com/fwlink/?LinkId=286152

Azure AD Module for Windows PowerShell 32 bit - http://go.microsoft.com/fwlink/p/?linkid=236298 64 bit - http://go.microsoft.com/fwlink/p/?linkid=236297

MORE INFORMATION FOUND HERE: http://technet.microsoft.com/en-us/library/hh974317.aspx

Difference between MEAN.js and MEAN.io

The Starter Trade-offs sheet of my comparison spreadsheet has comprehensive one-on-one comparisons between each generator. So no more need to distortedly cherry-pick great things to say about your favorite.

Here is the one between generator-angular-fullstack and MEAN.js. The percentages are values for each benefit based on my personal weightings, where a perfect generator would be 100%

generator- angular- fullstack offers 8% that MEANJS.org doesn't

  • 1.9% Client-side end-to-end tests
  • 0.6% factory
  • 0.5% provider
  • 0.4% SASS
  • 0.4% LESS
  • 0.4% Compass
  • 0.4% decorator
  • 0.4% Endpoint subgenerator
  • 0.4% Comments
  • 0.3% FontAwesome
  • 0.3% Run server in debug mode
  • 0.3% Save generator answers to a file
  • 0.2% constant
  • 0.2% Development build script: ...... replace 3rd party deps with CDN versions
  • 0.2% Authentication - Cookie
  • 0.2% Authentication - JSON Web Token (JWT)
  • 0.2% Server-side logging
  • 0.1% Development build script: run tasks in parallel to speed it up
  • 0.1% Development build script: Renames asset files to prevent browser caching
  • 0.1% Development build script: run end to end tests
  • 0.1% Production build script: safe pre-minification
  • 0.1% Production build script: add CSS vendor prefixes
  • 0.1% Heroku deployment automation
  • 0.1% value
  • 0.1% Jade
  • 0.1% Coffeescript
  • 0.1% Serverside authenticated route restriction
  • 0.1% SASS version of Twitter Bootstrap
  • 0.1% Production build script: compress images
  • 0.1% OpenShift deployment automation

MeanJS.org. offers 9% that generator-angular-fullstack doesn't

  • 3.7% Dedicated/searchable user group: response time mostly under a day
  • 0.4% Generate routes
  • 0.4% Authentication - Oauth
  • 0.4% config
  • 0.4% i18n, localization
  • 0.4% Input application profile
  • 0.3% FEATURE (a.k.a. module, entity, crud-mock)
  • 0.3% Menus system
  • 0.3% Options for making subcomponents
  • 0.3% test - client side
  • 0.3% Javascript performance thing
  • 0.3% Production build script: make static pages for SEO
  • 0.2% Quick install?
  • 0.2% Dedicated/searchable user group
  • 0.1% Development build script: reload build file upon change
  • 0.1% Development build script: coffee files compiled to JS
  • 0.1% controller - server side
  • 0.1% model - server side
  • 0.1% route - server side
  • 0.1% test - server side
  • 0.1% Swig
  • 0.1% Safe from IP Spoofing
  • 0.1% Production build script: uglification
  • 0.0% Approach to views: URLs start with "#!"
  • 0.0% Approach to frontend services and ajax calls: uses $resource

Here is the one between MEAN.io and MEAN.js in a more readable format

_x000D_
_x000D_
<table border="1" cellpadding="10"><tbody><tr><td valign="top" width="33%"><br><br><h1>MeanJS.org. provides these benefits that MEAN.io. doesn't</h1><br><br><b>Help</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions, using github issues<br>&nbsp;&nbsp;&nbsp;&nbsp;* There's a book about it<br><b>File Organization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Basic sourcecode organization, module(-&gt;submodule)-&gt;side<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold directives<br><b>Code Modularization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS modules, Only one module definition per file<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS modules, Don’t alter a module other than where it is defined<br><b>Model</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Object-relational mapping<br>&nbsp;&nbsp;&nbsp;&nbsp;* Server-side validation, server-side example<br>&nbsp;&nbsp;&nbsp;&nbsp;* Client side validation, using Angular 1.3<br><b>View</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS views, Directives start with "data-"<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to data readiness, Use ng-init<br><b>Control</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, URLs start with '#!'<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, Use query parameters to store route state<br><b>Support for things</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Languages, LESS<br>&nbsp;&nbsp;&nbsp;&nbsp;* Languages, SASS<br><b>Syntax, language and coding</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* JavaScript 5 best practices, Don't use "new"<br><b>Testing</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Testing, using Mocha<br>&nbsp;&nbsp;&nbsp;&nbsp;* End-to-end tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* End-to-end tests, using Protractor<br>&nbsp;&nbsp;&nbsp;&nbsp;* Continuous integration (CI), using Travis<br><b>Development and debugging</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Command line interface (CLI), using Yeoman<br><b>Build</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build configurations file(s)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation, using Azure<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation, using Digital Ocean, screencast of it<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation, using Heroku, screencast of it<br><b>Code Generation</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Input application profile<br>&nbsp;&nbsp;&nbsp;&nbsp;* Quick install?<br>&nbsp;&nbsp;&nbsp;&nbsp;* Options for making subcomponents<br>&nbsp;&nbsp;&nbsp;&nbsp;* config generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* controller (client side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* directive generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* filter generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* route (client side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* service (client side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* test - client side<br>&nbsp;&nbsp;&nbsp;&nbsp;* view or view partial generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* controller (server side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* model (server side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* route (server side) generator<br>&nbsp;&nbsp;&nbsp;&nbsp;* test (server side) generator<br><b>Implemented Functionality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Account Management, Forgotten Password with Resetting<br>&nbsp;&nbsp;&nbsp;&nbsp;* Chat<br>&nbsp;&nbsp;&nbsp;&nbsp;* CSV processing<br>&nbsp;&nbsp;&nbsp;&nbsp;* E-mail sending system<br>&nbsp;&nbsp;&nbsp;&nbsp;* E-mail sending system, using Nodemailer<br>&nbsp;&nbsp;&nbsp;&nbsp;* E-mail sending system, using its own e-mail implementation<br>&nbsp;&nbsp;&nbsp;&nbsp;* Menus system, state-based<br>&nbsp;&nbsp;&nbsp;&nbsp;* Paypal integration<br>&nbsp;&nbsp;&nbsp;&nbsp;* Responsive design<br>&nbsp;&nbsp;&nbsp;&nbsp;* Social connections management page<br><b>Performance</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Creates a favicon<br><b>Security</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Safe from IP Spoofing<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authorization, Access Contol List (ACL)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, Cookie<br>&nbsp;&nbsp;&nbsp;&nbsp;* Websocket and RESTful http share security policies<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. provides these benefits that MeanJS.org. doesn't</h1><br><br><b>Quality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Sponsoring company<br><b>Help</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Docs with flatdoc<br><b>Code Modularization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Share code between projects<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module manager<br><b>View</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to data readiness, Use state.resolve()<br><b>Control</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend code loading, Use AMD with Require.js<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend code loading, using wiredep<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to error handling, Server-side logging<br><b>Client/Server Communication</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Centralized event handling<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to XHR calls, using $http and $q<br><b>Syntax, language and coding</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* JavaScript 5 best practices, Wrap code in an IIFE (SEAF, SIAF)<br><b>Development and debugging</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* API introspection report and testing interface, using Swagger<br>&nbsp;&nbsp;&nbsp;&nbsp;* Command line interface (CLI), using Independent command line interface<br><b>Build</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, add IIFEs (SEAF, SIAF) to executable copies of code<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation<br>&nbsp;&nbsp;&nbsp;&nbsp;* Deployment automation, using Heroku<br><b>Code Generation</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Scaffolding undo&nbsp;&nbsp;&nbsp;&nbsp;(mean package -d &lt;name&gt;)<br>&nbsp;&nbsp;&nbsp;&nbsp;* FEATURE (a.k.a. module, entity) generator, Menu items added for new features<br><b>Implemented Functionality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Admin page for users and roles<br>&nbsp;&nbsp;&nbsp;&nbsp;* Content Management System&nbsp;&nbsp;&nbsp;&nbsp;(Use special data-bound directives in your templates.<br>Switch to edit mode and you can edit the values right where you see them)<br>&nbsp;&nbsp;&nbsp;&nbsp;* File Upload<br>&nbsp;&nbsp;&nbsp;&nbsp;* i18n, localization<br>&nbsp;&nbsp;&nbsp;&nbsp;* Menus system, submenus<br>&nbsp;&nbsp;&nbsp;&nbsp;* Search<br>&nbsp;&nbsp;&nbsp;&nbsp;* Search, actually works with backend API<br>&nbsp;&nbsp;&nbsp;&nbsp;* Search, using Elastic Search<br>&nbsp;&nbsp;&nbsp;&nbsp;* Styles, using Bootstrap, using UI Bootstrap AngularJS directives<br>&nbsp;&nbsp;&nbsp;&nbsp;* Text (WYSIWYG) Editor<br>&nbsp;&nbsp;&nbsp;&nbsp;* Text (WYSIWYG) Editor, using medium-editor<br><b>Performance</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Instrumentation, server-side<br><b>Security</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Serverside authenticated route restriction<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, using Oauth, Link multiple Oauth strategies to one account<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, JSON Web Token (JWT)<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. and MeanJS.org. both provide these benefits</h1><br><br><b>Quality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Version Control, using git<br><b>Platforms</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Client-side JS Framework, using AngularJS<br>&nbsp;&nbsp;&nbsp;&nbsp;* Frontend Server/ Framework, using Node.JS<br>&nbsp;&nbsp;&nbsp;&nbsp;* Frontend Server/ Framework, using Node.JS, using Express<br>&nbsp;&nbsp;&nbsp;&nbsp;* API Server/ Framework, using NodeJS<br>&nbsp;&nbsp;&nbsp;&nbsp;* API Server/ Framework, using NodeJS, using Express<br><b>Help</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions, using Google Groups<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions, using Facebook<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated/searchable user group for questions, response time mostly under a day<br>&nbsp;&nbsp;&nbsp;&nbsp;* Example application<br>&nbsp;&nbsp;&nbsp;&nbsp;* Tutorial screencast in English<br>&nbsp;&nbsp;&nbsp;&nbsp;* Tutorial screencast in English, using Youtube<br>&nbsp;&nbsp;&nbsp;&nbsp;* Dedicated chatroom<br><b>File Organization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Basic sourcecode organization, module(-&gt;submodule)-&gt;side, with type subfolders<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold controllers<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold services<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold templates<br>&nbsp;&nbsp;&nbsp;&nbsp;* Module directories hold unit tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Separate route configuration files for each module<br><b>Code Modularization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Modularized Functionality<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS modules, No global 'app' module variable<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to AngularJS modules, No global 'app' module variable without an IIFE<br><b>Model</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Setup of persistent storage<br>&nbsp;&nbsp;&nbsp;&nbsp;* Setup of persistent storage, using NoSQL db<br>&nbsp;&nbsp;&nbsp;&nbsp;* Setup of persistent storage, using NoSQL db, using MongoDB<br><b>View</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* No XHR calls in controllers<br>&nbsp;&nbsp;&nbsp;&nbsp;* Templates, using Angular directives<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to data readiness, prevents Flash of Unstyled/compiled Content (FOUC)<br><b>Control</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, example of it<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, State-based routing<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, State-based routing, using ui-router<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend routing or state changing, HTML5 Mode<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to frontend code loading, using angular.bootstrap()<br><b>Client/Server Communication</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Serve status codes only as responses<br>&nbsp;&nbsp;&nbsp;&nbsp;* Accept nested, JSON parameters<br>&nbsp;&nbsp;&nbsp;&nbsp;* Add timer header to requests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Support for signed and encrypted cookies<br>&nbsp;&nbsp;&nbsp;&nbsp;* Serve URLs based on the route definitions<br>&nbsp;&nbsp;&nbsp;&nbsp;* Can serve headers only<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to XHR calls, using JSON<br>&nbsp;&nbsp;&nbsp;&nbsp;* Approach to XHR calls, using $resource (angular-resource)<br><b>Support for things</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Languages, JavaScript (server side)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Languages, Swig<br><b>Syntax, language and coding</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* JavaScript 5 best practices, Use 'use strict'<br><b>Tool Configuration/customization</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Separate runtime configuration profiles<br><b>Testing</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Testing, using Jasmine<br>&nbsp;&nbsp;&nbsp;&nbsp;* Testing, using Karma<br>&nbsp;&nbsp;&nbsp;&nbsp;* Client-side unit tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Continuous integration (CI)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Automated device testing, using Live Reload<br>&nbsp;&nbsp;&nbsp;&nbsp;* Server-side integration &amp; unit tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Server-side integration &amp; unit tests, using Mocha<br><b>Development and debugging</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Command line interface (CLI)<br><b>Build</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build-time Dependency Management, using npm<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build-time Dependency Management, using bower<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build tool / Task runner, using Grunt<br>&nbsp;&nbsp;&nbsp;&nbsp;* Build tool / Task runner, using gulp<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, script<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, reload build script file upon change<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, copy assets to build or dist or target folder<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, html page processing<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, html page processing, inject references by searching directories<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, html page processing, inject references by searching directories, injects js references<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, html page processing, inject references by searching directories, injects css references<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, LESS/SASS/etc files are linted, compiled<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, JavaScript style checking<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, JavaScript style checking, using jshint or jslint<br>&nbsp;&nbsp;&nbsp;&nbsp;* Development build, run unit tests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, script<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, concatenation (aggregation, globbing, bundling)&nbsp;&nbsp;&nbsp;&nbsp;(If you add debug:true to your config/env/development.js the will not be <br>uglified)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, minification<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, safe pre-minification, using ng-annotate<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, uglification<br>&nbsp;&nbsp;&nbsp;&nbsp;* Production build, make static pages for SEO<br><b>Code Generation</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* FEATURE (a.k.a. module, entity) generator&nbsp;&nbsp;&nbsp;&nbsp;(README.md<br>feature css<br>routes<br>controller<br>view<br>additional menu item)<br><b>Implemented Functionality</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* 404 Page<br>&nbsp;&nbsp;&nbsp;&nbsp;* 500 Page<br>&nbsp;&nbsp;&nbsp;&nbsp;* Account Management<br>&nbsp;&nbsp;&nbsp;&nbsp;* Account Management, register/login/logout<br>&nbsp;&nbsp;&nbsp;&nbsp;* Account Management, is password manager friendly<br>&nbsp;&nbsp;&nbsp;&nbsp;* Front-end CRUD<br>&nbsp;&nbsp;&nbsp;&nbsp;* Full-stack CRUD<br>&nbsp;&nbsp;&nbsp;&nbsp;* Full-stack CRUD, with Read<br>&nbsp;&nbsp;&nbsp;&nbsp;* Full-stack CRUD, with Create, Update and Delete<br>&nbsp;&nbsp;&nbsp;&nbsp;* Google Analytics<br>&nbsp;&nbsp;&nbsp;&nbsp;* Menus system<br>&nbsp;&nbsp;&nbsp;&nbsp;* Realtime data sync<br>&nbsp;&nbsp;&nbsp;&nbsp;* Realtime data sync, using socket.io<br>&nbsp;&nbsp;&nbsp;&nbsp;* Styles, using Bootstrap<br><b>Performance</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* Javascript performance thing<br>&nbsp;&nbsp;&nbsp;&nbsp;* Javascript performance thing, using lodash<br>&nbsp;&nbsp;&nbsp;&nbsp;* One event-loop thread handles all requests<br>&nbsp;&nbsp;&nbsp;&nbsp;* Configurable response caching&nbsp;&nbsp;&nbsp;&nbsp;(Express plugin<br><b>https</b>://www.npmjs.org/package/apicache)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Clustered HTTP sessions<br><b>Security</b>:<br>&nbsp;&nbsp;&nbsp;&nbsp;* JavaScript obfuscation<br>&nbsp;&nbsp;&nbsp;&nbsp;* https<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, using Oauth<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, Basic&nbsp;&nbsp;&nbsp;&nbsp;(With Passport or others)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, Digest&nbsp;&nbsp;&nbsp;&nbsp;(With Passport or others)<br>&nbsp;&nbsp;&nbsp;&nbsp;* Authentication, Token&nbsp;&nbsp;&nbsp;&nbsp;(With Passport or others)<br></td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

How to go from Blob to ArrayBuffer

You can use FileReader to read the Blob as an ArrayBuffer.

Here's a short example:

var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
    arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

Here's a longer example:

// ArrayBuffer -> Blob
var uint8Array  = new Uint8Array([1, 2, 3]);
var arrayBuffer = uint8Array.buffer;
var blob        = new Blob([arrayBuffer]);

// Blob -> ArrayBuffer
var uint8ArrayNew  = null;
var arrayBufferNew = null;
var fileReader     = new FileReader();
fileReader.onload  = function(event) {
    arrayBufferNew = event.target.result;
    uint8ArrayNew  = new Uint8Array(arrayBufferNew);

    // warn if read values are not the same as the original values
    // arrayEqual from: http://stackoverflow.com/questions/3115982/how-to-check-javascript-array-equals
    function arrayEqual(a, b) { return !(a<b || b<a); };
    if (arrayBufferNew.byteLength !== arrayBuffer.byteLength) // should be 3
        console.warn("ArrayBuffer byteLength does not match");
    if (arrayEqual(uint8ArrayNew, uint8Array) !== true) // should be [1,2,3]
        console.warn("Uint8Array does not match");
};
fileReader.readAsArrayBuffer(blob);
fileReader.result; // also accessible this way once the blob has been read

This was tested out in the console of Chrome 27—69, Firefox 20—60, and Safari 6—11.

Here's also a live demonstration which you can play with: https://jsfiddle.net/potatosalad/FbaM6/

Update 2018-06-23: Thanks to Klaus Klein for the tip about event.target.result versus this.result

Reference:

How to remove duplicate values from a multi-dimensional array in PHP

Another way. Will preserve keys as well.

function array_unique_multidimensional($input)
{
    $serialized = array_map('serialize', $input);
    $unique = array_unique($serialized);
    return array_intersect_key($input, $unique);
}

VBA procedure to import csv file into access

Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work

Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant

    sFileIn = "z:\docs\FileName.csv"
    sFileOut = "z:\docs\FileOut.csv"

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading

    sTmp = tsIn.ReadAll

    Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
    aryFile = Split(sTmp, vbCrLf)

    ''Start at line 3 and end at last line -1
    For i = 3 To UBound(aryFile) - 1
        tsOut.WriteLine aryFile(i)
    Next

    tsOut.Close

    DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub

Edit re various comments

It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.

About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003

Introduction to importing and exporting data -- Applies to: Microsoft Access 2010

Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.

jQuery .val() vs .attr("value")

There is a big difference between an objects properties and an objects attributes

See this questions (and its answers) for some of the differences: .prop() vs .attr()

The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.

How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

Well, it will take you forever. There is so much to learn about programming that 10 years are not enough.

http://norvig.com/21-days.html

Don't get me wrong, you will learn the basics quickly enough, but to become good at it will take much longer.

You should focus on an area and try to make some examples, if you choose web development, start with an hello world web page, then add some code to it. Learn about postbacks, viewstate and Sessions. Try to master ifs, cycles and functions, you really have a lot to cover, it's not easy to say "this is the best way to learn".

I guess in the end you will learn on a need to do basis.

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

How to print color in console using System.out.println?

Here are a list of colors in a Java class with public static fields

Usage

System.out.println(ConsoleColors.RED + "RED COLORED" +
ConsoleColors.RESET + " NORMAL");


Note Don't forget to use the RESET after printing as the effect will remain if it's not cleared


public class ConsoleColors {
    // Reset
    public static final String RESET = "\033[0m";  // Text Reset

    // Regular Colors
    public static final String BLACK = "\033[0;30m";   // BLACK
    public static final String RED = "\033[0;31m";     // RED
    public static final String GREEN = "\033[0;32m";   // GREEN
    public static final String YELLOW = "\033[0;33m";  // YELLOW
    public static final String BLUE = "\033[0;34m";    // BLUE
    public static final String PURPLE = "\033[0;35m";  // PURPLE
    public static final String CYAN = "\033[0;36m";    // CYAN
    public static final String WHITE = "\033[0;37m";   // WHITE

    // Bold
    public static final String BLACK_BOLD = "\033[1;30m";  // BLACK
    public static final String RED_BOLD = "\033[1;31m";    // RED
    public static final String GREEN_BOLD = "\033[1;32m";  // GREEN
    public static final String YELLOW_BOLD = "\033[1;33m"; // YELLOW
    public static final String BLUE_BOLD = "\033[1;34m";   // BLUE
    public static final String PURPLE_BOLD = "\033[1;35m"; // PURPLE
    public static final String CYAN_BOLD = "\033[1;36m";   // CYAN
    public static final String WHITE_BOLD = "\033[1;37m";  // WHITE

    // Underline
    public static final String BLACK_UNDERLINED = "\033[4;30m";  // BLACK
    public static final String RED_UNDERLINED = "\033[4;31m";    // RED
    public static final String GREEN_UNDERLINED = "\033[4;32m";  // GREEN
    public static final String YELLOW_UNDERLINED = "\033[4;33m"; // YELLOW
    public static final String BLUE_UNDERLINED = "\033[4;34m";   // BLUE
    public static final String PURPLE_UNDERLINED = "\033[4;35m"; // PURPLE
    public static final String CYAN_UNDERLINED = "\033[4;36m";   // CYAN
    public static final String WHITE_UNDERLINED = "\033[4;37m";  // WHITE

    // Background
    public static final String BLACK_BACKGROUND = "\033[40m";  // BLACK
    public static final String RED_BACKGROUND = "\033[41m";    // RED
    public static final String GREEN_BACKGROUND = "\033[42m";  // GREEN
    public static final String YELLOW_BACKGROUND = "\033[43m"; // YELLOW
    public static final String BLUE_BACKGROUND = "\033[44m";   // BLUE
    public static final String PURPLE_BACKGROUND = "\033[45m"; // PURPLE
    public static final String CYAN_BACKGROUND = "\033[46m";   // CYAN
    public static final String WHITE_BACKGROUND = "\033[47m";  // WHITE

    // High Intensity
    public static final String BLACK_BRIGHT = "\033[0;90m";  // BLACK
    public static final String RED_BRIGHT = "\033[0;91m";    // RED
    public static final String GREEN_BRIGHT = "\033[0;92m";  // GREEN
    public static final String YELLOW_BRIGHT = "\033[0;93m"; // YELLOW
    public static final String BLUE_BRIGHT = "\033[0;94m";   // BLUE
    public static final String PURPLE_BRIGHT = "\033[0;95m"; // PURPLE
    public static final String CYAN_BRIGHT = "\033[0;96m";   // CYAN
    public static final String WHITE_BRIGHT = "\033[0;97m";  // WHITE

    // Bold High Intensity
    public static final String BLACK_BOLD_BRIGHT = "\033[1;90m"; // BLACK
    public static final String RED_BOLD_BRIGHT = "\033[1;91m";   // RED
    public static final String GREEN_BOLD_BRIGHT = "\033[1;92m"; // GREEN
    public static final String YELLOW_BOLD_BRIGHT = "\033[1;93m";// YELLOW
    public static final String BLUE_BOLD_BRIGHT = "\033[1;94m";  // BLUE
    public static final String PURPLE_BOLD_BRIGHT = "\033[1;95m";// PURPLE
    public static final String CYAN_BOLD_BRIGHT = "\033[1;96m";  // CYAN
    public static final String WHITE_BOLD_BRIGHT = "\033[1;97m"; // WHITE

    // High Intensity backgrounds
    public static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m";// BLACK
    public static final String RED_BACKGROUND_BRIGHT = "\033[0;101m";// RED
    public static final String GREEN_BACKGROUND_BRIGHT = "\033[0;102m";// GREEN
    public static final String YELLOW_BACKGROUND_BRIGHT = "\033[0;103m";// YELLOW
    public static final String BLUE_BACKGROUND_BRIGHT = "\033[0;104m";// BLUE
    public static final String PURPLE_BACKGROUND_BRIGHT = "\033[0;105m"; // PURPLE
    public static final String CYAN_BACKGROUND_BRIGHT = "\033[0;106m";  // CYAN
    public static final String WHITE_BACKGROUND_BRIGHT = "\033[0;107m";   // WHITE
}

How can I change the color of pagination dots of UIPageControl?

It's easy with Swift 1.2:

UIPageControl.appearance().pageIndicatorTintColor           = UIColor.lightGrayColor()
UIPageControl.appearance().currentPageIndicatorTintColor    = UIColor.redColor()

Add string in a certain position in Python

Simple function to accomplish this:

def insert_str(string, str_to_insert, index):
    return string[:index] + str_to_insert + string[index:]

Submit form on pressing Enter with AngularJS

FWIW - Here's a directive I've used for a basic confirm/alert bootstrap modal, without the need for a <form>

(just switch out the jQuery click action for whatever you like, and add data-easy-dismiss to your modal tag)

app.directive('easyDismiss', function() {
    return {
        restrict: 'A',
        link: function ($scope, $element) {

            var clickSubmit = function (e) {
                if (e.which == 13) {
                    $element.find('[type="submit"]').click();
                }
            };

            $element.on('show.bs.modal', function() {
                $(document).on('keypress', clickSubmit);
            });

            $element.on('hide.bs.modal', function() {
                $(document).off('keypress', clickSubmit);
            });
        }
    };
});

@import vs #import - iOS 7

It currently only works for the built in system frameworks. If you use #import like apple still do importing the UIKit framework in the app delegate it is replaced (if modules is on and its recognised as a system framework) and the compiler will remap it to be a module import and not an import of the header files anyway. So leaving the #import will be just the same as its converted to a module import where possible anyway

Easiest way to loop through a filtered list with VBA?

I used the RowHeight property of a range (which means cells as well). If it's zero then it's hidden. So just loop through all rows as you would normally but in the if condition check for that property as in If myRange.RowHeight > 0 then DoStuff where DoStuff is something you want to do with the visible cells.

Get column index from label in a data frame

Here is an answer that will generalize Henrik's answer.

df=data.frame(A=rnorm(100), B=rnorm(100), C=rnorm(100))
numeric_columns<-c('A', 'B', 'C')
numeric_index<-sapply(1:length(numeric_columns), function(i)
grep(numeric_columns[i], colnames(df))) 

Select distinct using linq

Using morelinq you can use DistinctBy:

myList.DistinctBy(x => x.id);

Otherwise, you can use a group:

myList.GroupBy(x => x.id)
      .Select(g => g.First());

Convert Float to Int in Swift

You can type cast like this:

 var float:Float = 2.2
 var integer:Int = Int(float)

What Does 'zoom' do in CSS?

Surprised that nobody mentioned that zoom: 1; is useful for IE6-7, to solve most IE-only bugs by triggering hasLayout.

Enzyme - How to access and set <input> value?

In my case i was using ref callbacks,

  <input id="usuario" className="form-control" placeholder="Usuario"
                                                       name="usuario" type="usuario"
                                                       onKeyUp={this._validateMail.bind(this)}
                                                       onChange={()=> this._validateMail()}
                                                       ref={(val) =>{ this._username = val}}
                                                    >

To obtain the value. So enzyme will not change the value of this._username.

So i had to:

login.node._username.value = "[email protected]";
    user.simulate('change');
    expect(login.state('mailValid')).toBe(true);

To be able to set the value then call change . And then assert.

How to force a WPF binding to refresh?

Try using BindingExpression.UpdateTarget()

error TS2339: Property 'x' does not exist on type 'Y'

The correct fix is to add the property in the type definition as explained in @Nitzan Tomer's answer. If that's not an option though:

(Hacky) Workaround 1

You can assign the object to a constant of type any, then call the 'non-existing' property.

const newObj: any = oldObj;
return newObj.someProperty;

You can also cast it as any:

return (oldObj as any).someProperty;

This fails to provide any type safety though, which is the point of TypeScript.


(Hacky) Workaround 2

Another thing you may consider, if you're unable to modify the original type, is extending the type like so:

interface NewType extends OldType {
  someProperty: string;
}

Now you can cast your variable as this NewType instead of any. Still not ideal but less permissive than any, giving you more type safety.

return (oldObj as NewType).someProperty;

How to vertically center an image inside of a div element in HTML using CSS?

Have you tried setting margin on the div? e.g.

div {
    padding: 25px, 0
}

for top and bottom. You may also be able to use a percentage:

div {
    padding: 25%, 0
}

Fit background image to div

background-position-x: center;
background-position-y: center;

Is there a naming convention for MySQL?

as @fabrizio-valencia said use lower case. in windows if you export mysql database (phpmyadmin) the tables name will converted to lower case and this lead to all sort of problems. see Are table names in MySQL case sensitive?

Apache VirtualHost and localhost

According to this documentation: Name-based Virtual Host Support

You may be missing the following directive:

NameVirtualHost *:80

Microsoft Excel mangles Diacritics in .csv files?

You can save an html file with the extension 'xls' and accents will work (pre 2007 at least).

Example: save this (using Save As utf8 in Notepad) as test.xls:

<html>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<table>
<tr>
  <th>id</th>
  <th>name</th>
</tr>
<tr>
 <td>4</td>
 <td>Hélène</td>
</tr>
</table>
</html>

JWT refresh token flow

Assuming that this is about OAuth 2.0 since it is about JWTs and refresh tokens...:

  1. just like an access token, in principle a refresh token can be anything including all of the options you describe; a JWT could be used when the Authorization Server wants to be stateless or wants to enforce some sort of "proof-of-possession" semantics on to the client presenting it; note that a refresh token differs from an access token in that it is not presented to a Resource Server but only to the Authorization Server that issued it in the first place, so the self-contained validation optimization for JWTs-as-access-tokens does not hold for refresh tokens

  2. that depends on the security/access of the database; if the database can be accessed by other parties/servers/applications/users, then yes (but your mileage may vary with where and how you store the encryption key...)

  3. an Authorization Server may issue both access tokens and refresh tokens at the same time, depending on the grant that is used by the client to obtain them; the spec contains the details and options on each of the standardized grants

What is a classpath and how do I set it?

CLASSPATH is an environment variable (i.e., global variables of the operating system available to all the processes) needed for the Java compiler and runtime to locate the Java packages used in a Java program. (Why not call PACKAGEPATH?) This is similar to another environment variable PATH, which is used by the CMD shell to find the executable programs.

CLASSPATH can be set in one of the following ways:

CLASSPATH can be set permanently in the environment: In Windows, choose control panel ? System ? Advanced ? Environment Variables ? choose "System Variables" (for all the users) or "User Variables" (only the currently login user) ? choose "Edit" (if CLASSPATH already exists) or "New" ? Enter "CLASSPATH" as the variable name ? Enter the required directories and JAR files (separated by semicolons) as the value (e.g., ".;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need to include the current working directory (denoted by '.') in the CLASSPATH.

To check the current setting of the CLASSPATH, issue the following command:

> SET CLASSPATH

CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:

> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar

Instead of using the CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of the javac and java commands, for example,

> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Paths specified with a . are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js but not if you run node folder/app.js. The only exception to this is require('./file') and that is only possible because require exists per-module and thus knows what module it is being called from.

To make a path relative to the script, you must use the __dirname variable.

var path = require('path');

path.join(__dirname, 'path/to/file')

or potentially

path.join(__dirname, 'path', 'to', 'file')

How do you extract classes' source code from a dll file?

Only managed Languages like c# and Java can be decompiled completely.You can view complete source code. For Win32 dll you cannot get source code.

For CSharp dll Use DotPeek becoz it free and works same as ReDgate .Net Compiler

Have fun.

What is the meaning of prepended double colon "::"?

Lots of reasonable answers already. I'll chip in with an analogy that may help some readers. :: works a lot like the filesystem directory separator '/', when searching your path for a program you'd like to run. Consider:

/path/to/executable

This is very explicit - only an executable at that exact location in the filesystem tree can match this specification, irrespective of the PATH in effect. Similarly...

::std::cout

...is equally explicit in the C++ namespace "tree".

Contrasting with such absolute paths, you can configure good UNIX shells (e.g. zsh) to resolve relative paths under your current directory or any element in your PATH environment variable, so if PATH=/usr/bin:/usr/local/bin, and you were "in" /tmp, then...

X11/xterm

...would happily run /tmp/X11/xterm if found, else /usr/bin/X11/xterm, else /usr/local/bin/X11/xterm. Similarly, say you were in a namespace called X, and had a "using namespace Y" in effect, then...

std::cout

...could be found in any of ::X::std::cout, ::std::cout, ::Y::std::cout, and possibly other places due to argument-dependent lookup (ADL, aka Koenig lookup). So, only ::std::cout is really explicit about exactly which object you mean, but luckily nobody in their right mind would ever create their own class/struct or namespace called "std", nor anything called "cout", so in practice using only std::cout is fine.

Noteworthy differences:

1) shells tend to use the first match using the ordering in PATH, whereas C++ gives a compiler error when you've been ambiguous.

2) In C++, names without any leading scope can be matched in the current namespace, while most UNIX shells only do that if you put . in the PATH.

3) C++ always searches the global namespace (like having / implicitly your PATH).

General discussion on namespaces and explicitness of symbols

Using absolute ::abc::def::... "paths" can sometimes be useful to isolate you from any other namespaces you're using, part of but don't really have control over the content of, or even other libraries that your library's client code also uses. On the other hand, it also couples you more tightly to the existing "absolute" location of the symbol, and you miss the advantages of implicit matching in namespaces: less coupling, easier mobility of code between namespaces, and more concise, readable source code.

As with many things, it's a balancing act. The C++ Standard puts lots of identifiers under std:: that are less "unique" than cout, that programmers might use for something completely different in their code (e.g. merge, includes, fill, generate, exchange, queue, toupper, max). Two unrelated non-Standard libraries have a far higher chance of using the same identifiers as the authors are generally un- or less-aware of each other. And libraries - including the C++ Standard library - change their symbols over time. All this potentially creates ambiguity when recompiling old code, particularly when there's been heavy use of using namespaces: the worst thing you can do in this space is allow using namespaces in headers to escape the headers' scopes, such that an arbitrarily large amount of direct and indirect client code is unable to make their own decisions about which namespaces to use and how to manage ambiguities.

So, a leading :: is one tool in the C++ programmer's toolbox to actively disambiguate a known clash, and/or eliminate the possibility of future ambiguity....

How to get Android application id?

I am not sure what you need the app/installation ID for, but you can review the existing possibilities in a great article from Android developers:

To sum up:

  • UUID.randomUUID() for creating id on the first time an app runs after installation and simple retrieval afterwards
  • TelephonyManager.getDeviceId() for actual device identifier
  • Settings.Secure.ANDROID_ID on relatively modern devices

How to change color of the back arrow in the new material theme?

As said on most of the previous comments, the solution is to add

<item name="colorControlNormal">@color/white</item> to your app theme. But confirm that you don´t have another theme defined in your Toolbar element on your layout.

     <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:elevation="4dp"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

this works for ubuntu 15.10:

sudo locale-gen "en_US.UTF-8"
sudo dpkg-reconfigure locales

Android setOnClickListener method - How does it work?

its an implementation of anonymouse class object creation to give ease of writing less code and to save time

Text size and different android screen sizes

I did same by dimension and paint something like (with dp but only for text and in drawText())

XML:

   <dimen name="text_size">30sp</dimen>

Code:

   Paint p =new Paint();
       p.setTextSize(getResources().getDimension(R.dimen.text_Size));

Set and Get Methods in java?

Having accessor methods is preferred to accessing fields directly, because it controls how fields are accessed (may impose data checking etc) and fits with interfaces (interfaces can not requires fields to be present, only methods).

Downloading all maven dependencies to a directory NOT in repository?

I finally figured out a how to use Maven. From within Eclipse, create a new Maven project.

Download Maven, extract the archive, add the /bin folder to path.

Validate install from command-line by running mvn -v (will print version and java install path)

Change to the project root folder (where pom.xml is located) and run:

mvn dependency:copy-dependencies

All jar-files are downloaded to /target/dependency.

To set another output directory:

mvn dependency:copy-dependencies -DoutputDirectory="c:\temp"

Now it's possible to re-use this Maven-project for all dependency downloads by altering the pom.xml

Add jars to java project by build path -> configure build path -> libraries -> add JARs..

Html.Raw() in ASP.NET MVC Razor view

You shouldn't be calling .ToString().

As the error message clearly states, you're writing a conditional in which one half is an IHtmlString and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.


There is never a reason to call Html.Raw(...).ToString().
Html.Raw returns an HtmlString instance that wraps the original string.
The Razor page output knows not to escape HtmlString instances.

However, calling HtmlString.ToString() just returns the original string value again; it doesn't accomplish anything.

Restore a postgres backup file using the command line?

Sorry for the necropost, but these solutions did not work for me. I'm on postgres 10. On Linux:

  1. I had to change directory to my pg_hba.conf.
  2. I had to edit the file to change method from peer to md5 as stated here
  3. Restart the service: service postgresql-10 restart
  4. Change directory to where my backup.sql was located and execute:
    psql postgres -d database_name -1 -f backup.sql

    -database_name is the name of my database

    -backup.sql is the name of my .sql backup file.

How to trim a file extension from a String in JavaScript?

If you know the length of the extension, you can use x.slice(0, -4) (where 4 is the three characters of the extension and the dot).

If you don't know the length @John Hartsock regex would be the right approach.

If you'd rather not use regular expressions, you can try this (less performant):

filename.split('.').slice(0, -1).join('.')

Note that it will fail on files without extension.

SQL - Create view from multiple tables

Union is not what you want. You want to use joins to create single rows. It's a little unclear what constitutes a unique row in your tables and how they really relate to each other and it's also unclear if one table will have rows for every country in every year. But I think this will work:

CREATE VIEW V AS (

  SELECT i.country,i.year,p.pop,f.food,i.income FROM
    INCOME i
  LEFT JOIN 
    POP p 
  ON
    i.country=p.country
  LEFT JOIN
    Food f
  ON 
    i.country=f.country
  WHERE 
    i.year=p.year
  AND
    i.year=f.year
);

The left (outer) join will return rows from the first table even if there are no matches in the second. I've written this assuming you would have a row for every country for every year in the income table. If you don't things get a bit hairy as MySQL does not have built in support for FULL OUTER JOINs last I checked. There are ways to simulate it, and they would involve unions. This article goes into some depth on the subject: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/

Updates were rejected because the tip of your current branch is behind its remote counterpart

This just happened to me.

  • I made a pull request to our master yesterday.
  • My colleague was reviewing it today and saw that it was out of sync with our master branch, so with the intention of helping me, he merged master to my branch.
  • I didn't know he did that.
  • Then I merged master locally, tried to push it, but it failed. Why? Because my colleague merge with master created an extra commit I did not have locally!

Solution: Pull down my own branch so I get that extra commit. Then push it back to my remote branch.

literally what I did on my branch was:

git pull
git push

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

Invoke-customs are only supported starting with android 0 --min-api 26

In my case the error was still there, because my system used upgraded Java. If you are using Java 10, modify the compileOptions:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_10
    targetCompatibility JavaVersion.VERSION_1_10

}

Setting a spinner onClickListener() in Android

Here is a working solution:

Instead of setting the spinner's OnClickListener, we are setting OnTouchListener and OnKeyListener.

spinner.setOnTouchListener(Spinner_OnTouch);
spinner.setOnKeyListener(Spinner_OnKey);

and the listeners:

private View.OnTouchListener Spinner_OnTouch = new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            doWhatYouWantHere();
        }
        return true;
    }
};
private static View.OnKeyListener Spinner_OnKey = new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
            doWhatYouWantHere();
            return true;
        } else {
            return false;
        }
    }
};

Replacing Spaces with Underscores

I used like this

$option = trim($option);
$option = str_replace(' ', '_', $option);

Batch script: how to check for admin rights

I have two ways of checking for privileged access, both are pretty reliable, and very portable across almost every windows version.

1. Method

set guid=%random%%random%-%random%-%random%-%random%-%random%%random%%random%

mkdir %WINDIR%\%guid%>nul 2>&1
rmdir %WINDIR%\%guid%>nul 2>&1

IF %ERRORLEVEL%==0 (
    ECHO PRIVILEGED!
) ELSE (
    ECHO NOT PRIVILEGED!
)

This is one of the most reliable methods, because of its simplicity, and the behavior of this very primitive command is very unlikely to change. That is not the case of other built-in CLI tools like net session that can be disabled by admin/network policies, or commands like fsutils that changed the output on Windows 10.

* Works on XP and later

2. Method

REG ADD HKLM /F>nul 2>&1

IF %ERRORLEVEL%==0 (
    ECHO PRIVILEGED!
) ELSE (
    ECHO NOT PRIVILEGED!
)

Sometimes you don't like the idea of touching the user disk, even if it is as inoffensive as using fsutils or creating a empty folder, is it unprovable but it can result in a catastrophic failure if something goes wrong. In this scenario you can just check the registry for privileges.

For this you can try to create a key on HKEY_LOCAL_MACHINE using default permissions you'll get Access Denied and the ERRORLEVEL == 1, but if you run as Admin, it will print "command executed successfully" and ERRORLEVEL == 0. Since the key already exists it have no effect on the registry. This is probably the fastest way, and the REG is there for a long time.

* It's not avaliable on pre NT (Win 9X).

* Works on XP and later


Working example

A script that clear the temp folder

_x000D_
_x000D_
@echo off_x000D_
:main_x000D_
    echo._x000D_
    echo. Clear Temp Files script_x000D_
    echo._x000D_
_x000D_
    call :requirePrivilegies_x000D_
_x000D_
    rem Do something that require privilegies_x000D_
_x000D_
    echo. _x000D_
    del %temp%\*.*_x000D_
    echo. End!_x000D_
_x000D_
    pause>nul_x000D_
goto :eof_x000D_
_x000D_
_x000D_
:requirePrivilegies_x000D_
    set guid=%random%%random%-%random%-%random%-%random%-%random%%random%%random%_x000D_
    mkdir %WINDIR%\%guid%>nul 2>&1_x000D_
    rmdir %WINDIR%\%guid%>nul 2>&1_x000D_
    IF NOT %ERRORLEVEL%==0 (_x000D_
        echo ########## ERROR: ADMINISTRATOR PRIVILEGES REQUIRED ###########_x000D_
        echo # This script must be run as administrator to work properly!  #_x000D_
        echo # Right click on the script and select "Run As Administrator" #_x000D_
        echo ###############################################################_x000D_
        pause>nul_x000D_
        exit_x000D_
    )_x000D_
goto :eof
_x000D_
_x000D_
_x000D_

Adding blur effect to background in swift

@AlvinGeorge should just use:

extension UIImageView{        
    func blurImage()
    {
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = self.bounds

        blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] // for supporting device rotation
        self.addSubview(blurEffectView)
    }
}

usage:

 blurredBackground.frame = self.view.bounds
 blurredBackground.blurImage()
 self.view.addSubview(self.blurredBackground)

How can I do a BEFORE UPDATED trigger with sql server?

Remember that when you use an instead trigger, it will not commit the insert unless you specifically tell it to in the trigger. Instead of really means do this instead of what you normally do, so none of the normal insert actions would happen.

display: inline-block extra margin

Can you post a link to the HTML in question?

Ultimately you should be able to do:

div {
    margin:0;
    padding: 0;
}

to remove the spacing. Is this just in one particular browser or all of them?

Mapping US zip code to time zone

Also note, that if you happen to be using Yahoo geocoding service you can have timezone information returned to you by setting the correct flag.

http://developer.yahoo.com/geo/placefinder/guide/requests.html#flags-parameter

int object is not iterable?

Side note: if you want to get the sum of all digits, you can simply do

print sum(int(digit) for digit in raw_input('Enter a number:'))

With android studio no jvm found, JAVA_HOME has been set

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

enter image description here

$(document).on("click"... not working?

Try this:

$("#test-element").on("click" ,function() {
    alert("click");
});

The document way of doing it is weird too. That would make sense to me if used for a class selector, but in the case of an id you probably just have useless DOM traversing there. In the case of the id selector, you get that element instantly.

How can I use a C++ library from node.js?

You could use emscripten to compile C++ code into js.

Remove Last Comma from a string

long shot here

var sentence="I got,. commas, here,";
var pattern=/,/g;
var currentIndex;
while (pattern.test(sentence)==true)  {    
  currentIndex=pattern.lastIndex;
 }
if(currentIndex==sentence.trim().length)
alert(sentence.substring(0,currentIndex-1));
else
 alert(sentence);

How to set up fixed width for <td>?

For Bootstrap 4, you can simply use the class helper:

<table class="table">
  <thead>
    <tr>
      <td class="w-25">Col 1</td>
      <td class="w-25">Col 2</td>
      <td class="w-25">Col 3</td>
      <td class="w-25">Col 4</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      ...

.htaccess rewrite to redirect root URL to subdirectory

Here is what I used to redirect to a subdirectory. This did it invisibly and still allows through requests that match an existing file or whatever.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?site.com$
RewriteCond %{REQUEST_URI} !^/subdir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /subdir/$1
RewriteCond %{HTTP_HOST} ^(www.)?site.com$
RewriteRule ^(/)?$ subdir/index.php [L]

Change out site.com and subdir with your values.

Replace multiple whitespaces with single whitespace in JavaScript string

You can augment String to implement these behaviors as methods, as in:

String.prototype.killWhiteSpace = function() {
    return this.replace(/\s/g, '');
};

String.prototype.reduceWhiteSpace = function() {
    return this.replace(/\s+/g, ' ');
};

This now enables you to use the following elegant forms to produce the strings you want:

"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra        whitespaces".reduceWhiteSpace();

Select count(*) from multiple tables

My experience is with SQL Server, but could you do:

select (select count(*) from table1) as count1,
  (select count(*) from table2) as count2

In SQL Server I get the result you are after.

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

Print a list of space-separated elements in Python 3

Joining elements in a list space separated:

word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
   joined_string = w + joined_string + " "
print(joined_string.rstrim())

How does @synchronized lock/unlock in Objective-C?

Actually

{
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

transforms directly into:

// needs #import <objc/objc-sync.h>
{
  objc_sync_enter(self)
    id retVal = [[myString retain] autorelease];
  objc_sync_exit(self);
  return retVal;
}

This API available since iOS 2.0 and imported using...

#import <objc/objc-sync.h>

Utility of HTTP header "Content-Type: application/force-download" for mobile?

To download a file please use the following code ... Store the File name with location in $file variable. It supports all mime type

$file = "location of file to download"
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);

To know about Mime types please refer to this link: http://php.net/manual/en/function.mime-content-type.php

Is it possible to set async:false to $.getJSON call

Roll your own e.g.

function syncJSON(i_url, callback) {
  $.ajax({
    type: "POST",
    async: false,
    url: i_url,
    contentType: "application/json",
    dataType: "json",
    success: function (msg) { callback(msg) },
    error: function (msg) { alert('error : ' + msg.d); }
  });
}

syncJSON("/pathToYourResouce", function (msg) {
   console.log(msg);
})

How do I implement a callback in PHP?

One nifty trick that I've recently found is to use PHP's create_function() to create an anonymous/lambda function for one-shot use. It's useful for PHP functions like array_map(), preg_replace_callback(), or usort() that use callbacks for custom processing. It looks pretty much like it does an eval() under the covers, but it's still a nice functional-style way to use PHP.

iPhone X / 8 / 8 Plus CSS media queries

iPhone X

@media only screen 
    and (device-width : 375px) 
    and (device-height : 812px) 
    and (-webkit-device-pixel-ratio : 3) { }

iPhone 8

@media only screen 
    and (device-width : 375px) 
    and (device-height : 667px) 
    and (-webkit-device-pixel-ratio : 2) { }

iPhone 8 Plus

@media only screen 
    and (device-width : 414px) 
    and (device-height : 736px) 
    and (-webkit-device-pixel-ratio : 3) { }


iPhone 6+/6s+/7+/8+ share the same sizes, while the iPhone 7/8 also do.


Looking for a specific orientation ?

Portrait

Add the following rule:

    and (orientation : portrait) 

Landscape

Add the following rule:

    and (orientation : landscape) 



References:

How do I get my page title to have an icon?

<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />

add this to your HTML Head. Of course the file "favicon.ico" has to exist. I think 16x16 or 32x32 pixel files are best.

/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

I ran into this issue on my Ubuntu-64 system when attempting to import fst within python as such:

    Python 3.4.3 |Continuum Analytics, Inc.| (default, Jun  4 2015, 15:29:08)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fst
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ogi/miniconda3/lib/python3.4/site-packages/pyfst-0.2.3.dev0-py3.4-linux-x86_64.egg/fst/__init__.py", line 1, in <module>
    from fst._fst import EPSILON, EPSILON_ID, SymbolTable,\
ImportError: /home/ogi/miniconda3/lib/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /usr/local/lib/libfst.so.1)

I then ran:

ogi@ubuntu:~/miniconda3/lib$ find ~/ -name "libstdc++.so.6"
/home/ogi/miniconda3/lib/libstdc++.so.6
/home/ogi/miniconda3/pkgs/libgcc-5-5.2.0-2/lib/libstdc++.so.6
/home/ogi/miniconda3/pkgs/libgcc-4.8.5-1/lib/libstdc++.so.6
find: `/home/ogi/.local/share/jupyter/runtime': Permission denied
ogi@ubuntu:~/miniconda3/lib$

mv /home/ogi/miniconda3/lib/libstdc++.so.6 /home/ogi/miniconda3/libstdc++.so.6.old
cp /home/ogi/miniconda3/libgcc-5-5.2.0-2/lib/libstdc++.so.6 /home/ogi/miniconda3/lib/

At which point I was then able to load the library

ogi@ubuntu:~/miniconda3/lib$ python
Python 3.4.3 |Continuum Analytics, Inc.| (default, Jun  4 2015, 15:29:08)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fst
>>> exit()

JavaScript single line 'if' statement - best syntax, this alternative?

As has already been stated, you can use:

&& style

lemons && document.write("foo gave me a bar");  

or

bracket-less style

if (lemons) document.write("foo gave me a bar");

short-circuit return

If, however, you wish to use the one line if statement to short-circuit a function though, you'd need to go with the bracket-less version like so:

if (lemons) return "foo gave me a bar";

as

lemons && return "foo gave me a bar"; // does not work!

will give you a SyntaxError: Unexpected keyword 'return'

When adding a Javascript library, Chrome complains about a missing source map, why?

In my case I had to remove React Dev Tools from Chrome to stop seeing the strange errors during development of React app using a local Express server with a create-react-app client (which uses Webpack). In the interest of community I did a sanity check and quit everything - server/client server/Chrome - and then I opened Chrome and reinstalled React Dev Tools... Started things back up and am seeing this funky address and error again: Error seems to be from React Dev Tools extension in my case

how to access iFrame parent page using jquery?

It's working for me with little twist. In my case I have to populate value from POPUP JS to PARENT WINDOW form.

So I have used $('#ee_id',window.opener.document).val(eeID);

Excellent!!!

Does svn have a `revert-all` command?

You could do:

svn revert -R .

This will not delete any new file not under version control. But you can easily write a shell script to do that like:

for file in `svn status|grep "^ *?"|sed -e 's/^ *? *//'`; do rm $file ; done

Downgrade npm to an older version

npm install -g npm@4

This will install the latest version on the major release 4, no no need to specify version number. Replace 4 with whatever major release you want.

How to remove provisioning profiles from Xcode

I found out how to find provisioning profiles in Xcode 8. Archive your project (Product -> Archive) and then hit the validate button. Xcode will prepare the binary and the entitlements. When the summary windows comes up just hit the little arrow at the right of the window. A finder window will open with all your downloaded profiles.enter image description here

How do I display an alert dialog on Android?

This is definitely help for you. Try this code: On click of a button, you can put one, two or three buttons with an alert dialog...

SingleButtton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {
        // Creating alert Dialog with one Button

        AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();

        // Setting Dialog Title
        alertDialog.setTitle("Alert Dialog");

        // Setting Dialog Message
        alertDialog.setMessage("Welcome to Android Application");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.tick);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog,int which)
            {
                // Write your code here to execute after dialog    closed
                Toast.makeText(getApplicationContext(),"You clicked on OK", Toast.LENGTH_SHORT).show();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
});

btnAlertTwoBtns.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {
        // Creating alert Dialog with two Buttons

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);

        // Setting Dialog Title
        alertDialog.setTitle("Confirm Delete...");

        // Setting Dialog Message
        alertDialog.setMessage("Are you sure you want delete this?");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.delete);

        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton("YES",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int which) {
                        // Write your code here to execute after dialog
                        Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
                    }
                });

        // Setting Negative "NO" Button
        alertDialog.setNegativeButton("NO",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,    int which) {
                        // Write your code here to execute after dialog
                        Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }
});

btnAlertThreeBtns.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {
        // Creating alert Dialog with three Buttons

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                AlertDialogActivity.this);

        // Setting Dialog Title
        alertDialog.setTitle("Save File...");

        // Setting Dialog Message
        alertDialog.setMessage("Do you want to save this file?");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.save);

        // Setting Positive Yes Button
        alertDialog.setPositiveButton("YES",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                        int which) {
                    // User pressed Cancel button. Write Logic Here
                    Toast.makeText(getApplicationContext(),
                            "You clicked on YES",
                            Toast.LENGTH_SHORT).show();
                }
            });

        // Setting Negative No Button... Neutral means in between yes and cancel button
        alertDialog.setNeutralButton("NO",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                        int which) {
                    // User pressed No button. Write Logic Here
                    Toast.makeText(getApplicationContext(),
                            "You clicked on NO", Toast.LENGTH_SHORT)
                            .show();
                }
            });

        // Setting Positive "Cancel" Button
        alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog,
                        int which) {
                    // User pressed Cancel button. Write Logic Here
                    Toast.makeText(getApplicationContext(),
                            "You clicked on Cancel",
                            Toast.LENGTH_SHORT).show();
                }
            });
        // Showing Alert Message
        alertDialog.show();
    }
});

angular js unknown provider

I got that error because I was passing an incorrect parameter to the factory definition. I had:

myModule.factory('myService', function($scope, $http)...

It worked when I removed the $scope and changed the factory definition to:

myModule.factory('myService', function( $http)...

In case you need to inject $scope, use:

myModule.factory('myService', function($rootScope, $http)...

Why is there still a row limit in Microsoft Excel?

In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.

Fatal error: iostream: No such file or directory in compiling C program using GCC

Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

ROWS UNBOUNDED PRECEDING is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY it defines the window on which the result is calculated.

Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.

Starting and ending rows might be fixed or relative to the current row based on the following keywords:

  • CURRENT ROW, the current row
  • UNBOUNDED PRECEDING, all rows before the current row -> fixed
  • UNBOUNDED FOLLOWING, all rows after the current row -> fixed
  • x PRECEDING, x rows before the current row -> relative
  • y FOLLOWING, y rows after the current row -> relative

Possible kinds of calculation include:

  • Both starting and ending row are fixed, the window consists of all rows of a partition, e.g. a Group Sum, i.e. aggregate plus detail rows
  • One end is fixed, the other relative to current row, the number of rows increases or decreases, e.g. a Running Total, Remaining Sum
  • Starting and ending row are relative to current row, the number of rows within a window is fixed, e.g. a Moving Average over n rows

So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING) results in a Cumulative Sum or Running Total

11 -> 11
 2 -> 11 +  2                = 13
 3 -> 13 +  3 (or 11+2+3)    = 16
44 -> 16 + 44 (or 11+2+3+44) = 60

How to define two angular apps / modules in one page?

Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead. AngularJS applications cannot be nested within each other. -- http://docs.angularjs.org/api/ng.directive:ngApp

See also

Dockerfile if else condition with external arguments

The accepted answer may solve the question, but if you want multiline if conditions in the dockerfile, you can do that placing \ at the end of each line (similar to how you would do in a shell script) and ending each command with ;. You can even define someting like set -eux as the 1st command.

Example:

RUN set -eux; \
  if [ -f /path/to/file ]; then \
    mv /path/to/file /dest; \
  fi; \
  if [ -d /path/to/dir ]; then \
    mv /path/to/dir /dest; \
  fi

In your case:

FROM centos:7
ARG arg
RUN if [ -z "$arg" ] ; then \
    echo Argument not provided; \
  else \
    echo Argument is $arg; \
  fi

Then build with:

docker build -t my_docker . --build-arg arg=42

Copy an entire worksheet to a new worksheet in Excel 2010

'Make the excel file that runs the software the active workbook
ThisWorkbook.Activate

'The first sheet used as a temporary place to hold the data 
ThisWorkbook.Worksheets(1).Cells.Copy

'Create a new Excel workbook
Dim NewCaseFile As Workbook
Dim strFileName As String

Set NewCaseFile = Workbooks.Add
With NewCaseFile
    Sheets(1).Select
    Cells(1, 1).Select
End With

ActiveSheet.Paste

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

Is it possible to have multiple styles inside a TextView?

As stated, use TextView.setText(Html.fromHtml(String))

And use these tags in your Html formatted string:

<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font size="..." color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>

http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html

Import SQL file by command line in Windows 7

Related to importing, if you are having issues importing a file with bulk inserts and you're getting MYSQL GONE AWAY, lost connection or similar error, open your my.cnf / my.ini and temporarily set your max_allowed_packet to something large like 400M

Remember to set it back again after your import!

What do "branch", "tag" and "trunk" mean in Subversion repositories?

In addition to what Nick has said you can find out more at Streamed Lines: Branching Patterns for Parallel Software Development

enter image description here

In this figure main is the trunk, rel1-maint is a branch and 1.0 is a tag.

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

How to load external scripts dynamically in Angular?

In my case, I've loaded both the js and css visjs files using the above technique - which works great. I call the new function from ngOnInit()

Note: I could not get it to load by simply adding a <script> and <link> tag to the html template file.

_x000D_
_x000D_
loadVisJsScript() {_x000D_
  console.log('Loading visjs js/css files...');_x000D_
  let script = document.createElement('script');_x000D_
  script.src = "../../assets/vis/vis.min.js";_x000D_
  script.type = 'text/javascript';_x000D_
  script.async = true;_x000D_
  script.charset = 'utf-8';_x000D_
  document.getElementsByTagName('head')[0].appendChild(script);    _x000D_
 _x000D_
  let link = document.createElement("link");_x000D_
  link.type = "stylesheet";_x000D_
  link.href = "../../assets/vis/vis.min.css";_x000D_
  document.getElementsByTagName('head')[0].appendChild(link);    _x000D_
}
_x000D_
_x000D_
_x000D_

Grant all on a specific schema in the db to a group role in PostgreSQL

My answer is similar to this one on ServerFault.com.

To Be Conservative

If you want to be more conservative than granting "all privileges", you might want to try something more like these.

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;

The use of public there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.

Access to the Schema

To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.

You will not notice this requirement when first using Postgres. By default every database has a first schema named public. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.

GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;

Excerpt from the Postgres doc:

For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.

For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.

Existing Objects Versus Future

These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.

Razor/CSHTML - Any Benefit over what we have?

One of the benefits is that Razor views can be rendered inside unit tests, this is something that was not easily possible with the previous ASP.Net renderer.

From ScottGu's announcement this is listed as one of the design goals:

Unit Testable: The new view engine implementation will support the ability to unit test views (without requiring a controller or web-server, and can be hosted in any unit test project – no special app-domain required).

How to install lxml on Ubuntu

First install Ubuntu's python-lxml package and its dependencies:

sudo apt-get install python-lxml

Then use pip to upgrade to the latest version of lxml for Python:

pip install lxml

Using grep and sed to find and replace a string

My use case was I wanted to replace foo:/Drive_Letter with foo:/bar/baz/xyz In my case I was able to do it with the following code. I was in the same directory location where there were bulk of files.

find . -name "*.library" -print0 | xargs -0 sed -i '' -e 's/foo:\/Drive_Letter:/foo:\/bar\/baz\/xyz/g'

hope that helped.

jquery get all form elements: input, textarea & select

all inputs:

var inputs = $("#formId :input");

all buttons

var button = $("#formId :button")

How do I find all the files that were created today in Unix/Linux?

Use ls or find to have all the files that were created today.

Using ls : ls -ltr | grep "$(date '+%b %e')"

Using find : cd $YOUR_DIRECTORY; find . -ls 2>/dev/null| grep "$(date '+%b %e')"