Programs & Examples On #Netezza

Netezza is a line of high-performance data warehouse appliances and advanced in-database analytics applications for uses including enterprise data warehousing, business intelligence, and predictive analytics. In 2010, Netezza became a subsidiary of IBM, and the product was subsequently rebranded as "PureData System for Analytics, Powered by Netezza Technology" (also known as PDA).

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1 
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));

http://www.sqlfiddle.com/#!4/22115/1

Nginx not running with no error message

1. Check for your configuration files by running the aforementioned command: sudo nginx -t.

2. Check for port conflicts. For instance, if apache2 (ps waux | grep apache2) or any other service is using the same ports configured for nginx (say port 80) the service will not start and will fail silently (err... the cousin of my friend had this problem...)

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

I made the mistake of defining my test like this

class MyTest {
    @Test
    fun `test name`() = runBlocking {


        // something here that isn't Unit
    }
}

That resulted in runBlocking returning something, which meant that the method wasn't void and junit didn't recognize it as a test. That was pretty lame. I explicitly supply a type parameter now to run blocking. It won't stop the pain or get me my two hours back but it will make sure this doesn't happen again.

class MyTest {
    @Test
    fun `test name`() = runBlocking<Unit> { // Specify Unit


        // something here that isn't Unit
    }
}

Django TemplateDoesNotExist?

in your setting.py file replace DIRS in TEMPLATES array with this

'DIRS': []

to this

'DIRS': [os.path.join(BASE_DIR, 'templates')],

but 1 think u need to know is that you have to make a folder with name templates and it should on the root path otherwise u have to change the DIRS value

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Is it possible the root password is not what you think it is? Have you checked the file /root/.mysql_secret for the password? That is the default location for the automated root password that is generated from starting from version 5.7.

cat /root/.mysql_secret

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

In your AndroidManifest.xml add this two-line.

android:usesCleartextTraffic="true"  
<uses-library android:name="org.apache.http.legacy" android:required="false"/>

See this below code

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup,GoogleAppIndexingWarning">
        <activity android:name=".activity.SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <uses-library android:name="org.apache.http.legacy" android:required="false"/>
    </application>

Getting IP address of client

As basZero mentioned, X-Forwarded-For should be checked for comma. (Look at : http://en.wikipedia.org/wiki/X-Forwarded-For). The general format of the field is: X-Forwarded-For: clientIP, proxy1, proxy2... and so on. So we will be seeing something like this : X-FORWARDED-FOR: 129.77.168.62, 129.77.63.62.

How do I check if a list is empty?

Here are a few ways you can check if a list is empty:

a = [] #the list

1) The pretty simple pythonic way:

if not a:
    print("a is empty")

In Python, empty containers such as lists,tuples,sets,dicts,variables etc are seen as False. One could simply treat the list as a predicate (returning a Boolean value). And a True value would indicate that it's non-empty.

2) A much explicit way: using the len() to find the length and check if it equals to 0:

if len(a) == 0:
    print("a is empty")

3) Or comparing it to an anonymous empty list:

if a == []:
    print("a is empty")

4) Another yet silly way to do is using exception and iter():

try:
    next(iter(a))
    # list has elements
except StopIteration:
    print("Error: a is empty")

Move view with keyboard using Swift

I've need to move a UIView in swift 4 when keyboard opens and closes. and all of the answers couldn't help me. because height of keyboard changes when emojis open. so my code is :

@objc func keyboardWillShow(sender: NSNotification) {

    if let keyboardFrame: NSValue = sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {

        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height

        if(self.oldHeight == keyboardHeight){
            self.sendingView.frame.origin.y -= keyboardHeight
            self.oldHeight = keyboardHeight
        }
        else{
            self.sendingView.frame.origin.y += self.oldHeight
            self.sendingView.frame.origin.y -= keyboardHeight
            self.oldHeight = keyboardHeight
        }
    }
}

@objc func keyboardWillHide(sender: NSNotification) {

    if let keyboardFrame: NSValue = sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {

        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height

        self.sendingView.frame.origin.y += keyboardHeight

    }
}

and in viewDidLoad() :

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:NSNotification.Name.UIKeyboardWillHide, object: nil);

self.oldHeight = CGFloat() and defines as field at the top of class.

MongoDB Show all contents from all collections

Before writing below queries first get into your cmd or PowerShell

TYPE:
mongo             //To get into MongoDB shell
use <Your_dbName>      //For Creating or making use of existing db

To List All Collection Names use any one from below options :-

show collections  //output every collection
  OR
show tables
  OR
db.getCollectionNames() //shows all collections as a list

To show all collections content or data use below listed code which had been posted by Bruno_Ferreira.

var collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++) {    
   print('Collection: ' + collections[i]); // print the name of each collection
   db.getCollection(collections[i]).find().forEach(printjson); //and then print     the json of each of its elements
}

Logarithmic returns in pandas dataframe

Single line, and only calculating logs once. First convert to log-space, then take the 1-period diff.

    np.diff(np.log(df.price))

In earlier versions of numpy:

    np.log(df.price)).diff()

How to save a spark DataFrame as csv on disk?

I had similar problem. I needed to write down csv file on driver while I was connect to cluster in client mode.

I wanted to reuse the same CSV parsing code as Apache Spark to avoid potential errors.

I checked spark-csv code and found code responsible for converting dataframe into raw csv RDD[String] in com.databricks.spark.csv.CsvSchemaRDD.

Sadly it is hardcoded with sc.textFile and the end of relevant method.

I copy-pasted that code and removed last lines with sc.textFile and returned RDD directly instead.

My code:

/*
  This is copypasta from com.databricks.spark.csv.CsvSchemaRDD
  Spark's code has perfect method converting Dataframe -> raw csv RDD[String]
  But in last lines of that method it's hardcoded against writing as text file -
  for our case we need RDD.
 */
object DataframeToRawCsvRDD {

  val defaultCsvFormat = com.databricks.spark.csv.defaultCsvFormat

  def apply(dataFrame: DataFrame, parameters: Map[String, String] = Map())
           (implicit ctx: ExecutionContext): RDD[String] = {
    val delimiter = parameters.getOrElse("delimiter", ",")
    val delimiterChar = if (delimiter.length == 1) {
      delimiter.charAt(0)
    } else {
      throw new Exception("Delimiter cannot be more than one character.")
    }

    val escape = parameters.getOrElse("escape", null)
    val escapeChar: Character = if (escape == null) {
      null
    } else if (escape.length == 1) {
      escape.charAt(0)
    } else {
      throw new Exception("Escape character cannot be more than one character.")
    }

    val quote = parameters.getOrElse("quote", "\"")
    val quoteChar: Character = if (quote == null) {
      null
    } else if (quote.length == 1) {
      quote.charAt(0)
    } else {
      throw new Exception("Quotation cannot be more than one character.")
    }

    val quoteModeString = parameters.getOrElse("quoteMode", "MINIMAL")
    val quoteMode: QuoteMode = if (quoteModeString == null) {
      null
    } else {
      QuoteMode.valueOf(quoteModeString.toUpperCase)
    }

    val nullValue = parameters.getOrElse("nullValue", "null")

    val csvFormat = defaultCsvFormat
      .withDelimiter(delimiterChar)
      .withQuote(quoteChar)
      .withEscape(escapeChar)
      .withQuoteMode(quoteMode)
      .withSkipHeaderRecord(false)
      .withNullString(nullValue)

    val generateHeader = parameters.getOrElse("header", "false").toBoolean
    val headerRdd = if (generateHeader) {
      ctx.sparkContext.parallelize(Seq(
        csvFormat.format(dataFrame.columns.map(_.asInstanceOf[AnyRef]): _*)
      ))
    } else {
      ctx.sparkContext.emptyRDD[String]
    }

    val rowsRdd = dataFrame.rdd.map(row => {
      csvFormat.format(row.toSeq.map(_.asInstanceOf[AnyRef]): _*)
    })

    headerRdd union rowsRdd
  }

}

What is the difference between screenX/Y, clientX/Y and pageX/Y?

In JavaScript:

pageX, pageY, screenX, screenY, clientX, and clientY returns a number which indicates the number of physical “CSS pixels” a point is from the reference point. The event point is where the user clicked, the reference point is a point in the upper left. These properties return the horizontal and vertical distance from that reference point.

pageX and pageY:
Relative to the top left of the fully rendered content area in the browser. This reference point is below the URL bar and back button in the upper left. This point could be anywhere in the browser window and can actually change location if there are embedded scrollable pages embedded within pages and the user moves a scrollbar.

screenX and screenY:
Relative to the top left of the physical screen/monitor, this reference point only moves if you increase or decrease the number of monitors or the monitor resolution.

clientX and clientY:
Relative to the upper left edge of the content area (the viewport) of the browser window. This point does not move even if the user moves a scrollbar from within the browser.

For a visual on which browsers support which properties:

http://www.quirksmode.org/dom/w3c_cssom.html#t03

w3schools has an online Javascript interpreter and editor so you can see what each does

http://www.w3schools.com/jsref/tryit.asp?filename=try_dom_event_clientxy

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script>_x000D_
function show_coords(event)_x000D_
{_x000D_
  var x=event.clientX;_x000D_
  var y=event.clientY;_x000D_
  alert("X coords: " + x + ", Y coords: " + y);_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<p onmousedown="show_coords(event)">Click this paragraph, _x000D_
and an alert box will alert the x and y coordinates _x000D_
of the mouse pointer.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

In:

for i in range(c/10):

You're creating a float as a result - to fix this use the int division operator:

for i in range(c // 10):

How to get the browser to navigate to URL in JavaScript

Try these:

  1. window.location.href = 'http://www.google.com';
  2. window.location.assign("http://www.w3schools.com");
  3. window.location = 'http://www.google.com';

For more see this link: other ways to reload the page with JavaScript

What is the difference between Task.Run() and Task.Factory.StartNew()

The Task.Run got introduced in newer .NET framework version and it is recommended.

Starting with the .NET Framework 4.5, the Task.Run method is the recommended way to launch a compute-bound task. Use the StartNew method only when you require fine-grained control for a long-running, compute-bound task.

The Task.Factory.StartNew has more options, the Task.Run is a shorthand:

The Run method provides a set of overloads that make it easy to start a task by using default values. It is a lightweight alternative to the StartNew overloads.

And by shorthand I mean a technical shortcut:

public static Task Run(Action action)
{
    return Task.InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default,
        TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
}

MongoDB: How to query for records where field is null or not set?

You can also try this:

db.emails.find($and:[{sent_at:{$exists:true},'sent_at':null}]).count()

window.open with target "_blank" in Chrome

"_blank" is not guaranteed to be a new tab or window. It's implemented differently per-browser.

You can, however, put anything into target. I usually just say "_tab", and every browser I know of just opens it in a new tab.

Be aware that it means it's a named target, so if you try to open 2 URLs, they will use the same tab.

Execute cmd command from VBScript

Can also invoke oShell.Exec in order to be able to read STDIN/STDOUT/STDERR responses. Perfect for error checking which it seems you're doing with your sanity .BAT.

AttributeError: 'module' object has no attribute 'urlretrieve'

Suppose you have following lines of code

MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)

If you are receiving following error message

AttributeError: module 'urllib' has no attribute 'urlretrieve'

Then you should try following code to fix the issue:

import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)

'xmlParseEntityRef: no name' warnings while loading xml into a php file

The XML is invalid.

<![CDATA[ 
{INVALID XML}
]]> 

CDATA should be wrapped around all special XML characters, as per W3C

PHP how to get value from array if key is in a variable

As others stated, it's likely failing because the requested key doesn't exist in the array. I have a helper function here that takes the array, the suspected key, as well as a default return in the event the key does not exist.

    protected function _getArrayValue($array, $key, $default = null)
    {
        if (isset($array[$key])) return $array[$key];
        return $default;
    }

hope it helps.

ReferenceError: fetch is not defined

Best one is Axios library for fetching. use npm i --save axios for installng and use it like fetch, just write axios instead of fetch and then get response in then().

How to Troubleshoot Intermittent SQL Timeout Errors

I've seen similar problems happen if anti-virus was installed on the SQL server. The AV's auto-update features were clocking the server and not allowing enough CPU for SQL Server.

Also, have you put a small application on the SQL server itself that verifies that connections can be made or runs very basic SQL like "SELECT GETDATE();"? This would eliminate network possibilities.

What are the differences between using the terminal on a mac vs linux?

If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.

Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.

If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.

There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd on Mac and ifconfig works differently.

The following table is useful for knowing the various unix shells.

sh      The original Bourne shell   Present on every unix system 
ksh     Original Korn shell         Richer shell programming environment than sh 
csh     Original C-shell            C-like syntax; early versions buggy 
tcsh    Enhanced C-shell            User-friendly and less buggy csh implementation 
bash    GNU Bourne-again shell      Enhanced and free sh implementation 
zsh     Z shell                     Enhanced, user-friendly ksh-like shell

You may also find these guides helpful:

http://homepage.mac.com/rgriff/files/TerminalBasics.pdf

http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html

On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile on OSX) file with aliases, some examples below. I now placed all my aliases in a separate .bash_aliases file and include it with:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

in the .bashrc or .bash_profile file.

Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto. The first time I did this (without knowing) I redefined ls to be invalid which was a bit alarming until I removed --auto-color !

You may also find https://unix.stackexchange.com/q/127799/10043 useful

# ~/.bash_aliases
# ls variants
#alias l='ls -CF' 
alias la='ls -A' 
alias l='ls -alFtr' 
alias lsd='ls -d .*' 
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i' 
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed' 
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status' 
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'

Connect multiple devices to one device via Bluetooth

This is the class where the connection is established and messages are recieved. Make sure to pair the devices before you run the application. If you want to have a slave/master connection, where each slave can only send messages to the master , and the master can broadcast messages to all slaves. You should only pair the master with each slave , but you shouldn't pair the slaves together.

    package com.example.gaby.coordinatorv1;
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Set;
    import java.util.UUID;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothServerSocket;
    import android.bluetooth.BluetoothSocket;
    import android.content.Context;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.widget.Toast;

    public class Piconet {


        private final static String TAG = Piconet.class.getSimpleName();

        // Name for the SDP record when creating server socket
        private static final String PICONET = "ANDROID_PICONET_BLUETOOTH";

        private final BluetoothAdapter mBluetoothAdapter;

        // String: device address
        // BluetoothSocket: socket that represent a bluetooth connection
        private HashMap<String, BluetoothSocket> mBtSockets;

        // String: device address
        // Thread: thread for connection
        private HashMap<String, Thread> mBtConnectionThreads;

        private ArrayList<UUID> mUuidList;

        private ArrayList<String> mBtDeviceAddresses;

        private Context context;


        private Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        Toast.makeText(context, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
            };
        };

        public Piconet(Context context) {
            this.context = context;

            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

            mBtSockets = new HashMap<String, BluetoothSocket>();
            mBtConnectionThreads = new HashMap<String, Thread>();
            mUuidList = new ArrayList<UUID>();
            mBtDeviceAddresses = new ArrayList<String>();

            // Allow up to 7 devices to connect to the server
            mUuidList.add(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
            mUuidList.add(UUID.fromString("54d1cc90-1169-11e2-892e-0800200c9a66"));
            mUuidList.add(UUID.fromString("6acffcb0-1169-11e2-892e-0800200c9a66"));
            mUuidList.add(UUID.fromString("7b977d20-1169-11e2-892e-0800200c9a66"));
            mUuidList.add(UUID.fromString("815473d0-1169-11e2-892e-0800200c9a66"));
            mUuidList.add(UUID.fromString("503c7434-bc23-11de-8a39-0800200c9a66"));
            mUuidList.add(UUID.fromString("503c7435-bc23-11de-8a39-0800200c9a66"));

            Thread connectionProvider = new Thread(new ConnectionProvider());
            connectionProvider.start();

        }



        public void startPiconet() {
            Log.d(TAG, " -- Looking devices -- ");
            // The devices must be already paired
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
                    .getBondedDevices();
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    // X , Y and Z are the Bluetooth name (ID) for each device you want to connect to
                    if (device != null && (device.getName().equalsIgnoreCase("X") || device.getName().equalsIgnoreCase("Y")
                            || device.getName().equalsIgnoreCase("Z") || device.getName().equalsIgnoreCase("M"))) {
                        Log.d(TAG, " -- Device " + device.getName() + " found --");
                        BluetoothDevice remoteDevice = mBluetoothAdapter
                                .getRemoteDevice(device.getAddress());
                        connect(remoteDevice);
                    }
                }
            } else {
                Toast.makeText(context, "No paired devices", Toast.LENGTH_SHORT).show();
            }
        }

        private class ConnectionProvider implements Runnable {
            @Override
            public void run() {
                try {
                    for (int i=0; i<mUuidList.size(); i++) {
                        BluetoothServerSocket myServerSocket = mBluetoothAdapter
                                .listenUsingRfcommWithServiceRecord(PICONET, mUuidList.get(i));
                        Log.d(TAG, " ** Opened connection for uuid " + i + " ** ");

                        // This is a blocking call and will only return on a
                        // successful connection or an exception
                        Log.d(TAG, " ** Waiting connection for socket " + i + " ** ");
                        BluetoothSocket myBTsocket = myServerSocket.accept();
                        Log.d(TAG, " ** Socket accept for uuid " + i + " ** ");
                        try {
                            // Close the socket now that the
                            // connection has been made.
                            myServerSocket.close();
                        } catch (IOException e) {
                            Log.e(TAG, " ** IOException when trying to close serverSocket ** ");
                        }

                        if (myBTsocket != null) {
                            String address = myBTsocket.getRemoteDevice().getAddress();

                            mBtSockets.put(address, myBTsocket);
                            mBtDeviceAddresses.add(address);

                            Thread mBtConnectionThread = new Thread(new BluetoohConnection(myBTsocket));
                            mBtConnectionThread.start();

                            Log.i(TAG," ** Adding " + address + " in mBtDeviceAddresses ** ");
                            mBtConnectionThreads.put(address, mBtConnectionThread);
                        } else {
                            Log.e(TAG, " ** Can't establish connection ** ");
                        }
                    }
                } catch (IOException e) {
                    Log.e(TAG, " ** IOException in ConnectionService:ConnectionProvider ** ", e);
                }
            }
        }

        private class BluetoohConnection implements Runnable {
            private String address;

            private final InputStream mmInStream;

            public BluetoohConnection(BluetoothSocket btSocket) {

                InputStream tmpIn = null;

                try {
                    tmpIn = new DataInputStream(btSocket.getInputStream());
                } catch (IOException e) {
                    Log.e(TAG, " ** IOException on create InputStream object ** ", e);
                }
                mmInStream = tmpIn;
            }
            @Override
            public void run() {
                byte[] buffer = new byte[1];
                String message = "";
                while (true) {

                    try {
                        int readByte = mmInStream.read();
                        if (readByte == -1) {
                            Log.e(TAG, "Discarting message: " + message);
                            message = "";
                            continue;
                        }
                        buffer[0] = (byte) readByte;

                        if (readByte == 0) { // see terminateFlag on write method
                            onReceive(message);
                            message = "";
                        } else { // a message has been recieved
                            message += new String(buffer, 0, 1);
                        }
                    } catch (IOException e) {
                        Log.e(TAG, " ** disconnected ** ", e);
                    }

                    mBtDeviceAddresses.remove(address);
                    mBtSockets.remove(address);
                    mBtConnectionThreads.remove(address);
                }
            }
        }

        /**
         * @param receiveMessage
         */
        private void onReceive(String receiveMessage) {
            if (receiveMessage != null && receiveMessage.length() > 0) {
                Log.i(TAG, " $$$$ " + receiveMessage + " $$$$ ");
                Bundle bundle = new Bundle();
                bundle.putString("msg", receiveMessage);
                Message message = new Message();
                message.what = 1;
                message.setData(bundle);
                handler.sendMessage(message);
            }
        }

        /**
         * @param device
         * @param uuidToTry
         * @return
         */
        private BluetoothSocket getConnectedSocket(BluetoothDevice device, UUID uuidToTry) {
            BluetoothSocket myBtSocket;
            try {
                myBtSocket = device.createRfcommSocketToServiceRecord(uuidToTry);
                myBtSocket.connect();
                return myBtSocket;
            } catch (IOException e) {
                Log.e(TAG, "IOException in getConnectedSocket", e);
            }
            return null;
        }

        private void connect(BluetoothDevice device) {
            BluetoothSocket myBtSocket = null;
            String address = device.getAddress();
            BluetoothDevice remoteDevice = mBluetoothAdapter.getRemoteDevice(address);
            // Try to get connection through all uuids available
            for (int i = 0; i < mUuidList.size() && myBtSocket == null; i++) {
                // Try to get the socket 2 times for each uuid of the list
                for (int j = 0; j < 2 && myBtSocket == null; j++) {
                    Log.d(TAG, " ** Trying connection..." + j + " with " + device.getName() + ", uuid " + i + "...** ");
                    myBtSocket = getConnectedSocket(remoteDevice, mUuidList.get(i));
                    if (myBtSocket == null) {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            Log.e(TAG, "InterruptedException in connect", e);
                        }
                    }
                }
            }
            if (myBtSocket == null) {
                Log.e(TAG, " ** Could not connect ** ");
                return;
            }
            Log.d(TAG, " ** Connection established with " + device.getName() +"! ** ");
            mBtSockets.put(address, myBtSocket);
            mBtDeviceAddresses.add(address);
            Thread mBluetoohConnectionThread = new Thread(new BluetoohConnection(myBtSocket));
            mBluetoohConnectionThread.start();
            mBtConnectionThreads.put(address, mBluetoohConnectionThread);

        }

        public void bluetoothBroadcastMessage(String message) {
            //send message to all except Id
            for (int i = 0; i < mBtDeviceAddresses.size(); i++) {
                sendMessage(mBtDeviceAddresses.get(i), message);
            }
        }

        private void sendMessage(String destination, String message) {
            BluetoothSocket myBsock = mBtSockets.get(destination);
            if (myBsock != null) {
                try {
                    OutputStream outStream = myBsock.getOutputStream();
                    final int pieceSize = 16;
                    for (int i = 0; i < message.length(); i += pieceSize) {
                        byte[] send = message.substring(i,
                                Math.min(message.length(), i + pieceSize)).getBytes();
                        outStream.write(send);
                    }
                    // we put at the end of message a character to sinalize that message
                    // was finished
                    byte[] terminateFlag = new byte[1];
                    terminateFlag[0] = 0; // ascii table value NULL (code 0)
                    outStream.write(new byte[1]);
                } catch (IOException e) {
                    Log.d(TAG, "line 278", e);
                }
            }
        }

    }

Your main activity should be as follow :

package com.example.gaby.coordinatorv1;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button discoveryButton;
    private Button messageButton;

    private Piconet piconet;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        piconet = new Piconet(getApplicationContext());

        messageButton = (Button) findViewById(R.id.messageButton);
        messageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                piconet.bluetoothBroadcastMessage("Hello World---*Gaby Bou Tayeh*");
            }
        });

        discoveryButton = (Button) findViewById(R.id.discoveryButton);
        discoveryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                piconet.startPiconet();
            }
        });

    }

}

And here's the XML Layout :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Button
    android:id="@+id/discoveryButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Discover"
    />

<Button
    android:id="@+id/messageButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Send message"
    />

Do not forget to add the following permissions to your Manifest File :

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

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

MVC - Set selected value of SelectList

You can use below method, which is quite simple.

new SelectList(items, "ID", "Name",items.Select(x=> x.Id).FirstOrDefault());

This will auto-select the first item in your list. You can modify the above query by adding a where clause.

Update Top 1 record in table sql server

It also works well ...

Update t
Set t.TIMESTAMP2 = '2013-12-12 15:40:31.593'
From
(
    Select Top 1 TIMESTAMP2
    From TX_Master_PCBA
    Where SERIAL_NO IN ('0500030309')
    Order By TIMESTAMP2 DESC
) t

Switch statement fallthrough in C#?

You can 'goto case label' http://www.blackwasp.co.uk/CSharpGoto.aspx

The goto statement is a simple command that unconditionally transfers the control of the program to another statement. The command is often criticised with some developers advocating its removal from all high-level programming languages because it can lead to spaghetti code. This occurs when there are so many goto statements or similar jump statements that the code becomes difficult to read and maintain. However, there are programmers who point out that the goto statement, when used carefully, provides an elegant solution to some problems...

ionic 2 - Error Could not find an installed version of Gradle either in Android Studio

There is a problem with cordova version 6.4.0 and android 6.2.1 .so,please try with below compatible versions

cordova version must be 6.4.0

sudo npm install -g [email protected]

Install android in your project

sudo cordova platform add [email protected]

 or

sudo ionic platform add [email protected]

How to ensure a <select> form field is submitted when it is disabled?

I use next code for disable options in selections

<select class="sel big" id="form_code" name="code" readonly="readonly">
   <option value="user_played_game" selected="true">1 Game</option>
   <option value="coins" disabled="">2 Object</option>
   <option value="event" disabled="">3 Object</option>
   <option value="level" disabled="">4 Object</option>
   <option value="game" disabled="">5 Object</option>
</select>

// Disable selection for options
$('select option:not(:selected)').each(function(){
 $(this).attr('disabled', 'disabled');
});

No submodule mapping found in .gitmodule for a path that's not a submodule

The folder mapping can be found in .git/modules folder (each has config file with reference to its worktree), so make sure these folders correspond to the configuration in .gitmodules and .git/config.

So .gitmodules has the correct path:

[submodule "<path>"]
  path = <path>
  url = [email protected]:foo/bar.git

and in .git/modules/<path>/config in [core] section you've the right path to your <path>, e.g.

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
  worktree = ../../../<path>

If the right folder in .git/modules is missing, then you've to go to your submodule dir and try git reset HEAD --hard or git checkout master -f. If this won't help, you probably want to remove all the references to the broken submodule and add it again, then see: Rename a git submodule.

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

I faced the same issue, I tried the below solution and it worked for me In Android SDK Manager Window, click on Tools->Options-> under "Others", check "Force https://... sources to be fetched using http://..."

Associating enums with strings in C#

I like to use properties in a class instead of methods, since they look more enum-like.

Here's a example for a Logger:

public class LogCategory
{
    private LogCategory(string value) { Value = value; }

    public string Value { get; set; }

    public static LogCategory Trace   { get { return new LogCategory("Trace"); } }
    public static LogCategory Debug   { get { return new LogCategory("Debug"); } }
    public static LogCategory Info    { get { return new LogCategory("Info"); } }
    public static LogCategory Warning { get { return new LogCategory("Warning"); } }
    public static LogCategory Error   { get { return new LogCategory("Error"); } }
}

Pass in type-safe string values as a parameter:

public static void Write(string message, LogCategory logCategory)
{
    var log = new LogEntry { Message = message };
    Logger.Write(log, logCategory.Value);
}

Usage:

Logger.Write("This is almost like an enum.", LogCategory.Info);

jQuery adding 2 numbers from input fields

There are two way that you can add two number in jQuery

First way:

var x = parseInt(a) + parseInt(b);
alert(x);

Second Way:

var x = parseInt(a+2);
alert(x);

Now come your question

var a = parseInt($("#a").val()); 
var b = parseInt($("#b").val());
alert(a+b);

clear javascript console in Google Chrome

On the Mac you can also use ?+K just like in Terminal.

How to add elements of a Java8 stream into an existing List

You just have to refer your original list to be the one that the Collectors.toList() returns.

Here's a demo:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Reference {

  public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    System.out.println(list);

    // Just collect even numbers and start referring the new list as the original one.
    list = list.stream()
               .filter(n -> n % 2 == 0)
               .collect(Collectors.toList());
    System.out.println(list);
  }
}

And here's how you can add the newly created elements to your original list in just one line.

List<Integer> list = ...;
// add even numbers from the list to the list again.
list.addAll(list.stream()
                .filter(n -> n % 2 == 0)
                .collect(Collectors.toList())
);

That's what this Functional Programming Paradigm provides.

Placeholder Mixin SCSS/CSS

This is for shorthand syntax

=placeholder
  &::-webkit-input-placeholder
    @content
  &:-moz-placeholder
    @content
  &::-moz-placeholder
    @content
  &:-ms-input-placeholder
    @content

use it like

input
  +placeholder
    color: red

How to round up integer division and have int result in Java?

this might be helpfull,, Subtract the remainder to the legnth and make it a divisible number and then divide it with 153

int r=message.length()%153;       //Calculate the remainder by %153
return (message.length()-r)/153;  // find the pages by adding the remainder and 
                                  //then divide by 153 

Calling one Activity from another in Android

I have implemented this way and it works.It is much easier than all that is reported.

We have two activities : one is the main and another is the secondary.

In secondary activity, which is where we want to end the main activity , define the following variable:

public static Activity ACTIVIDAD;

And then the following method:

public static void enlaceActividadPrincipal(Activity actividad) 
{
    tuActividad.ACTIVIDAD=actividad;
}

Then, in your main activity from the onCreate method , you make the call:

    actividadSecundaria.enlaceActividadPrincipal(this);

Now, you're in control. Now, from your secondary activity, you can complete the main activity. Finish calling the function, like this:

ACTIVIDAD.finish();

android: how to change layout on button click?

You wanted to change the layout at runtime on button click. But that is not possible and as it has been rightly stated above, you need to restart the activity. You will come across a similar problem when u plan on changing the theme based on user's selection but it will not reflect in runtime. You will have to restart the activity.

Session TimeOut in web.xml

If you don't want a timeout happening for some purpose:

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

Should result in no timeout at all -> infinite

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

jQuery.ajax handling continue responses: "success:" vs ".done"?

If you need async: false in your ajax, you should use success instead of .done. Else you better to use .done. This is from jQuery official site:

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().

Windows 7, 64 bit, DLL problems

Installation of SQL Server Management Studio 2014 on a freshly installed Windows 7 resolved this problem at our client after a two-day ridiculous battle.

How do I get the YouTube video ID from a URL?

/^.*(youtu.be\/|v\/|e\/|u\/\w+\/|embed\/|v=)([^#\&\?]*).*/

Tested on:

  • http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
  • http://www.youtube.com/embed/0zM3nApSvMg?rel=0
  • http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
  • http://www.youtube.com/watch?v=0zM3nApSvMg
  • http://youtu.be/0zM3nApSvMg
  • http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
  • http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/KdwsulMb8EQ
  • http://youtu.be/dQw4w9WgXcQ
  • http://www.youtube.com/embed/dQw4w9WgXcQ
  • http://www.youtube.com/v/dQw4w9WgXcQ
  • http://www.youtube.com/e/dQw4w9WgXcQ
  • http://www.youtube.com/watch?v=dQw4w9WgXcQ
  • http://www.youtube.com/?v=dQw4w9WgXcQ
  • http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
  • http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
  • http://www.youtube.com/user/IngridMichaelsonVEVO#p/u/11/KdwsulMb8EQ
  • http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0

Inspired by this other answer.

ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)

In Matrix terms, the number of elements always has to equal the product of the number of rows and columns. In this particular case, the condition is not matching.

What does "both" mean in <div style="clear:both">

Description of the possible values:

  • left: No floating elements allowed on the left side
  • right: No floating elements allowed on the right side
  • both: No floating elements allowed on either the left or the right side
  • none: Default. Allows floating elements on both sides
  • inherit: Specifies that the value of the clear property should be inherited from the parent element

Source: w3schools.com

How to retrieve field names from temporary table (SQL Server 2008)

select * 
from tempdb.INFORMATION_SCHEMA.COLUMNS
where table_name like '#MyTempTable%'

val() vs. text() for textarea

The best way to set/get the value of a textarea is the .val(), .value method.

.text() internally uses the .textContent (or .innerText for IE) method to get the contents of a <textarea>. The following test cases illustrate how text() and .val() relate to each other:

var t = '<textarea>';
console.log($(t).text('test').val());             // Prints test
console.log($(t).val('too').text('test').val());  // Prints too
console.log($(t).val('too').text());              // Prints nothing
console.log($(t).text('test').val('too').val());  // Prints too

console.log($(t).text('test').val('too').text()); // Prints test

The value property, used by .val() always shows the current visible value, whereas text()'s return value can be wrong.

Adding close button in div to close the box

jQuery("#your_div_id").remove(); will completely remove the corresponding elements from the HTML DOM. So if you want to show the div on another event without a refresh, it will not be possible to retrieve the removed elements back unless you use AJAX.

jQuery("#your_div_id").toggle("slow"); will also could make unexpected results. As an Example when you select some element on your div which generates another div with a close button(which uses the same close functionality just as your previous div) it could make undesired behaviour.

So without using AJAX, a good solution for the close button would be as follows

HTML____________

<div id="your_div_id">
<span class="close_div" onclick="close_div(1)">&#10006</span>
</div>

JQUERY__________

function close_div(id) {
    if(id === 1) {
        jQuery("#your_div_id").hide();
    }
}

Now you can show the div, when another event occures as you wish... :-)

Scroll to bottom of div?

You can try the code below:

function scrollToBottom (id) {
   var div = document.getElementById(id);
   div.scrollTop = div.scrollHeight - div.clientHeight;
}

To perform a smooth scroll with JQuery:

function scrollSmoothToBottom (id) {
   var div = document.getElementById(id);
   $('#' + id).animate({
      scrollTop: div.scrollHeight - div.clientHeight
   }, 500);
}

See the example on JSFiddle

Here's why this works:

enter image description here

Ref: scrollTop, scrollHeight, clientHeight

Regular expression for not allowing spaces in the input field

This will help to find the spaces in the beginning, middle and ending:

var regexp = /\s/g

Set a request header in JavaScript

W3C Spec on setrequestheader.

The brief points:

If the request header had already been set, then the new value MUST be concatenated to the existing value using a U+002C COMMA followed by a U+0020 SPACE for separation.

UAs MAY give the User-Agent header an initial value, but MUST allow authors to append values to it.

However - After searching through the framework XHR in jQuery they don't allow you to change the User-Agent or Referer headers. The closest thing:

// Set header so the called script knows that it's an XMLHttpRequest
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

I'm leaning towards the opinion that what you want to do is being denied by a security policy in FF - if you want to pass some custom Referer type header you could always do:

xhr.setRequestHeader('X-Alt-Referer', 'http://www.google.com');

jQuery Mobile Page refresh mechanism

This answer did the trick for me http://view.jquerymobile.com/master/demos/faq/injected-content-is-not-enhanced.php.

In the context of a multi-pages template, I modify the content of a <div id="foo">...</div> in a Javascript 'pagebeforeshow' handler and trigger a refresh at the end of the script:

$(document).bind("pagebeforeshow", function(event,pdata) {
  var parsedUrl = $.mobile.path.parseUrl( location.href );
  switch ( parsedUrl.hash ) {
    case "#p_02":
      ... some modifications of the content of the <div> here ...
      $("#foo").trigger("create");
    break;
  }
});

How to change date format in JavaScript

Using the Datejs library, this can be as easy as:

Date.parse("05/05/2010").toString("MMMM yyyy");
//          parse date             convert to
//                                 string with
//                                 custom format

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

I've been struggling with this myself and I finally believe I have it figured out. It's incredible how many failed answers there are on this question

All you have to do is remove the padding from all your .col elements, and remove the padding also from the .container-fluid.

I did this in my own project a little sloppily by adding the following to my css file:

.col, col-10, col-12, col-2, col-6 {
    padding: 0!important;
}

.container-fluid {
    padding: 0!important;
}

I just have the different col sizes there to account for all the different col sizes I'm using. I'm confident there is a cleaner way to write the css but this illustrates the end result.

Android Spinner: Get the selected item change event

By default, you will get the first item of the spinner array through

value = spinner.getSelectedItem().toString();

whenever you selected the value in the spinner this will give you the selected value

if you want the position of the selected item then do it like that

pos = spinner.getSelectedItemPosition();

the above two answers are for without applying listener

JSON to pandas DataFrame

Once you have the flattened DataFrame obtained by the accepted answer, you can make the columns a MultiIndex ("fancy multiline header") like this:

df.columns = pd.MultiIndex.from_tuples([tuple(c.split('.')) for c in df.columns])

How to increment variable under DOS?

I realize you've found another answer - but the fact is that your original code was nearly correct but for a syntax error.

Your code contained the line

set /A COUNTER=%COUNTER%+1

and the syntax that would work is simply...

set /A COUNTER=COUNTER+1

See http://ss64.com/nt/set.html for all the details on the SET command. I just thought I'd add this clarification for anyone else who doesn't have the option of using FreeDOS.

Duplicate keys in .NET dictionaries?

Do you mean congruent and not an actual duplicate? Otherwise a hashtable wouldn't be able to work.

Congruent means that two separate keys can hash to the equivalent value, but the keys aren't equal.

For example: say your hashtable's hash function was just hashval = key mod 3. Both 1 and 4 map to 1, but are different values. This is where your idea of a list comes into play.

When you need to lookup 1, that value is hashed to 1, the list is traversed until the Key = 1 is found.

If you allowed for duplicate keys to be inserted, you wouldn't be able to differentiate which keys map to which values.

How to convert View Model into JSON object in ASP.NET MVC?

@Html.Raw(Json.Encode(object)) can be used to convert the View Modal Object to JSON

How to Validate a DateTime in C#?

private void btnEnter_Click(object sender, EventArgs e)
{
    maskedTextBox1.Mask = "00/00/0000";
    maskedTextBox1.ValidatingType = typeof(System.DateTime);
    //if (!IsValidDOB(maskedTextBox1.Text)) 
    if (!ValidateBirthday(maskedTextBox1.Text))
        MessageBox.Show(" Not Valid");
    else
        MessageBox.Show("Valid");
}
// check date format dd/mm/yyyy. but not if year < 1 or > 2013.
public static bool IsValidDOB(string dob)
{ 
    DateTime temp;
    if (DateTime.TryParse(dob, out temp))
        return (true);
    else 
        return (false);
}
// checks date format dd/mm/yyyy and year > 1900!.
protected bool ValidateBirthday(String date)
{
    DateTime Temp;
    if (DateTime.TryParse(date, out Temp) == true &&
        Temp.Year > 1900 &&
       // Temp.Hour == 0 && Temp.Minute == 0 &&
        //Temp.Second == 0 && Temp.Millisecond == 0 &&
        Temp > DateTime.MinValue)
        return (true);
    else
        return (false);
}

Printing out a linked list using toString

As has been pointed out in some other answers and comments, what you are missing here is a call to the JVM System class to print out the string generated by your toString() method.

LinkedList myLinkedList = new LinkedList();
System.out.println(myLinkedList.toString());

This will get the job done, but I wouldn't recommend doing it that way. If we take a look at the javadocs for the Object class, we find this description for toString():

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The emphasis added there is my own. You are creating a string that contains the entire state of the linked list, which somebody using your class is probably not expecting. I would recommend the following changes:

  1. Add a toString() method to your LinkedListNode class.
  2. Update the toString() method in your LinkedList class to be more concise.
  3. Add a new method called printList() to your LinkedList class that does what you are currently expecting toString() to do.

In LinkedListNode:

public String toString(){
   return "LinkedListNode with data: " + getData();
}

In LinkedList:

public int size(){
    int currentSize = 0;
    LinkedListNode current = head;
    while(current != null){
        currentSize = currentSize + 1;
        current = current.getNext();
    }

    return currentSize;
}

public String toString(){
    return "LinkedList with " + size() + "elements.";
}

public void printList(){
    System.out.println("Contents of " + toString());

    LinkedListNode current = head;
    while(current != null){
        System.out.println(current.toString());
        current = current.getNext();
    }

}

What are the lengths of Location Coordinates, latitude and longitude?

Google Maps actually uses signed values to represent the position:

  • Latitude : max/min 90.0000000 to -90.0000000

  • Longitude : max/min 180.0000000 to -180.0000000

So if you want to work with Coordinates in your projects you would need DECIMAL(10,7) ie. for SQL.

Python safe method to get value of nested dictionary

A recursive solution. It's not the most efficient but I find it a bit more readable than the other examples and it doesn't rely on functools.

def deep_get(d, keys):
    if not keys or d is None:
        return d
    return deep_get(d.get(keys[0]), keys[1:])

Example

d = {'meta': {'status': 'OK', 'status_code': 200}}
deep_get(d, ['meta', 'status_code'])     # => 200
deep_get(d, ['garbage', 'status_code'])  # => None

A more polished version

def deep_get(d, keys, default=None):
    """
    Example:
        d = {'meta': {'status': 'OK', 'status_code': 200}}
        deep_get(d, ['meta', 'status_code'])          # => 200
        deep_get(d, ['garbage', 'status_code'])       # => None
        deep_get(d, ['meta', 'garbage'], default='-') # => '-'
    """
    assert type(keys) is list
    if d is None:
        return default
    if not keys:
        return d
    return deep_get(d.get(keys[0]), keys[1:], default)

Error 5 : Access Denied when starting windows service

Computer -> Manage -> Service -> [your service] properties. Then the the tab with the account information. Play with those settings, like run the service with administrator account or so.

That did it for me.

EDIT: What also can be the problem is that, most services are run as LOCAL SERVICE or LOCAL SYSTEM accounts. Now when you run C:/my-admin-dir/service.exe with those accounts but they are not allowed to execute anything in that directory, you will get error 5. So locate the executable of the service, RMB the directory -> Properties -> Security and make sure that the account the service is run with, is in the list of users that are alloewd to have full control over the directory.

How to set max width of an image in CSS

Given your container width 600px.

If you want only bigger images than that to fit inside, add: CSS:

#ImageContainer img {
    max-width: 600px;
}

If you want ALL images to take the avaiable (600px) space:

#ImageContainer img {
    width: 600px;
}

Using a .php file to generate a MySQL dump

None of the above codes worked for me. I am using windows. Below Code worked for me...

$sql = "SELECT * FROM  $tableName WHERE yourclause";
$result = $conn->query($sql);


if($result){

        if ($result->num_rows > 0) {

            $myfile = fopen("daily_events_$district.sql", "w") or die("Unable to open file!");

            while($row = $result->fetch_assoc()) {  

                $rowToString = implode("','",$row);
                $writeToFile = "INSERT INTO $tableName VALUES('$rowToString');". PHP_EOL;
                fwrite($myfile,$writeToFile);
            }
            echo "File saved successfully";
        }
    } else {
        echo "No result found";
    }

This will save file in your project folder according to your query whatever data you want.

Performing user authentication in Java EE / JSF using j_security_check

After searching the Web and trying many different ways, here's what I'd suggest for Java EE 6 authentication:

Set up the security realm:

In my case, I had the users in the database. So I followed this blog post to create a JDBC Realm that could authenticate users based on username and MD5-hashed passwords in my database table:

http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html

Note: the post talks about a user and a group table in the database. I had a User class with a UserType enum attribute mapped via javax.persistence annotations to the database. I configured the realm with the same table for users and groups, using the userType column as the group column and it worked fine.

Use form authentication:

Still following the above blog post, configure your web.xml and sun-web.xml, but instead of using BASIC authentication, use FORM (actually, it doesn't matter which one you use, but I ended up using FORM). Use the standard HTML , not the JSF .

Then use BalusC's tip above on lazy initializing the user information from the database. He suggested doing it in a managed bean getting the principal from the faces context. I used, instead, a stateful session bean to store session information for each user, so I injected the session context:

 @Resource
 private SessionContext sessionContext;

With the principal, I can check the username and, using the EJB Entity Manager, get the User information from the database and store in my SessionInformation EJB.

Logout:

I also looked around for the best way to logout. The best one that I've found is using a Servlet:

 @WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
 public class LogoutServlet extends HttpServlet {
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   HttpSession session = request.getSession(false);

   // Destroys the session for this user.
   if (session != null)
        session.invalidate();

   // Redirects back to the initial page.
   response.sendRedirect(request.getContextPath());
  }
 }

Although my answer is really late considering the date of the question, I hope this helps other people that end up here from Google, just like I did.

Ciao,

Vítor Souza

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

You can use date to get time and date of a day:

[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013

Also hwclock would do:

[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST  -0.516080 seconds

For customized output, you can either redirect the output of date to something like awk, or write your own program to do that.

Remember to put your own executable scripts/binary into your PATH (e.g. /usr/bin) to make it invokable anywhere.

Visual Studio replace tab with 4 spaces?

For Visual Studio 2019 users:

By the comment under accepted answer, link:

Well... This is "almost" still the same in VS 2019... if you already done that and seems not to work, go to: Tools > Options, and then Text Editor > Advanced > Uncheck "Use adaptive formatting" as seen here

Limit file format when using <input type="file">?

Yes, you are right. It's impossible with HTML. User will be able to pick whatever file he/she wants.

You could write a piece of JavaScript code to avoid submitting a file based on its extension. But keep in mind that this by no means will prevent a malicious user to submit any file he/she really wants to.

Something like:

function beforeSubmit()
{
    var fname = document.getElementById("ifile").value;
    // check if fname has the desired extension
    if (fname hasDesiredExtension) {
        return true;
    } else {
        return false;
    }
}

HTML code:

<form method="post" onsubmit="return beforeSubmit();">
    <input type="file" id="ifile" name="ifile"/>
</form>

newline in <td title="">

This should now work with Internet Explorer, Firefox v12+ and Chrome 28+

<img src="'../images/foo.gif'" 
  alt="line 1&#013;line 2" title="line 1&#013;line 2">

Try a JavaScript tooltip library for a better result, something like OverLib.

Plot a bar using matplotlib using a dictionary

Why not just:

import seaborn as sns

sns.barplot(list(D.keys()), list(D.values()))

Get current batchfile directory

Within your .bat file:

set mypath=%cd%

You can now use the variable %mypath% to reference the file path to the .bat file. To verify the path is correct:

@echo %mypath%

For example, a file called DIR.bat with the following contents

set mypath=%cd%
@echo %mypath%
Pause

run from the directory g:\test\bat will echo that path in the DOS command window.

Argument of type 'X' is not assignable to parameter of type 'X'

you just use variable type any and remove these types of problem.

error code :

  let accessToken = res;
  localStorage.setItem(LocalStorageConstants.TOKEN_KEY, accessToken);

given error Argument of type '{}' is not assignable to parameter of type 'string'.

success Code :

  var accessToken:any = res;
  localStorage.setItem(LocalStorageConstants.TOKEN_KEY, accessToken);

we create var type variable then use variable type any and resolve this issue.

any = handle any type of value so that remove error.

WHERE clause on SQL Server "Text" data type

If you can't change the datatype on the table itself to use varchar(max), then change your query to this:

SELECT *
FROM   [Village]
WHERE  CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'

Make xargs handle filenames that contain spaces

Alternative solutions can be helpful...

You can also add a null character to the end of your lines using Perl, then use the -0 option in xargs. Unlike the xargs -d '\n' (in approved answer) - this works everywhere, including OS X.

For example, to recursively list (execute, move, etc.) MPEG3 files which may contain spaces or other funny characters - I'd use:

find . | grep \.mp3 | perl -ne 'chop; print "$_\0"' | xargs -0  ls

(Note: For filtering, I prefer the easier-to-remember "| grep" syntax to "find's" --name arguments.)

How do I make a https post in Node Js without any third party module?

For example, like this:

const querystring = require('querystring');
const https = require('https');

var postData = querystring.stringify({
    'msg' : 'Hello World!'
});

var options = {
  hostname: 'posttestserver.com',
  port: 443,
  path: '/post.php',
  method: 'POST',
  headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Content-Length': postData.length
     }
};

var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});

req.write(postData);
req.end();

add allow_url_fopen to my php.ini using .htaccess

If your host is using suPHP, you can try creating a php.ini file in the same folder as the script and adding:

allow_url_fopen = On

(you can determine this by creating a file and checking which user it was created under: if you, it's suPHP, if "apache/nobody" or not you, then it's a normal PHP mode. You can also make a script

<?php
echo `id`;
?>

To give the same information, assuming shell_exec is not a disabled function)

Find an object in SQL Server (cross-database)

sp_MSforeachdb 'select db_name(), * From ?..sysobjects where xtype in (''U'', ''P'') And name = ''ObjectName'''

Instead of 'ObjectName' insert object you are looking for. First column will display name of database where object is located at.

Why do we usually use || over |? What is the difference?

usually I use when there is pre increment and post increment operator. Look at the following code:

package ocjpPractice;
/**
 * @author tithik
 *
 */
public class Ex1 {

    public static void main(String[] args) {
    int i=10;
    int j=9;
    int x=10;
    int y=9;
    if(i==10 | ++i>j){
        System.out.println("it will print in first if");  
        System.out.println("i is: "+i);
    }

    if(x==10 ||++x>y){
        System.out.println("it will print in second if");   
        System.out.println("x is: "+x);
    }
    }
}

output:

it will print in first if
i is: 11

it will print in second if
x is: 10

both if blocks are same but result is different. when there is |, both the conditions will be evaluated. But if it is ||, it will not evaluate second condition as the first condition is already true.

jQuery DatePicker with today as maxDate

If you're using bootstrap 3 date time picker, try this:

$('.selector').datetimepicker({ maxDate: $.now() });

How to combine paths in Java?

I know its a long time since Jon's original answer, but I had a similar requirement to the OP.

By way of extending Jon's solution I came up with the following, which will take one or more path segments takes as many path segments that you can throw at it.

Usage

Path.combine("/Users/beardtwizzle/");
Path.combine("/", "Users", "beardtwizzle");
Path.combine(new String[] { "/", "Users", "beardtwizzle", "arrayUsage" });

Code here for others with a similar problem

public class Path {
    public static String combine(String... paths)
    {
        File file = new File(paths[0]);

        for (int i = 1; i < paths.length ; i++) {
            file = new File(file, paths[i]);
        }

        return file.getPath();
    }
}

Plot a horizontal line using matplotlib

You're looking for axhline (a horizontal axis line). For example, the following will give you a horizontal line at y = 0.5:

import matplotlib.pyplot as plt
plt.axhline(y=0.5, color='r', linestyle='-')
plt.show()

sample figure

How do I test a single file using Jest?

You could use the file name with npm test --:

npm test -- fileName.jsx 

Editing legend (text) labels in ggplot

The legend titles can be labeled by specific aesthetic.

This can be achieved using the guides() or labs() functions from ggplot2 (more here and here). It allows you to add guide/legend properties using the aesthetic mapping.

Here's an example using the mtcars data set and labs():

ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
  geom_point() +
  labs(x="miles per gallon", y="displacement", size="horsepower", 
       col="# of cylinders", shape="# of gears")

enter image description here

Answering the OP's question using guides():

# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")

# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) + 
  geom_point(size=5) +
  labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
  scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
  theme_bw() +
  guides(color=guide_legend("my title"))  # add guide properties by aesthetic

enter image description here

Difference Between Select and SelectMany

SelectMany flattens queries that return lists of lists. For example

public class PhoneNumber
{
    public string Number { get; set; }
}

public class Person
{
    public IEnumerable<PhoneNumber> PhoneNumbers { get; set; }
    public string Name { get; set; }
}

IEnumerable<Person> people = new List<Person>();

// Select gets a list of lists of phone numbers
IEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);

// SelectMany flattens it to just a list of phone numbers.
IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);

// And to include data from the parent in the result: 
// pass an expression to the second parameter (resultSelector) in the overload:
var directory = people
   .SelectMany(p => p.PhoneNumbers,
               (parent, child) => new { parent.Name, child.Number });

Live Demo on .NET Fiddle

C# testing to see if a string is an integer?

If you just want to check type of passed variable, you could probably use:

    var a = 2;
    if (a is int)
    {
        //is integer
    }
    //or:
    if (a.GetType() == typeof(int))
    {
        //is integer
    }

Breaking up long strings on multiple lines in Ruby without stripping newlines

Maybe this is what you're looking for?

string = "line #1"\
         "line #2"\
         "line #3"

p string # => "line #1line #2line #3"

How do I split a string into an array of characters?

To support emojis use this

('Dragon ').split(/(?!$)/u);

=> ['D', 'r', 'a', 'g', 'o', 'n', ' ', '']

How to replace multiple substrings of a string?

I don't know about speed but this is my workaday quick fix:

reduce(lambda a, b: a.replace(*b)
    , [('o','W'), ('t','X')] #iterable of pairs: (oldval, newval)
    , 'tomato' #The string from which to replace values
    )

... but I like the #1 regex answer above. Note - if one new value is a substring of another one then the operation is not commutative.

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

How do I print a datetime in the local timezone?

I believe the best way to do this is to use the LocalTimezone class defined in the datetime.tzinfo documentation (goto http://docs.python.org/library/datetime.html#tzinfo-objects and scroll down to the "Example tzinfo classes" section):

Assuming Local is an instance of LocalTimezone

t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=utc)
local_t = t.astimezone(Local)

then str(local_t) gives:

'2009-07-11 04:44:59.193982+10:00'

which is what you want.

(Note: this may look weird to you because I'm in New South Wales, Australia which is 10 or 11 hours ahead of UTC)

Sending and receiving data over a network using TcpClient

Be warned - this is a very old and cumbersome "solution".

By the way, you can use serialization technology to send strings, numbers or any objects which are support serialization (most of .NET data-storing classes & structs are [Serializable]). There, you should at first send Int32-length in four bytes to the stream and then send binary-serialized (System.Runtime.Serialization.Formatters.Binary.BinaryFormatter) data into it.

On the other side or the connection (on both sides actually) you definetly should have a byte[] buffer which u will append and trim-left at runtime when data is coming.

Something like that I am using:

namespace System.Net.Sockets
{
    public class TcpConnection : IDisposable
    {
        public event EvHandler<TcpConnection, DataArrivedEventArgs> DataArrive = delegate { };
        public event EvHandler<TcpConnection> Drop = delegate { };

        private const int IntSize = 4;
        private const int BufferSize = 8 * 1024;

        private static readonly SynchronizationContext _syncContext = SynchronizationContext.Current;
        private readonly TcpClient _tcpClient;
        private readonly object _droppedRoot = new object();
        private bool _dropped;
        private byte[] _incomingData = new byte[0];
        private Nullable<int> _objectDataLength;

        public TcpClient TcpClient { get { return _tcpClient; } }
        public bool Dropped { get { return _dropped; } }

        private void DropConnection()
        {
            lock (_droppedRoot)
            {
                if (Dropped)
                    return;

                _dropped = true;
            }

            _tcpClient.Close();
            _syncContext.Post(delegate { Drop(this); }, null);
        }

        public void SendData(PCmds pCmd) { SendDataInternal(new object[] { pCmd }); }
        public void SendData(PCmds pCmd, object[] datas)
        {
            datas.ThrowIfNull();
            SendDataInternal(new object[] { pCmd }.Append(datas));
        }
        private void SendDataInternal(object data)
        {
            if (Dropped)
                return;

            byte[] bytedata;

            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();

                try { bf.Serialize(ms, data); }
                catch { return; }

                bytedata = ms.ToArray();
            }

            try
            {
                lock (_tcpClient)
                {
                    TcpClient.Client.BeginSend(BitConverter.GetBytes(bytedata.Length), 0, IntSize, SocketFlags.None, EndSend, null);
                    TcpClient.Client.BeginSend(bytedata, 0, bytedata.Length, SocketFlags.None, EndSend, null);
                }
            }
            catch { DropConnection(); }
        }
        private void EndSend(IAsyncResult ar)
        {
            try { TcpClient.Client.EndSend(ar); }
            catch { }
        }

        public TcpConnection(TcpClient tcpClient)
        {
            _tcpClient = tcpClient;
            StartReceive();
        }

        private void StartReceive()
        {
            byte[] buffer = new byte[BufferSize];

            try
            {
                _tcpClient.Client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, DataReceived, buffer);
            }
            catch { DropConnection(); }
        }

        private void DataReceived(IAsyncResult ar)
        {
            if (Dropped)
                return;

            int dataRead;

            try { dataRead = TcpClient.Client.EndReceive(ar); }
            catch
            {
                DropConnection();
                return;
            }

            if (dataRead == 0)
            {
                DropConnection();
                return;
            }

            byte[] byteData = ar.AsyncState as byte[];
            _incomingData = _incomingData.Append(byteData.Take(dataRead).ToArray());
            bool exitWhile = false;

            while (exitWhile)
            {
                exitWhile = true;

                if (_objectDataLength.HasValue)
                {
                    if (_incomingData.Length >= _objectDataLength.Value)
                    {
                        object data;
                        BinaryFormatter bf = new BinaryFormatter();

                        using (MemoryStream ms = new MemoryStream(_incomingData, 0, _objectDataLength.Value))
                            try { data = bf.Deserialize(ms); }
                            catch
                            {
                                SendData(PCmds.Disconnect);
                                DropConnection();
                                return;
                            }

                        _syncContext.Post(delegate(object T)
                        {
                            try { DataArrive(this, new DataArrivedEventArgs(T)); }
                            catch { DropConnection(); }
                        }, data);

                        _incomingData = _incomingData.TrimLeft(_objectDataLength.Value);
                        _objectDataLength = null;
                        exitWhile = false;
                    }
                }
                else
                    if (_incomingData.Length >= IntSize)
                    {
                        _objectDataLength = BitConverter.ToInt32(_incomingData.TakeLeft(IntSize), 0);
                        _incomingData = _incomingData.TrimLeft(IntSize);
                        exitWhile = false;
                    }
            }
            StartReceive();
        }


        public void Dispose() { DropConnection(); }
    }
}

That is just an example, you should edit it for your use.

Nexus 7 not visible over USB via "adb devices" from Windows 7 x64

PDANet driver was the only solution for me to successfully connect to Google Galaxy Nexus 4.2.1 on Windows 7 x64 which was rejecting/ignoring official USB drivers from the latest 4.2 ADK (revision 7) - http://junefabrics.com/android/index.php

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Just to add to yamen's answer, which is perfect for images but not so much for text.

If you are trying to use this to scale text, like say a Word document (which is in this case in bytes from Word Interop), you will need to make a few modifications or you will get giant bars on the side.

May not be perfect but works for me!

using (MemoryStream ms = new MemoryStream(wordBytes))
{
    float width = 3840;
    float height = 2160;
    var brush = new SolidBrush(Color.White);

    var rawImage = Image.FromStream(ms);
    float scale = Math.Min(width / rawImage.Width, height / rawImage.Height);
    var scaleWidth  = (int)(rawImage.Width  * scale);
    var scaleHeight = (int)(rawImage.Height * scale);
    var scaledBitmap = new Bitmap(scaleWidth, scaleHeight);

    Graphics graph = Graphics.FromImage(scaledBitmap);
    graph.InterpolationMode = InterpolationMode.High;
    graph.CompositingQuality = CompositingQuality.HighQuality;
    graph.SmoothingMode = SmoothingMode.AntiAlias;
    graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
    graph.DrawImage(rawImage, new Rectangle(0, 0 , scaleWidth, scaleHeight));

    scaledBitmap.Save(fileName, ImageFormat.Png);
    return scaledBitmap;
}

Printing one character at a time from a string, using the while loop

Python Code:

for s in myStr:
        print s

OR

for i in xrange(len(myStr)):
    print myStr[i]

"getaddrinfo failed", what does that mean?

The problem, in my case, was that some install at some point defined an environment variable http_proxy on my machine when I had no proxy.

Removing the http_proxy environment variable fixed the problem.

Exclude all transitive dependencies of a single dependency

Use the latest maven in your classpath.. It will remove the duplicate artifacts and keep the latest maven artifact..

Google Maps API v2: How to make markers clickable?

All markers in Google Android Maps Api v2 are clickable. You don't need to set any additional properties to your marker. What you need to do - is to register marker click callback to your googleMap and handle click within callback:

public class MarkerDemoActivity extends android.support.v4.app.FragmentActivity
    implements OnMarkerClickListener
{
    private Marker myMarker;    

    private void setUpMap()
    {
        .......
        googleMap.setOnMarkerClickListener(this);

        myMarker = googleMap.addMarker(new MarkerOptions()
                    .position(latLng)
                    .title("My Spot")
                    .snippet("This is my spot!")
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        ......
    }

    @Override
    public boolean onMarkerClick(final Marker marker) {

        if (marker.equals(myMarker)) 
        {
            //handle click here
        }
    }
}

here is a good guide on google about marker customization

Redeploy alternatives to JRebel

You might want to take a look this:

HotSwap support: the object-oriented architecture of the Java HotSpot VM enables advanced features such as on-the-fly class redefinition, or "HotSwap". This feature provides the ability to substitute modified code in a running application through the debugger APIs. HotSwap adds functionality to the Java Platform Debugger Architecture, enabling a class to be updated during execution while under the control of a debugger. It also allows profiling operations to be performed by hotswapping in versions of methods in which profiling code has been inserted.

For the moment, this only allows for newly compiled method body to be redeployed without restarting the application. All you have to do is to run it with a debugger. I tried it in Eclipse and it works splendidly.

Also, as Emmanuel Bourg mentioned in his answer (JEP 159), there is hope to have support for the addition of supertypes and the addition and removal of methods and fields.

Reference: Java Whitepaper 135217: Reliability, Availability and Serviceability

How to use shell commands in Makefile

Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.

If you're on GNU Make, use the := assignment instead of =. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.

FILES := $(shell ...)  # expand now; FILES is now the result of $(shell ...)

FILES = $(shell ...)   # expand later: FILES holds the syntax $(shell ...)

If you use the = assignment, it means that every single occurrence of $(FILES) will be expanding the $(shell ...) syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

I know this is an old question, but I wanted to add ServiceCapture to the list, for those who may come across this.

I've been using ServiceCapture for about 4 years and love it. It's not free, but it is a great tool and not very expensive. If you debug a lot of Flash or AJAX apps it is invaluable.

Oracle: Import CSV file

Another solution you can use is SQL Developer.

With it, you have the ability to import from a csv file (other delimited files are available).

Just open the table view, then:

  • choose actions
  • import data
  • find your file
  • choose your options.

You have the option to have SQL Developer do the inserts for you, create an sql insert script, or create the data for a SQL Loader script (have not tried this option myself).

Of course all that is moot if you can only use the command line, but if you are able to test it with SQL Developer locally, you can always deploy the generated insert scripts (for example).

Just adding another option to the 2 already very good answers.

jQuery click events not working in iOS

You should bind the tap event, the click does not exist on mobile safari or in the UIWbview. You can also use this polyfill ,to avoid the 300ms delay when a link is touched.

SQL ROWNUM how to return rows between a specific range

SELECT  *
FROM    (
        SELECT  q.*, rownum rn
        FROM    (
                SELECT  *
                FROM    maps006
                ORDER BY
                        id
                ) q
        )
WHERE   rn BETWEEN 50 AND 100

Note the double nested view. ROWNUM is evaluated before ORDER BY, so it is required for correct numbering.

If you omit ORDER BY clause, you won't get consistent order.

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

How do I get the title of the current active window using c#?

Based on GetForegroundWindow function | Microsoft Docs:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowTextLength(IntPtr hWnd);

private string GetCaptionOfActiveWindow()
{
    var strTitle = string.Empty;
    var handle = GetForegroundWindow();
    // Obtain the length of the text   
    var intLength = GetWindowTextLength(handle) + 1;
    var stringBuilder = new StringBuilder(intLength);
    if (GetWindowText(handle, stringBuilder, intLength) > 0)
    {
        strTitle = stringBuilder.ToString();
    }
    return strTitle;
}

It supports UTF8 characters.

How to resize a custom view programmatically?

this.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, theSizeIWant));

Problem solved!

NOTE: Be sure to use the parent Layout's LayoutParams. Mine is LinearLayout.LayoutParams!

Undo git update-index --assume-unchanged <file>

Nothing here that is not covered. But would like to add my 2 cents. At times, I run a build and it changes lot of files and then I want to work on something, so this command really helps me a lot.

git update-index --assume-unchanged `git status | grep modified | sed 's|modified:||g'| xargs`

Hope someone else find it useful as well.

Char array declaration and initialization in C

This is another C example of where the same syntax has different meanings (in different places). While one might be able to argue that the syntax should be different for these two cases, it is what it is. The idea is that not that it is "not allowed" but that the second thing means something different (it means "pointer assignment").

Check if String / Record exists in DataTable

You can loop over each row of the DataTable and check the value.

I'm a big fan of using a foreach loop when using IEnumerables. Makes it very simple and clean to look at or process each row

DataTable dtPs = // ... initialize your DataTable
foreach (DataRow dr in dtPs.Rows)
{
    if (dr["item_manuf_id"].ToString() == "some value")
    {
        // do your deed
    }
}

Alternatively you can use a PrimaryKey for your DataTable. This helps in various ways, but you often need to define one before you can use it.

An example of using one if at http://msdn.microsoft.com/en-us/library/z24kefs8(v=vs.80).aspx

DataTable workTable = new DataTable("Customers");

// set constraints on the primary key
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;

workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));

// set primary key
workTable.PrimaryKey = new DataColumn[] { workTable.Columns["CustID"] };

Once you have a primary key defined and data populated, you can use the Find(...) method to get the rows that match your primary key.

Take a look at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx

DataRow drFound = dtPs.Rows.Find("some value");
if (drFound["item_manuf_id"].ToString() == "some value")
{
    // do your deed
}

Finally, you can use the Select() method to find data within a DataTable also found at at http://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.80).aspx.

String sExpression = "item_manuf_id == 'some value'";
DataRow[] drFound;
drFound = dtPs.Select(sExpression);

foreach (DataRow dr in drFound)
{
    // do you deed. Each record here was already found to match your criteria
}

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

Is there a function to split a string in PL/SQL?

You have to roll your own. E.g.,

/* from :http://www.builderau.com.au/architect/database/soa/Create-functions-to-join-and-split-strings-in-Oracle/0,339024547,339129882,00.htm

select split('foo,bar,zoo') from dual;
select * from table(split('foo,bar,zoo'));

pipelined function is SQL only (no PL/SQL !)
*/

create or replace type split_tbl as table of varchar2(32767);
/
show errors

create or replace function split
(
    p_list varchar2,
    p_del varchar2 := ','
) return split_tbl pipelined
is
    l_idx    pls_integer;
    l_list    varchar2(32767) := p_list;
    l_value    varchar2(32767);
begin
    loop
        l_idx := instr(l_list,p_del);
        if l_idx > 0 then
            pipe row(substr(l_list,1,l_idx-1));
            l_list := substr(l_list,l_idx+length(p_del));

        else
            pipe row(l_list);
            exit;
        end if;
    end loop;
    return;
end split;
/
show errors;

/* An own implementation. */

create or replace function split2(
  list in varchar2,
  delimiter in varchar2 default ','
) return split_tbl as
  splitted split_tbl := split_tbl();
  i pls_integer := 0;
  list_ varchar2(32767) := list;
begin
  loop
    i := instr(list_, delimiter);
    if i > 0 then
      splitted.extend(1);
      splitted(splitted.last) := substr(list_, 1, i - 1);
      list_ := substr(list_, i + length(delimiter));
    else
      splitted.extend(1);
      splitted(splitted.last) := list_;
      return splitted;
    end if;
  end loop;
end;
/
show errors

declare
  got split_tbl;

  procedure print(tbl in split_tbl) as
  begin
    for i in tbl.first .. tbl.last loop
      dbms_output.put_line(i || ' = ' || tbl(i));
    end loop;
  end;

begin
  got := split2('foo,bar,zoo');
  print(got);
  print(split2('1 2 3 4 5', ' '));
end;
/

Angular - res.json() is not a function

Don't need to use this method:

 .map((res: Response) => res.json() );

Just use this simple method instead of the previous method. hopefully you'll get your result:

.map(res => res );

"While .. End While" doesn't work in VBA?

While constructs are terminated not with an End While but with a Wend.

While counter < 20
    counter = counter + 1
Wend

Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.

Also in the VBA help file:

Tip The Do...Loop statement provides a more structured and flexible way to perform looping.

How do I parse a string with a decimal point to a double?

Instead of having to specify a locale in all parses, I prefer to set an application wide locale, although if string formats are not consistent across the app, this might not work.

CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("pt-PT");
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("pt-PT");

Defining this at the begining of your application will make all double parses expect a comma as the decimal delimiter. You can set an appropriate locale so that the decimal and thousands separator fits the strings you are parsing.

jQuery plugin returning "Cannot read property of undefined"

I had same problem with 'parallax' plugin. I changed jQuery librery version to *jquery-1.6.4* from *jquery-1.10.2*. And error cleared.

Edit and Continue: "Changes are not allowed when..."

I had this annoying issue since I upgraded my VS 2019 to 16.4.3 and caused me a lot of headache.
Finally I solved the problem this way:

1. Stop Debugging
2. Select the solution from "Solution Explorer"
3. In the Properties window change the "Active config" Property From "Release|Any CPU" To "Debug|Any CPU"
4. In Debug > Options > General Check the Edit and Continue checkbox

That worked for me, and hope it works for you too.

How to use SVN, Branch? Tag? Trunk?

I thinks there is two way about committing frequency:

  1. Commit very often, for each implemented method, small part of code, etc.
  2. Commit only completed parts of code, like modules, etc.

I prefer the first one - because using source control system is very useful not only for project or company, the first of all it's useful for the developer. For me the best feature is to roll back all code while searching the best assigned task implementation.

IntelliJ - Convert a Java project/module into a Maven project/module

I want to add the important hint that converting a project like this can have side effects which are noticeable when you have a larger project. This is due the fact that Intellij Idea (2017) takes some important settings only from the pom.xml then which can lead to some confusion, following sections are affected at least:

  1. Annotation settings are changed for the modules
  2. Compiler output path is changed for the modules
  3. Resources settings are ignored totally and only taken from pom.xml
  4. Module dependencies are messed up and have to checked
  5. Language/Encoding settings are changed for the modules

All these points need review and adjusting but after this it works like charm.

Further more unfortunately there is no sufficient pom.xml template created, I have added an example which might help to solve most problems.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Name</groupId>
<artifactId>Artifact</artifactId>
<version>4.0</version>
<properties>
    <!-- Generic properties -->
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
    <!--All dependencies to put here, including module dependencies-->
</dependencies>
<build>
    <directory>${project.basedir}/target</directory>
    <outputDirectory>${project.build.directory}/classes</outputDirectory>
    <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
    <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
    <testSourceDirectory> ${project.basedir}/src/test/java</testSourceDirectory>

    <resources>
        <resource>
            <directory>${project.basedir}/src/main/java</directory>
            <excludes>
                <exclude>**/*.java</exclude>
            </excludes>
        </resource>
        <resource>
            <directory>${project.basedir}/src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <annotationProcessors/>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Edit 2019:

  • Added recursive resource scan
  • Added directory specification which might be important to avoid confusion of IDEA recarding the content root structure

Batch Files - Error Handling

I guess this feature was added since the OP but for future reference errors that would output in the command window can be redirected to a file independent of the standard output

command 1> file - Write the standard output of command to file

command 2> file - Write the standard error of command to file

Android Pop-up message

If you want a Popup that closes automatically, you should look for Toasts. But if you want a dialog that the user has to close first before proceeding, you should look for a Dialog.

For both approaches it is possible to read a text file with the text you want to display. But you could also hardcode the text or use R.String to set the text.

Changing precision of numeric column in Oracle

By setting the scale, you decrease the precision. Try NUMBER(16,2).

How do I call a function inside of another function?

_x000D_
_x000D_
function function_one() {_x000D_
    function_two(); // considering the next alert, I figured you wanted to call function_two first_x000D_
    alert("The function called 'function_one' has been called.");_x000D_
}_x000D_
_x000D_
function function_two() {_x000D_
    alert("The function called 'function_two' has been called.");_x000D_
}_x000D_
_x000D_
function_one();
_x000D_
_x000D_
_x000D_

A little bit more context: this works in JavaScript because of a language feature called "variable hoisting" - basically, think of it like variable/function declarations are put at the top of the scope (more info).

Perl: Use s/ (replace) and return new string

If you have Perl 5.14 or greater, you can use the /r option with the substitution operator to perform non-destructive substitution:

print "bla: ", $myvar =~ s/a/b/r, "\n";

In earlier versions you can achieve the same using a do() block with a temporary lexical variable, e.g.:

print "bla: ", do { (my $tmp = $myvar) =~ s/a/b/; $tmp }, "\n";

iOS 7 status bar overlapping UI

Some of the above answers will give you a black bar on top if you set your screen bound 20px, other will keep reduce your webview screen if you use webview.frame.size.height -20px; Try this one then, it works on any ios and no need to change css, put in inside

- (void)webViewDidFinishLoad:(UIWebView*)theWebView {

//is it IOS7 and up

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {

//get the device screen size

    CGRect screenBounds = [[UIScreen mainScreen] bounds];

//reduce the height by 20px

    int x= screenBounds.size.height -20;

//set the webview top pos 20px so it is under the status bar and reduce the size by 20px

    [theWebView setFrame:CGRectMake(0, 20, theWebView.frame.size.width, x )];

}

Disable nginx cache for JavaScript files

Remember set sendfile off; or cache headers doesn't work. I use this snipped:

location / {

        index index.php index.html index.htm;
        try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular

        #.s. kill cache. use in dev
        sendfile off;
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
        proxy_no_cache 1;
        proxy_cache_bypass 1; 
    }

ASP.net Getting the error "Access to the path is denied." while trying to upload files to my Windows Server 2008 R2 Web server

the problem might be that networkservice has no read rights

salution:

rightclick your upload folder -> poperty's -> security ->Edit -> add -> type :NETWORK SERVICE -> check box full control allow-> press ok or apply

Execute jar file with multiple classpath libraries from command prompt

Using java 1.7, on UNIX -

java -cp myjar.jar:lib/*:. mypackage.MyClass

On Windows you need to use ';' instead of ':' -

java -cp myjar.jar;lib/*;. mypackage.MyClass

PYTHONPATH on Linux

  1. PYTHONPATH is an environment variable
  2. Yes (see https://unix.stackexchange.com/questions/24802/on-which-unix-distributions-is-python-installed-as-part-of-the-default-install)
  3. /usr/lib/python2.7 on Ubuntu
  4. you shouldn't install packages manually. Instead, use pip. When a package isn't in pip, it usually has a setuptools setup script which will install the package into the proper location (see point 3).
  5. if you use pip or setuptools, then you don't need to set PYTHONPATH explicitly

If you look at the instructions for pyopengl, you'll see that they are consistent with points 4 and 5.

Twitter bootstrap collapse: change display of toggle button

I guess you could look inside your downloaded code where exactly there is a + sign (but this might not be very easy).

What I'd do? I'd find the class/id of the DOM elements that contain the + sign (suppose it's ".collapsible", and with Javascript (actually jQuery):

<script>
     $(document).ready(function() {
         var content=$(".collapsible").html().replace("+", "-");
         $(".collapsible").html(content));
     });
</script>

edit Alright... Sorry I haven't looked at the bootstrap code... but I guess it works with something like slideToggle, or slideDown and slideUp... Imagine it's a slideToggle for the elements of class .collapsible, which reveal contents of some .info elements. Then:

         $(".collapsible").click(function() { 
             var content=$(".collapsible").html();
             if $(this).next().css("display") === "none") { 
                 $(".collapsible").html(content.replace("+", "-"));
             }
             else $(".collapsible").html(content.replace("-", "+"));
         });

This seems like the opposite thing to do, but since the actual animation runs in parallel, you will check css before animation, and that's why you need to check if it's visible (which will mean it will be hidden once the animation is complete) and then set the corresponding + or -.

jquery clone div and append it after specific div

This works great if a straight copy is in order. If the situation calls for creating new objects from templates, I usually wrap the template div in a hidden storage div and use jquery's html() in conjunction with clone() applying the following technique:

<style>
#element-storage {
    display: none;
    top: 0;
    right: 0;
    position: fixed;
    width: 0;
    height: 0;
}
</style>

<script>
$("#new-div").append($("#template").clone().html(function(index, oldHTML){ 
    // .. code to modify template, e.g. below:
    var newHTML = "";
    newHTML = oldHTML.replace("[firstname]", "Tom");
    newHTML = newHTML.replace("[lastname]", "Smith");
    // newHTML = newHTML.replace(/[Example Replace String]/g, "Replacement"); // regex for global replace
    return newHTML;
}));
</script>

<div id="element-storage">
  <div id="template">
    <p>Hello [firstname] [lastname]</p>
  </div>
</div>

<div id="new-div">

</div>

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

OP's question: "How do I convert a string to a byte array in .NET (C#)?" [sic]

You can use the following code:

static byte[] ConvertString (string s) {
    return new byte[0];
}

As a benefit, encoding does not matter! Oh wait, this is an ecoding... it's just trivial and highly lossy.

PHP equivalent of .NET/Java's toString()

Another option is to use the built in settype function:

<?php
$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo is now 5   (integer)
settype($bar, "string");  // $bar is now "1" (string)
?>

This actually performs a conversion on the variable unlike typecasting and allows you to have a general way of converting to multiple types.

Best programming based games

My favourite was PCRobots back in the 90's - you could write your bot in pretty much any language that could compile a DOS executable. Still runs quite nicely in DOSBox :)

Checking if a number is a prime number in Python

a = input('inter a number: ')
s = 0
if a == 1:  
    print a, 'is a prime'

else : 

    for i in range (2, a ):

        if a%i == 0:
            print a,' is not a prime number'
            s = 'true'
            break

    if s == 0 : print a,' is a prime number'

it worked with me just fine :D

Test process.env with Jest

You can use the setupFiles feature of the Jest configuration. As the documentation said that,

A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.

  1. npm install dotenv dotenv that uses to access environment variable.

  2. Create your .env file to the root directory of your application and add this line into it:

    #.env
    APP_PORT=8080
    
  3. Create your custom module file as its name being someModuleForTest.js and add this line into it:

    // someModuleForTest.js
    require("dotenv").config()
    
  4. Update your jest.config.js file like this:

    module.exports = {
      setupFiles: ["./someModuleForTest"]
    }
    
  5. You can access an environment variable within all test blocks.

    test("Some test name", () => {
      expect(process.env.APP_PORT).toBe("8080")
    })
    

get UTC time in PHP

You can use following to get UTC time:

date_default_timezone_set('Asia/Calcutta');

$current_date = date("Y/m/d g:i A");

$ist_date = DateTime::createFromFormat(
                        '"Y/m/d g:i A"',
                        $current_date,
                        new DateTimeZone('Asia/Calcutta')
                    );

$utc_date = clone $ist_date;
$utc_date->setTimeZone(new DateTimeZone('UTC'));

echo 'UTC:  ' . $utc_date->format('Y-m-d g:i A');

Metadata file '.dll' could not be found

I got the same error "Metadata file '.dll' could not be found", and I tried several things described above, but the reason for the error was that I was referencing third-party DLL file which was targeting a .NET version higher that my project target .NET version. So the solution was to change the target framework of my project.

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

it is very simple....

[in make file]

==== 1 ===================

OBJS = ....\

version.o <<== add to your obj lists

==== 2 ===================

DATE = $(shell date +'char szVersionStr[20] = "%Y-%m-%d %H:%M:%S";') <<== add

all:version $(ProgramID) <<== version add at first

version: <<== add

echo '$(DATE)' > version.c  <== add ( create version.c file)

[in program]

=====3 =============

extern char szVersionStr[20];

[ using ]

=== 4 ====

printf( "Version: %s\n", szVersionStr );

Returning anonymous type in C#

In C# 7 we can use tuples to accomplish this:

public List<(int SomeVariable, string AnotherVariable)> TheMethod(SomeParameter)
{
  using (MyDC TheDC = new MyDC())
  {
     var TheQueryFromDB = (....
                       select new { SomeVariable = ....,
                                    AnotherVariable = ....}
                       ).ToList();

      return TheQueryFromDB
                .Select(s => (
                     SomeVariable = s.SomeVariable, 
                     AnotherVariable = s.AnotherVariable))
                 .ToList();
  }
}

You might need to install System.ValueTuple nuget package though.

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

My situation was with Visual Studio 2019 and we have both C# and C++ code. Not sure what I screwed up, but the solution was to change from auto to Native as the C# code was working.

Debug -> Attach to Process... and where it says Attach to: select native code (in my case). Find the process in question and voila.

Error: EACCES: permission denied

Just change the owner of the global node_modules directory to be your user:

sudo chown -R $USER:$GROUP /usr/local/lib/node_modules

PHP is_numeric or preg_match 0-9 validation

is_numeric checks whether it is any sort of number, while your regex checks whether it is an integer, possibly with leading 0s. For an id, stored as an integer, it is quite likely that we will want to not have leading 0s. Following Spudley's answer, we can do:

/^[1-9][0-9]*$/

However, as Spudley notes, the resulting string may be too large to be stored as a 32-bit or 64-bit integer value. The maximum value of an signed 32-bit integer is 2,147,483,647 (10 digits), and the maximum value of an signed 64-bit integer is 9,223,372,036,854,775,807 (19 digits). However, many 10 and 19 digit integers are larger than the maximum 32-bit and 64-bit integers respectively. A simple regex-only solution would be:

/^[1-9][0-9]{0-8}$/ 

or

/^[1-9][0-9]{0-17}$/

respectively, but these "solutions" unhappily restrict each to 9 and 19 digit integers; hardly a satisfying result. A better solution might be something like:

$expr = '/^[1-9][0-9]*$/';
if (preg_match($expr, $id) && filter_var($id, FILTER_VALIDATE_INT)) {
    echo 'ok';
} else {
    echo 'nok';
}

How to iterate over rows in a DataFrame in Pandas

cs95 shows that Pandas vectorization far outperforms other Pandas methods for computing stuff with dataframes.

I wanted to add that if you first convert the dataframe to a NumPy array and then use vectorization, it's even faster than Pandas dataframe vectorization, (and that includes the time to turn it back into a dataframe series).

If you add the following functions to cs95's benchmark code, this becomes pretty evident:

def np_vectorization(df):
    np_arr = df.to_numpy()
    return pd.Series(np_arr[:,0] + np_arr[:,1], index=df.index)

def just_np_vectorization(df):
    np_arr = df.to_numpy()
    return np_arr[:,0] + np_arr[:,1]

Enter image description here

Generating CSV file for Excel, how to have a newline inside a value

In Excel 365 while importing the file:

Data -> From Text/CSV: From Text/CSV

-> Select File > Transform Data:

Select File -> Transform Data

In the Power Query Editor, right hand side at "Query Settings", under APPLIED STEPS, on "Source" row, click the "Settings icon"

Source settings icon

-> In the line break dropdown select Ignore line breaks inside quotes.

Ignore quoted line breaks

Then press OK -> File -> Close & Load

What's default HTML/CSS link color?

As of HTML5, the foreground colors of hyperlinks, among other things, are on track for standardization in the form of guidelines for expected default rendering behavior. In particular, taken from the section Phrasing content, the recommended default colors for unvisited and visited hyperlinks are the following:

:link { color: #0000EE; }
:visited { color: #551A8B; }

Notice that there is no recommended default for active hyperlinks (:link:active, :visited:active), however.

You can use these default colors and reasonably expect them to work. But keep in mind that a browser is free to ignore any or all of these guidelines, as it is never required to follow them. It is, however, recommended for a consistent user experience across browsers (which is how "expected" is defined in this context), so chances are that these colors will correspond to the defaults for most browsers. At worst, they still serve as reasonable approximations of the actual values.

In particular, the default unvisited and visited link colors in the latest versions of Firefox and Chrome are consistent with the above guidelines, but recent versions of IE report different values: unvisited links are rgb(0, 102, 204), or #0066CC, and visited links are rgb(128, 0, 128), or #800080. Older versions of Firefox (and possibly Safari/Chrome) had different defaults as well. Those are older versions, however; the main outlier today that I am aware of is IE. No word yet on whether this will change in Project Spartan — currently it still reflects the same values as the latest version of IE.

If you are looking for a standardized color scheme that is used by all browsers rather than suggested by HTML5, then there isn't one. Neither is there a way to revert to a browser's default value for a particular property on a particular element using pure CSS. You will have to either use the colors suggested by HTML5, or devise your own color scheme and use that instead. Either of these options will take precedence over a browser's defaults, regardless of browser.

If in doubt, you can always use the about:blank technique I described before to sniff out the default colors, as it remains applicable today. You can use this to sniff the active link color in all browsers, for example; in the latest version of Firefox (29 as of this update), it's rgb(238, 0, 0), or #EE0000.

PowerShell To Set Folder Permissions

Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it. This is actually working:

$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl

Named tuple and default values for optional keyword arguments

The answer by jterrace to use recordtype is great, but the author of the library recommends to use his namedlist project, which provides both mutable (namedlist) and immutable (namedtuple) implementations.

from namedlist import namedtuple
>>> Node = namedtuple('Node', ['val', ('left', None), ('right', None)])
>>> Node(3)
Node(val=3, left=None, right=None)
>>> Node(3, 'L')
Node(val=3, left=L, right=None)

Why is this HTTP request not working on AWS Lambda?

Of course, I was misunderstanding the problem. As AWS themselves put it:

For those encountering nodejs for the first time in Lambda, a common error is forgetting that callbacks execute asynchronously and calling context.done() in the original handler when you really meant to wait for another callback (such as an S3.PUT operation) to complete, forcing the function to terminate with its work incomplete.

I was calling context.done way before any callbacks for the request fired, causing the termination of my function ahead of time.

The working code is this:

var http = require('http');

exports.handler = function(event, context) {
  console.log('start request to ' + event.url)
  http.get(event.url, function(res) {
    console.log("Got response: " + res.statusCode);
    context.succeed();
  }).on('error', function(e) {
    console.log("Got error: " + e.message);
    context.done(null, 'FAILURE');
  });

  console.log('end request to ' + event.url);
}

Update: starting 2017 AWS has deprecated the old Nodejs 0.10 and only the newer 4.3 run-time is now available (old functions should be updated). This runtime introduced some changes to the handler function. The new handler has now 3 parameters.

function(event, context, callback)

Although you will still find the succeed, done and fail on the context parameter, AWS suggest to use the callback function instead or null is returned by default.

callback(new Error('failure')) // to return error
callback(null, 'success msg') // to return ok

Complete documentation can be found at http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html

Difference between F5, Ctrl + F5 and click on refresh button?

F5 triggers a standard reload.

Ctrl + F5 triggers a forced reload. This causes the browser to re-download the page from the web server, ensuring that it always has the latest copy.

Unlike with F5, a forced reload does not display a cached copy of the page.

Python loop that also accesses previous and next values

Very C/C++ style solution:

    foo = 5
    objectsList = [3, 6, 5, 9, 10]
    prev = nex = 0
    
    currentIndex = 0
    indexHigher = len(objectsList)-1 #control the higher limit of list
    
    found = False
    prevFound = False
    nexFound = False
    
    #main logic:
    for currentValue in objectsList: #getting each value of list
        if currentValue == foo:
            found = True
            if currentIndex > 0: #check if target value is in the first position   
                prevFound = True
                prev = objectsList[currentIndex-1]
            if currentIndex < indexHigher: #check if target value is in the last position
                nexFound = True
                nex = objectsList[currentIndex+1]
            break #I am considering that target value only exist 1 time in the list
        currentIndex+=1
    
    if found:
        print("Value %s found" % foo)
        if prevFound:
            print("Previous Value: ", prev)
        else:
            print("Previous Value: Target value is in the first position of list.")
        if nexFound:
            print("Next Value: ", nex)
        else:
            print("Next Value: Target value is in the last position of list.")
    else:
        print("Target value does not exist in the list.")

Converting char* to float or double

Code posted by you is correct and should have worked. But check exactly what you have in the char*. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL. Check what you have in the char* against maximum values that float and double can represent on your computer.

Check this page for strtod reference and this page for atof reference.

I have tried the example you provided in both Windows and Linux and it worked fine.

What is the difference between tree depth and height?

I wanted to make this post because I'm an undergrad CS student and more and more we use OpenDSA and other open source textbooks. It seems like from the top rated answer that the way height and depth is being taught has changed from one generation to the next, and I'm posting this so everyone is aware that this discrepancy now exists and hopefully won't cause bugs in any programs! Thanks.

From the OpenDSA Data Structures & Algos book:

If n1, n2,...,nk is a sequence of nodes in the tree such that ni is the parent of ni+1 for 1<=i<k, then this sequence is called a path from n1 to nk. The length of the path is k-1. If there is a path from node R to node M, then R is an ancestor of M, and M is a descendant of R. Thus, all nodes in the tree are descendants of the root of the tree, while the root is the ancestor of all nodes. The depth of a node M in the tree is the length of the path from the root of the tree to M. The height of a tree is one more than the depth of the deepest node in the tree. All nodes of depth d are at level d in the tree. The root is the only node at level 0, and its depth is 0.

Figure 7.2.1

Figure 7.2.1: A binary tree. Node A is the root. Nodes B and C are A's children. Nodes B and D together form a subtree. Node B has two children: Its left child is the empty tree and its right child is D. Nodes A, C, and E are ancestors of G. Nodes D, E, and F make up level 2 of the tree; node A is at level 0. The edges from A to C to E to G form a path of length 3. Nodes D, G, H, and I are leaves. Nodes A, B, C, E, and F are internal nodes. The depth of I is 3. The height of this tree is 4.

Delete topic in Kafka 0.8.1.1

The command:

bin/kafka-topics.sh --delete --zookeeper localhost:2181 --topic test

unfortunately only marks topic for deletion.

Deletion does not happen.

That makes troubles, while testing any scripts, which prepares Kafka configuration.

Connected threads:

Append TimeStamp to a File Name

You can use below instead:

DateTime.Now.Ticks

The system cannot find the file specified. in Visual Studio

I resolved this issue after deleting folder where I was trying to add the file in Visual Studio. Deleted folder from window explorer also. After doing all this, successfully able to add folder and file.

How can I change the size of a Bootstrap checkbox?

I have used this library with sucess

http://plugins.krajee.com/checkbox-x

It requires jQuery and bootstrap 3.x

Download the zip here: https://github.com/kartik-v/bootstrap-checkbox-x/zipball/master

Put the contents of the zip in a folder within your project

Pop the needed libs in your header

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="path/to/css/checkbox-x.min.css" media="all" rel="stylesheet" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="path/to/js/checkbox-x.min.js" type="text/javascript"></script>

Add the data controls to the element using the data-size="xl" to change the size as shown here http://plugins.krajee.com/cbx-sizes-demo

<label for="element_id">CheckME</label>
<input type="checkbox" name="my_element" id="element_id" value="1" data-toggle="checkbox-x" data-three-state="false" data-size="xl"/>

There are numerous other features as well if you browse the plugin site.

Xcode "Device Locked" When iPhone is unlocked

This happens at times while using Xcode 9.

Screenshot

There are multiple solution to this as mentioned below :

Note : Make sure that your device is not locked when Xcode is trying to install app.

Solution 1 :

i. Disconnect device and connect again

Solution 2 :

i. Restart you device

Solution 3 :

i. Disconnect device

ii. Quit Xcode (Shortcut key : cmd + Q)

iii. Open your project

iv. Clean project (Shortcut key : cmd + shift + K)

v. Now connect device

vi. Run your project

For me Solution 3 worked perfectly

location.host vs location.hostname and cross-browser compatibility?

host just includes the port number if there is one specified. If there is no port number specifically in the URL, then it returns the same as hostname. You pick whether you care to match the port number or not. See https://developer.mozilla.org/en/window.location for more info.

I would assume you want hostname to just get the site name.

Typescript interface default values

Default values to an interface are not possible because interfaces only exists at compile time.

Alternative solution:

You could use a factory method for this which returns an object which implements the XI interface.

Example:

class AnotherType {}

interface IX {
    a: string,
    b: any,
    c: AnotherType | null
}

function makeIX (): IX {
    return {
    a: 'abc',
    b: null,
    c: null
    }
}

const x = makeIX();

x.a = 'xyz';
x.b = 123;
x.c = new AnotherType();

The only thing I changed with regard to your example is made the property c both AnotherType | null. Which will be necessary to not have any compiler errors (This error was also present in your example were you initialized null to property c).

What is AndroidX?

AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.

After hours of struggling, I solved it by including the following within app/build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Put these flags in your gradle.properties

android.enableJetifier=true
android.useAndroidX=true

Changes in gradle:

implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha04'

When migrating on Android studio, the app/gradle file is automatically updated with the correction library impleemntations from the standard library

Refer to: https://developer.android.com/jetpack/androidx/migrate

How can I hide or encrypt JavaScript code?

The only safe way to protect your code is not giving it away. With client deployment, there is no avoiding the client having access to the code.

So the short answer is: You can't do it

The longer answer is considering flash or Silverlight. Although I believe silverlight will gladly give away it's secrets with reflector running on the client.

I'm not sure if something simular exists with the flash platform.

Using a custom typeface in Android

Is there a way to do this from the XML?

No, sorry. You can only specify the built-in typefaces through XML.

Is there a way to do it from code in one place, to say that the whole application and all the components should use the custom typeface instead of the default one?

Not that I am aware of.

There are a variety of options for these nowadays:

  • Font resources and backports in the Android SDK, if you are using appcompat

  • Third-party libraries for those not using appcompat, though not all will support defining the font in layout resources

Python - How to sort a list of lists by the fourth element in each list?

Use sorted() with a key as follows -

>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

The lambda returns the fourth element of each of the inner lists and the sorted function uses that to sort those list. This assumes that int(elem) will not fail for the list.

Or use itemgetter (As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)

>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

Jmeter - get current date and time

JMeter is using java SimpleDateFormat

For UTC with timezone use this

${__time(yyyy-MM-dd'T'hh:mm:ssX)}

android.content.Context.getPackageName()' on a null object reference

In my case the error occurred inside a Fragment on this line:

Intent intent = new Intent(getActivity(), SecondaryActivity.class);

It happened when I double clicked on an item which triggered the code above so two SecondaryActivity.class activities were launched at the same time, one on top of the other. I closed the top SecondaryActivity.class activity by pressing back button which triggered a call to getActivity() in the SecondaryActivity.class which came to foreground. The call to getActivity() returned null. It's some kind of weird Android bug so it usually should not happen. You can block the clicks after the user clicked once.

Is there a decorator to simply cache function return values?

Starting from Python 3.2 there is a built-in decorator:

@functools.lru_cache(maxsize=100, typed=False)

Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.

Example of an LRU cache for computing Fibonacci numbers:

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> print([fib(n) for n in range(16)])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> print(fib.cache_info())
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)

If you are stuck with Python 2.x, here's a list of other compatible memoization libraries:

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

You can divide column of dtype timedelta by np.timedelta64(1, 'D'), but output is not int, but float, because NaN values:

df_test['Difference'] = df_test['Difference'] / np.timedelta64(1, 'D')
print (df_test)
  First_Date Second Date  Difference
0 2016-02-09  2015-11-19        82.0
1 2016-01-06  2015-11-30        37.0
2        NaT  2015-12-04         NaN
3 2016-01-06  2015-12-08        29.0
4        NaT  2015-12-09         NaN
5 2016-01-07  2015-12-11        27.0
6        NaT  2015-12-12         NaN
7        NaT  2015-12-14         NaN
8 2016-01-06  2015-12-14        23.0
9        NaT  2015-12-15         NaN

Frequency conversion.

C# difference between == and Equals()

I would add that if you cast your object to a string then it will work correctly. This is why the compiler will give you a warning saying:

Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'

How to run a script at a certain time on Linux?

Cron is good for something that will run periodically, like every Saturday at 4am. There's also anacron, which works around power shutdowns, sleeps, and whatnot. As well as at.

But for a one-off solution, that doesn't require root or anything, you can just use date to compute the seconds-since-epoch of the target time as well as the present time, then use expr to find the difference, and sleep that many seconds.

Disable building workspace process in Eclipse

For anyone running into a problem where build automatically is unchecked but the project is still building. Make sure your project isn't deployed to the server in the server tab and told to stay synchronous.

Build android release apk on Phonegap 3.x CLI

Following up to @steven-anderson you can also configure passwords inside the ant.properties, so the process can be fully automated

so if you put in platform\android\ant.properties the following

key.store=../../yourCertificate.jks
key.store.password=notSoSecretPassword
key.alias=userAlias
key.alias.password=notSoSecretPassword

NULL vs nullptr (Why was it replaced?)

nullptr is always a pointer type. 0 (aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:

f(int);
f(foo *);

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Get all dates between two dates in SQL Server

create procedure [dbo].[p_display_dates](@startdate datetime,@enddate datetime)
as
begin
    declare @mxdate datetime
    declare @indate datetime
    create table #daterange (dater datetime)
    insert into #daterange values (@startdate)
    set @mxdate = (select MAX(dater) from #daterange)
    while @mxdate < @enddate
        begin
            set @indate = dateadd(day,1,@mxdate)
            insert into #daterange values (@indate)
            set @mxdate = (select MAX(dater) from #daterange)
        end
    select * from #daterange
end

How to terminate a process in vbscript

Dim shll : Set shll = CreateObject("WScript.Shell")
Set Rt = shll.Exec("Notepad") : wscript.sleep 4000 : Rt.Terminate

Run the process with .Exec.

Then wait for 4 seconds.

After that kill this process.

How might I extract the property values of a JavaScript object into an array?

In case you use d3. you can do d3.values(dataObject) which will give

enter image description here

How to reference a local XML Schema file correctly?

Add one more slash after file:// in the value of xsi:schemaLocation. (You have two; you need three. Think protocol://host/path where protocol is 'file' and host is empty here, yielding three slashes in a row.) You can also eliminate the double slashes along the path. I believe that the double slashes help with file systems that allow spaces in file and directory names, but you wisely avoided that complication in your path naming.

xsi:schemaLocation="http://www.w3schools.com file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd"

Still not working? I suggest that you carefully copy the full file specification for the XSD into the address bar of Chrome or Firefox:

file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd

If the XSD does not display in the browser, delete all but the last component of the path (email.xsd) and see if you can't display the parent directory. Continue in this manner, walking up the directory structure until you discover where the path diverges from the reality of your local filesystem.

If the XSD does displayed in the browser, state what XML processor you're using, and be prepared to hear that it's broken or that you must work around some limitation. I can tell you that the above fix will work with my Xerces-J-based validator.

Viewing unpushed Git commits

I had a commit done previously, not pushed to any branch, nor remote nor local. Just the commit. Nothing from other answers worked for me, but with:

git reflog

There I found my commit.

Multiple Java versions running concurrently under Windows

It should be possible changing setting the JAVA_HOME environment variable differently for specific applications.

When starting from the command line or from a batch script you can use set JAVA_HOME=C:\...\j2dskXXX to change the JAVA_HOME environment.

It is possible that you also need to change the PATH environment variable to use the correct java binary. To do this you can use set PATH=%JAVA_HOME%\bin;%PATH%.

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

What is the difference between Cygwin and MinGW?

   MinGW (or MinGW-w64)               Cygwin
   --------------------               ------

   Your program written        Your program written
    for Unix and Linux          for Unix and Linux

             |                           |
             |                           |
             V                           V

    Heavy modifications       Almost no modifications

             |                           |
             |                           |
             V                           V

        Compilation                 Compilation
Program compiled with Cygwin ---> Compatibility layer ---> Windows API

Program compiled with MinGW (or MingGW-w64) -------------> Windows API

How to apply filters to *ngFor?

Pipe would be best approach. but below one would also work.

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

How to refer environment variable in POM.xml?

You can use <properties> tag to define a custom variable and ${variable} pattern to use it

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <!-- define -->
    <properties>
        <property.name>1.0</property.name>
    </properties>

    <!-- using -->
    <version>${property.name}</version>

</project>

Broadcast receiver for checking internet connection in android app

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        if (checkInternet(context)) {
            Toast.makeText(context, "Network Available Do operations", Toast.LENGTH_LONG).show();
        }
    }

    boolean checkInternet(Context context) {
        ServiceManager serviceManager = new ServiceManager(context);
        return serviceManager.isNetworkAvailable()
    }
}

ServiceManager.java

public class ServiceManager {

    Context context;

    public ServiceManager(Context base) {
        context = base;
    }

    public boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }
}

permissions:

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

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

We had the same problem. In our case, the browser was blocked by a login popup (Windows authentication), so not returning after 60 seconds. Adding correct access rights to the Windows account Chrome was running under solved the problem.

How do I parse a YAML file in Ruby?

I had the same problem but also wanted to get the content of the file (after the YAML front-matter).

This is the best solution I have found:

if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
  self.contents = md.post_match
  self.metadata = YAML.load(md[:metadata])
end

Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files

Does Python have a string 'contains' substring method?

If it's just a substring search you can use string.find("substring").

You do have to be a little careful with find, index, and in though, as they are substring searches. In other words, this:

s = "This be a string"
if s.find("is") == -1:
    print("No 'is' here!")
else:
    print("Found 'is' in the string.")

It would print Found 'is' in the string. Similarly, if "is" in s: would evaluate to True. This may or may not be what you want.

How to take input in an array + PYTHON?

raw_input is your helper here. From documentation -

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

So your code will basically look like this.

num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
    n = raw_input("num :")
    num_array.append(int(n))
print 'ARRAY: ',num_array

P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input does not do any type checking, so you need to be careful...

Access Https Rest Service using Spring RestTemplate

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(new File(keyStoreFile)),
  keyStorePassword.toCharArray());

SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
  new SSLContextBuilder()
    .loadTrustMaterial(null, new TrustSelfSignedStrategy())
    .loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
    .build(),
    NoopHostnameVerifier.INSTANCE);

HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(
  socketFactory).build();

ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
  httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
MyRecord record = restTemplate.getForObject(uri, MyRecord.class);
LOG.debug(record.toString());