Programs & Examples On #Stomp

STOMP is a simple interoperable protocol designed for asynchronous message passing between clients via mediating servers.

Flutter: RenderBox was not laid out

Reading answers here, it seems that the error "RenderBox was not laid out" is caused when somehow the ListView size is limitless and this can happen in different scenarios.

Just aiming to help who may have the same case as mine. In my case, I was getting this error because my ListView was inside a a column whose parent was a SingleChildScrollView. I remove this parent and it worked.

Here is my working code:

 List _todoList = ["AAA", "BBB"];

 ...

    body: Column(
      children: [
        Container(...),
        Expanded(
            child: ListView.builder(
                itemCount: _todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(_todoList[index]));
                }))
      ],
    ));

Here how it was when I was getting the "not laid out" error:

     List _todoList = ["AAA", "BBB"];

     ...


     body: SingleChildScrollView(child: Column(
      children: [
        Container(...),
        Expanded(
            child: ListView.builder(
                itemCount: _todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(_todoList[index]));
                }))
      ],
    )));

I hope this may be useful for someone.

Flutter - The method was called on null

The reason for this error occurs is that you are using the CryptoListPresenter _presenter without initializing.

I found that CryptoListPresenter _presenter would have to be initialized to fix because _presenter.loadCurrencies() is passing through a null variable at the time of instantiation;

there are two ways to initialize

  1. Can be initialized during an declaration, like this

    CryptoListPresenter _presenter = CryptoListPresenter();
    
  2. In the second, initializing(with assigning some value) it when initState is called, which the framework will call this method once for each state object.

    @override
    void initState() {
      _presenter = CryptoListPresenter(...);
    }
    

Websocket connections with Postman

Postman currently does not support that.

You may use this online tester by Websocket.in: https://www.websocket.in/test-online

Using an array from Observable Object with ngFor and Async Pipe Angular 2

I think what u r looking for is this

<article *ngFor="let news of (news$ | async)?.articles">
<h4 class="head">{{news.title}}</h4>
<div class="desc"> {{news.description}}</div>
<footer>
    {{news.author}}
</footer>

How to redirect output of systemd service to a file

We are using Centos7, spring boot application with systemd. I was running java as below. and setting StandardOutput to file was not working for me.

ExecStart=/bin/java -jar xxx.jar  -Xmx512-Xms32M

Below workaround solution working without setting StandardOutput. running java through sh as below.


ExecStart=/bin/sh -c 'exec /bin/java -jar xxx.jar -Xmx512M -Xms32M >> /data/logs/xxx.log 2>&1'

enter image description here

Unable to add window -- token null is not valid; is your activity running?

You should not put the windowManager.addView in onCreate

Try to call the windowManager.addView after onWindowFocusChanged and the status of hasFoucus is true.

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    //code here
    //that you can add a flag that you can call windowManager.addView now.
}

Slick.js: Get current and total slides (ie. 3/5)

This might help:

  • You don't need to enable dots or customPaging.
  • Position .slick-counter with CSS.

CSS

.slick-counter{
  position:absolute;
  top:5px;
  left:5px;
  background:yellow;
  padding:5px;
  opacity:0.8;
  border-radius:5px;
}

JavaScript

var $el = $('.slideshow');

$el.slick({
  slide: 'img',
  autoplay: true,
  onInit: function(e){
    $el.append('<div class="slick-counter">'+ parseInt(e.currentSlide + 1, 10) +' / '+ e.slideCount +'</div>');
  },
  onAfterChange: function(e){
    $el.find('.slick-counter').html(e.currentSlide + 1 +' / '+e.slideCount);
  }
});

http://jsfiddle.net/cpdqhdwy/6/

Removing "bullets" from unordered list <ul>

You can remove the "bullets" by setting the "list-style-type: none;" Like

ul
{
    list-style-type: none;
}

OR

<ul class="menu custompozition4"  style="list-style-type: none;">
    <li class="item-507"><a href=#">Strategic Recruitment Solutions</a>
    </li>
    <li class="item-508"><a href="#">Executive Recruitment</a>
    </li>
    <li class="item-509"><a href="#">Leadership Development</a>
    </li>
    <li class="item-510"><a href="#">Executive Capability Review</a>
    </li>
    <li class="item-511"><a href="#">Board and Executive Coaching</a>
    </li>
    <li class="item-512"><a href="#">Cross Cultutral Coaching</a>
    </li>
    <li class="item-513"><a href="#">Team Enhancement &amp; Coaching</a>
    </li>
    <li class="item-514"><a href="#">Personnel Re-deployment</a>
    </li>
</ul>

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

I had the same problem - my scenario was that I was referencing the new System.Web.Mvc.dll from a lib folder and I did not have "Copy Local" set to true. The application was then reverting back to the version in the GAC which didn't have the correct namespaces (Html, Ajax etc) in it and was giving me the run time error.

error: the details of the application error from being viewed remotely

Dear olga is clear what the message says. Turn off the custom errors to see the details about this error for fix it, and then you close them back. So add mode="off" as:

<configuration>
    <system.web>
        <customErrors mode="Off"/>
    </system.web>
</configuration>

Relative answer: Deploying website: 500 - Internal server error

By the way: The error message declare that the web.config is not the one you type it here. Maybe you have forget to upload your web.config ? And remember to close the debug flag on the web.config that you use for online pages.

POI setting Cell Background to a Custom Color

You get this error because pallete is full. What you need to do is override preset color. Here is an example of function I'm using:

public HSSFColor setColor(HSSFWorkbook workbook, byte r,byte g, byte b){
    HSSFPalette palette = workbook.getCustomPalette();
    HSSFColor hssfColor = null;
    try {
        hssfColor= palette.findColor(r, g, b); 
        if (hssfColor == null ){
            palette.setColorAtIndex(HSSFColor.LAVENDER.index, r, g,b);
            hssfColor = palette.getColor(HSSFColor.LAVENDER.index);
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return hssfColor;
}

And later use it for background color:

HSSFColor lightGray =  setColor(workbook,(byte) 0xE0, (byte)0xE0,(byte) 0xE0);
style2.setFillForegroundColor(lightGray.getIndex());
style2.setFillPattern(CellStyle.SOLID_FOREGROUND);

Single controller with multiple GET methods in ASP.NET Web API

In ASP.NET Core 2.0 you can add Route attribute to the controller:

[Route("api/[controller]/[action]")]
public class SomeController : Controller
{
    public SomeValue GetItems(CustomParam parameter) { ... }

    public SomeValue GetChildItems(CustomParam parameter, SomeObject parent) { ... }
}

Android: No Activity found to handle Intent error? How it will resolve

in my case, i was sure that the action is correct, but i was passing wrong URL, i passed the website link without the http:// in it's beginning, so it caused the same issue, here is my manifest (part of it)

<activity
        android:name=".MyBrowser"
        android:label="MyBrowser Activity" >
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <action android:name="com.dsociety.activities.MyBrowser" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:scheme="http" />
        </intent-filter>
    </activity>

when i code the following, the same Exception is thrown at run time :

Intent intent = new Intent();
intent.setAction("com.dsociety.activities.MyBrowser");
intent.setData(Uri.parse("www.google.com"));    // should be http://www.google.com
startActivity(intent);

Server Error in '/' Application. ASP.NET

Look at these two excerpts:

I uploaded my website to my domain under the public folder.

and

This error can be caused by a virtual directory not being configured as an application in IIS.

It's pretty clear to me that you did exactly what you said you did, and no more, i.e. you transfered the files to the web server, but nothing else. You need to configure that public folder as a virtual directory in IIS as the error is telling you, or it's just not going to work.

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.

Custom Drawable for ProgressBar/ProgressDialog

I used the following for creating a custom progress bar.

File res/drawable/progress_bar_states.xml declares the colors of the different states:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/background">
        <shape>
            <gradient
                    android:startColor="#000001"
                    android:centerColor="#0b131e"
                    android:centerY="0.75"
                    android:endColor="#0d1522"
                    android:angle="270"
            />
        </shape>
    </item>

    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <gradient
                        android:startColor="#234"
                        android:centerColor="#234"
                        android:centerY="0.75"
                        android:endColor="#a24"
                        android:angle="270"
                />
            </shape>
        </clip>
    </item>

    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <gradient
                    android:startColor="#144281"
                    android:centerColor="#0b1f3c"
                    android:centerY="0.75"
                    android:endColor="#06101d"
                    android:angle="270"
                />
            </shape>
        </clip>
    </item>

</layer-list>

And the code inside your layout xml:

<ProgressBar android:id="@+id/progressBar"
    android:progressDrawable="@drawable/progress_bar_states"
    android:layout_width="fill_parent" android:layout_height="8dip" 
    style="?android:attr/progressBarStyleHorizontal" 
    android:indeterminateOnly="false" 
    android:max="100">
</ProgressBar>

Enjoy!

How to convert "0" and "1" to false and true

My solution (vb.net):

Private Function ConvertToBoolean(p1 As Object) As Boolean
    If p1 Is Nothing Then Return False
    If IsDBNull(p1) Then Return False
    If p1.ToString = "1" Then Return True
    If p1.ToString.ToLower = "true" Then Return True
    Return False
End Function

Javascript: best Singleton pattern

(1) UPDATE 2019: ES7 Version

class Singleton {
    static instance;

    constructor() {
        if (instance) {
            return instance;
        }

        this.instance = this;
    }

    foo() {
        // ...
    }
}

console.log(new Singleton() === new Singleton());

(2) ES6 Version

class Singleton {
    constructor() {
        const instance = this.constructor.instance;
        if (instance) {
            return instance;
        }

        this.constructor.instance = this;
    }

    foo() {
        // ...
    }
}

console.log(new Singleton() === new Singleton());

Best solution found: http://code.google.com/p/jslibs/wiki/JavascriptTips#Singleton_pattern

function MySingletonClass () {

  if (arguments.callee._singletonInstance) {
    return arguments.callee._singletonInstance;
  }

  arguments.callee._singletonInstance = this;

  this.Foo = function () {
    // ...
  };
}

var a = new MySingletonClass();
var b = MySingletonClass();
console.log( a === b ); // prints: true

For those who want the strict version:

(function (global) {
  "use strict";
  var MySingletonClass = function () {

    if (MySingletonClass.prototype._singletonInstance) {
      return MySingletonClass.prototype._singletonInstance;
    }

    MySingletonClass.prototype._singletonInstance = this;

    this.Foo = function() {
      // ...
    };
  };

var a = new MySingletonClass();
var b = MySingletonClass();
global.result = a === b;

} (window));

console.log(result);

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

And one more:

#!/bin/bash

# We have:
#
# 1) $KEY : Secret key in PEM format ("-----BEGIN RSA PRIVATE KEY-----") 
# 2) $LEAFCERT : Certificate for secret key obtained from some
#    certification outfit, also in PEM format ("-----BEGIN CERTIFICATE-----")   
# 3) $CHAINCERT : Intermediate certificate linking $LEAFCERT to a trusted
#    Self-Signed Root CA Certificate 
#
# We want to create a fresh Java "keystore" $TARGET_KEYSTORE with the
# password $TARGET_STOREPW, to be used by Tomcat for HTTPS Connector.
#
# The keystore must contain: $KEY, $LEAFCERT, $CHAINCERT
# The Self-Signed Root CA Certificate is obtained by Tomcat from the
# JDK's truststore in /etc/pki/java/cacerts

# The non-APR HTTPS connector (APR uses OpenSSL-like configuration, much
# easier than this) in server.xml looks like this 
# (See: https://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html):
#
#  <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
#                SSLEnabled="true"
#                maxThreads="150" scheme="https" secure="true"
#                clientAuth="false" sslProtocol="TLS"
#                keystoreFile="/etc/tomcat6/etl-web.keystore.jks"
#                keystorePass="changeit" />
#

# Let's roll:    

TARGET_KEYSTORE=/etc/tomcat6/foo-server.keystore.jks
TARGET_STOREPW=changeit

TLS=/etc/pki/tls

KEY=$TLS/private/httpd/foo-server.example.com.key
LEAFCERT=$TLS/certs/httpd/foo-server.example.com.pem
CHAINCERT=$TLS/certs/httpd/chain.cert.pem

# ----
# Create PKCS#12 file to import using keytool later
# ----

# From https://www.sslshopper.com/ssl-converter.html:
# The PKCS#12 or PFX format is a binary format for storing the server certificate,
# any intermediate certificates, and the private key in one encryptable file. PFX
# files usually have extensions such as .pfx and .p12. PFX files are typically used 
# on Windows machines to import and export certificates and private keys.

TMPPW=$$ # Some random password

PKCS12FILE=`mktemp`

if [[ $? != 0 ]]; then
  echo "Creation of temporary PKCS12 file failed -- exiting" >&2; exit 1
fi

TRANSITFILE=`mktemp`

if [[ $? != 0 ]]; then
  echo "Creation of temporary transit file failed -- exiting" >&2; exit 1
fi

cat "$KEY" "$LEAFCERT" > "$TRANSITFILE"

openssl pkcs12 -export -passout "pass:$TMPPW" -in "$TRANSITFILE" -name etl-web > "$PKCS12FILE"

/bin/rm "$TRANSITFILE"

# Print out result for fun! Bug in doc (I think): "-pass " arg does not work, need "-passin"

openssl pkcs12 -passin "pass:$TMPPW" -passout "pass:$TMPPW" -in "$PKCS12FILE" -info

# ----
# Import contents of PKCS12FILE into a Java keystore. WTF, Sun, what were you thinking?
# ----

if [[ -f "$TARGET_KEYSTORE" ]]; then
  /bin/rm "$TARGET_KEYSTORE"
fi

keytool -importkeystore \
   -deststorepass  "$TARGET_STOREPW" \
   -destkeypass    "$TARGET_STOREPW" \
   -destkeystore   "$TARGET_KEYSTORE" \
   -srckeystore    "$PKCS12FILE" \
   -srcstoretype  PKCS12 \
   -srcstorepass  "$TMPPW" \
   -alias foo-the-server

/bin/rm "$PKCS12FILE"

# ----
# Import the chain certificate. This works empirically, it is not at all clear from the doc whether this is correct
# ----

echo "Importing chain"

TT=-trustcacerts

keytool -import $TT -storepass "$TARGET_STOREPW" -file "$CHAINCERT" -keystore "$TARGET_KEYSTORE" -alias chain

# ----
# Print contents
# ----

echo "Listing result"

keytool -list -storepass "$TARGET_STOREPW" -keystore "$TARGET_KEYSTORE"

Where is Python's sys.path initialized from?

"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default"

-- http://docs.python.org/library/sys.html#sys.path

Can .NET load and parse a properties file equivalent to Java Properties class?

I don't know of any built-in way to do this. However, it would seem easy enough to do, since the only delimiters you have to worry about are the newline character and the equals sign.

It would be very easy to write a routine that will return a NameValueCollection, or an IDictionary given the contents of the file.

Simplest way to have a configuration file in a Windows Forms C# application

The default name for a configuration file is [yourexe].exe.config. So notepad.exe will have a configuration file named notepad.exe.config, in the same folder as the program. This is a general configuration file for all aspects of the CLR and Framework, but it can contain your own settings under an <appSettings> node.

The <appSettings> element creates a collection of name-value pairs which can be accessed as System.Configuration.ConfigurationSettings.AppSettings. There is no way to save changes back to the configuration file, however.

It is also possible to add your own custom elements to a configuration file - for example, to define a structured setting - by creating a class that implements IConfigurationSectionHandler and adding it to the <configSections> element of the configuration file. You can then access it by calling ConfigurationSettings.GetConfig.

.NET 2.0 adds a new class, System.Configuration.ConfigurationManager, which supports multiple files, with per-user overrides of per-system data. It also supports saving modified configurations back to settings files.

Visual Studio creates a file called App.config, which it copies to the EXE folder, with the correct name, when the project is built.

How to recursively find and list the latest modified files in a directory with subdirectories and times

Try this:

#!/bin/bash
stat --format %y $(ls -t $(find alfa/ -type f) | head -n 1)

It uses find to gather all files from the directory, ls to list them sorted by modification date, head for selecting the first file and finally stat to show the time in a nice format.

At this time it is not safe for files with whitespace or other special characters in their names. Write a commend if it doesn't meet your needs yet.

Can two or more people edit an Excel document at the same time?

Unfortunately, the file must be locked for updates unless you're using Office 2010 and SharePoint 2010 together. This means that only one user per time can edit a file. The locking and version tracking capabilities of SharePoint are excellent, and this makes it a great tool for the type of collaboration you're talking about, but you would have to split documents into multiple files in order to extend the amount that could be edited at a time. For instance, we sometimes unmerge documents into technical, requirements, and financials sections so that the 3 experts required for the review can work concurrently. We then merge when everyone is finished.

How do I pass multiple parameters into a function in PowerShell?

Parameters in calls to functions in PowerShell (all versions) are space-separated, not comma separated. Also, the parentheses are entirely unneccessary and will cause a parse error in PowerShell 2.0 (or later) if Set-StrictMode -Version 2 or higher is active. Parenthesised arguments are used in .NET methods only.

function foo($a, $b, $c) {
   "a: $a; b: $b; c: $c"
}

ps> foo 1 2 3
a: 1; b: 2; c: 3

Auto start print html page using javascript

If what you want is to open a separate window from the web browser you can use this:

  window.open(basePath + "Controller/Route/?ID=" + param, '_blank').print();

[ :Unexpected operator in shell programming

Do not use any reserved keyword as the start of any variable name: eg HOSTNAME will fail as HOST {TYPE|NAME} are reserved

Apache Tomcat :java.net.ConnectException: Connection refused

Depending on your version of Tomcat, this might be a simple problem (bug) with a 0-byte log file. Take a look at /var/log/tomcatX.Y where X.Y is your version you're working with and check if the log file catalina.out is read- and writeable. If it has 0 byte and is not accessible, then simply delete it and re-start Tomcat. This solved the problem for us a few times already.

Check if object exists in JavaScript

if (maybeObject !== undefined)
  alert("Got here!");

Hide Button After Click (With Existing Form on Page)

CSS code:

.hide{
display:none;
}

.show{
display:block;
}

Html code:

<button onclick="block_none()">Check Availability</button>

Javascript Code:

function block_none(){
 document.getElementById('hidden-div').classList.add('show');
document.getElementById('button-id').classList.add('hide');
}

Iterate over elements of List and Map using JSTL <c:forEach> tag

Mark, this is already answered in your previous topic. But OK, here it is again:

Suppose ${list} points to a List<Object>, then the following

<c:forEach items="${list}" var="item">
    ${item}<br>
</c:forEach>

does basically the same as as following in "normal Java":

for (Object item : list) {
    System.out.println(item);
}

If you have a List<Map<K, V>> instead, then the following

<c:forEach items="${list}" var="map">
    <c:forEach items="${map}" var="entry">
        ${entry.key}<br>
        ${entry.value}<br>
    </c:forEach>
</c:forEach>

does basically the same as as following in "normal Java":

for (Map<K, V> map : list) {
    for (Entry<K, V> entry : map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
}

The key and value are here not special methods or so. They are actually getter methods of Map.Entry object (click at the blue Map.Entry link to see the API doc). In EL (Expression Language) you can use the . dot operator to access getter methods using "property name" (the getter method name without the get prefix), all just according the Javabean specification.

That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".

What is an unsigned char?

An unsigned char uses the bit that is reserved for the sign of a regular char as another number. This changes the range to [0 - 255] as opposed to [-128 - 127].

Generally unsigned chars are used when you don't want a sign. This will make a difference when doing things like shifting bits (shift extends the sign) and other things when dealing with a char as a byte rather than using it as a number.

How to insert array of data into mysql using php

First of all you should stop using mysql_*. MySQL supports multiple inserting like

INSERT INTO example
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

You just have to build one string in your foreach loop which looks like that

$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";

and then insert it after the loop

$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;

Another way would be Prepared Statements, which are even more suited for your situation.

How to remove leading and trailing zeros in a string? Python

What about a basic

your_string.strip("0")

to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use .rstrip instead (and .lstrip for only the leading ones).

More info in the doc.

You could use some list comprehension to get the sequences you want like so:

trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]

How to add Active Directory user group as login in SQL Server

In SQL Server Management Studio, go to Object Explorer > (your server) > Security > Logins and right-click New Login:

enter image description here

Then in the dialog box that pops up, pick the types of objects you want to see (Groups is disabled by default - check it!) and pick the location where you want to look for your objects (e.g. use Entire Directory) and then find your AD group.

enter image description here

You now have a regular SQL Server Login - just like when you create one for a single AD user. Give that new login the permissions on the databases it needs, and off you go!

Any member of that AD group can now login to SQL Server and use your database.

How to detect when facebook's FB.init is complete

The Facebook API watches for the FB._apiKey so you can watch for this before calling your own application of the API with something like:

window.fbAsyncInit = function() {
  FB.init({
    //...your init object
  });
  function myUseOfFB(){
    //...your FB API calls
  };
  function FBreadyState(){
    if(FB._apiKey) return myUseOfFB();
    setTimeout(FBreadyState, 100); // adjust time as-desired
  };
  FBreadyState();
}; 

Not sure this makes a difference but in my case--because I wanted to be sure the UI was ready--I've wrapped the initialization with jQuery's document ready (last bit above):

  $(document).ready(FBreadyState);

Note too that I'm NOT using async = true to load Facebook's all.js, which in my case seems to be helping with signing into the UI and driving features more reliably.

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

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

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

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

Java out.println() how is this possible?

PrintStream out = System.out;
out.println( "hello" );

Do I commit the package-lock.json file created by npm 5?

Yes, you SHOULD:

  1. commit the package-lock.json.
  2. use npm ci instead of npm install when building your applications both on your CI and your local development machine

The npm ci workflow requires the existence of a package-lock.json.


A big downside of npm install command is its unexpected behavior that it may mutate the package-lock.json, whereas npm ci only uses the versions specified in the lockfile and produces an error

  • if the package-lock.json and package.json are out of sync
  • if a package-lock.json is missing.

Hence, running npm install locally, esp. in larger teams with multiple developers, may lead to lots of conflicts within the package-lock.json and developers to decide to completely delete the package-lock.json instead.

Yet there is a strong use-case for being able to trust that the project's dependencies resolve repeatably in a reliable way across different machines.

From a package-lock.json you get exactly that: a known-to-work state.

In the past, I had projects without package-lock.json / npm-shrinkwrap.json / yarn.lock files whose build would fail one day because a random dependency got a breaking update.

Those issue are hard to resolve as you sometimes have to guess what the last working version was.

If you want to add a new dependency, you still run npm install {dependency}. If you want to upgrade, use either npm update {dependency} or npm install ${dependendency}@{version} and commit the changed package-lock.json.

If an upgrade fails, you can revert to the last known working package-lock.json.


To quote npm doc:

It is highly recommended you commit the generated package lock to source control: this will allow anyone else on your team, your deployments, your CI/continuous integration, and anyone else who runs npm install in your package source to get the exact same dependency tree that you were developing on. Additionally, the diffs from these changes are human-readable and will inform you of any changes npm has made to your node_modules, so you can notice if any transitive dependencies were updated, hoisted, etc.

And in regards to the difference between npm ci vs npm install:

  • The project must have an existing package-lock.json or npm-shrinkwrap.json.
  • If dependencies in the package lock do not match those in package.json, npm ci will exit with an error, instead of updating the package lock.
  • npm ci can only install entire projects at a time: individual dependencies cannot be added with this command.
  • If a node_modules is already present, it will be automatically removed before npm ci begins its install.
  • It will never write to package.json or any of the package-locks: installs are essentially frozen.

Note: I posted a similar answer here

DATEDIFF function in Oracle

In Oracle, you can simply subtract two dates and get the difference in days. Also note that unlike SQL Server or MySQL, in Oracle you cannot perform a select statement without a from clause. One way around this is to use the builtin dummy table, dual:

SELECT TO_DATE('2000-01-02', 'YYYY-MM-DD') -  
       TO_DATE('2000-01-01', 'YYYY-MM-DD') AS DateDiff
FROM   dual

CentOS 7 and Puppet unable to install nc

Nc is a link to nmap-ncat.

It would be nice to use nmap-ncat in your puppet, because NC is a virtual name of nmap-ncat.

Puppet cannot understand the links/virtualnames

your puppet should be:

package {
  'nmap-ncat':
    ensure => installed;
}

How do I compare two string variables in an 'if' statement in Bash?

$ if [ "$s1" == "$s2" ]; then echo match; fi
match
$ test "s1" = "s2" ;echo match
match
$

Only mkdir if it does not exist

if [ ! -d directory ]; then
  mkdir directory
fi

or

mkdir -p directory

-p ensures creation if directory does not exist

Excel VBA date formats

Use value(cellref) on the side to evaluate the cells. Strings will produce the "#Value" error, but dates resolve to a number (e.g. 43173).

What is the function __construct used for?

__construct was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor). You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.

An example could go like this:

class Database {
  protected $userName;
  protected $password;
  protected $dbName;

  public function __construct ( $UserName, $Password, $DbName ) {
    $this->userName = $UserName;
    $this->password = $Password;
    $this->dbName = $DbName;
  }
}

// and you would use this as:
$db = new Database ( 'user_name', 'password', 'database_name' );

Everything else is explained in the PHP manual: click here

Where do I put image files, css, js, etc. in Codeigniter?

I use the following folder structure:

application 
system 
static
    admin
        js
        css
        images
    public
        js
        css
        images
    uploads
        original
        thumbs

How to disable anchor "jump" when loading a page?

Try this to prevent client from any kind of vertical scrolling on hashchanged (inside your event handler):

var sct = document.body.scrollTop;
document.location.hash = '#next'; // or other manipulation
document.body.scrollTop = sct;

(browser redraw)

Check if a record exists in the database

ExecuteScalar returns the first column of the first row. Other columns or rows are ignored. It looks like your first column of the first row is null, and that's why you get NullReferenceException when you try to use the ExecuteScalar method.

From MSDN;

Return Value

The first column of the first row in the result set, or a null reference if the result set is empty.

You might need to use COUNT in your statement instead which returns the number of rows affected...

Using parameterized queries is always a good practise. It prevents SQL Injection attacks.

And Table is a reserved keyword in T-SQL. You should use it with square brackets, like [Table] also.

As a final suggestion, use the using statement for dispose your SqlConnection and SqlCommand:

SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM [Table] WHERE ([user] = @user)" , conn);
check_User_Name.Parameters.AddWithValue("@user", txtBox_UserName.Text);
int UserExist = (int)check_User_Name.ExecuteScalar();

if(UserExist > 0)
{
   //Username exist
}
else
{
   //Username doesn't exist.
}

Getting fb.me URL

Facebook uses Bit.ly's services to shorten links from their site. While pages that have a username turns into "fb.me/<username>", other links associated with Facebook turns into "on.fb.me/*****". To you use the on.fb.me service, just use your Bit.ly account. Note that if you change the default link shortener on your Bit.ly account to j.mp from bit.ly this service won't work.

SQL to Query text in access with an apostrophe in it

When you include a string literal in a query, you can enclose the string in either single or double quotes; Access' database engine will accept either. So double quotes will avoid the problem with a string which contains a single quote.

SELECT * FROM tblStudents WHERE [name] Like "Daniel O'Neal";

If you want to keep the single quotes around your string, you can double up the single quote within it, as mentioned in other answers.

SELECT * FROM tblStudents WHERE [name] Like 'Daniel O''Neal';

Notice the square brackets surrounding name. I used the brackets to lessen the chance of confusing the database engine because name is a reserved word.

It's not clear why you're using the Like comparison in your query. Based on what you've shown, this should work instead.

SELECT * FROM tblStudents WHERE [name] = "Daniel O'Neal";

How can I run code on a background thread on Android?

Today I was looking for this and Mr Brandon Rude gave an excellent answer. Unfortunately, AsyncTask is now depricated, you can still use it, but it gives you a warning which is very annoying. So an alternative is to use Executors like this way (in kotlin):


    val someRunnable = object : Runnable{
      override fun run() {
        // todo: do your background tasks
        requireActivity().runOnUiThread{
          // update views / ui if you are in a fragment
        };
        /*
        runOnUiThread {
          // update ui if you are in an activity
        }
        * */
      }
    };
    Executors.newSingleThreadExecutor().execute(someRunnable);

And in java it looks like this:


        Runnable someRunnable = new Runnable() {
            @Override
            public void run() {
                // todo: background tasks
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // todo: update your ui / view in activity
                    }
                });

                /*
                requireActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // todo: update your ui / view in Fragment
                    }
                });*/
            }
        };

        Executors.newSingleThreadExecutor().execute(someRunnable);

Automatic exit from Bash shell script on error

An alternative to the accepted answer that fits in the first line:

#!/bin/bash -e

cd some_dir  

./configure --some-flags  

make  

make install

"query function not defined for Select2 undefined error"

It seems that your selector returns an undefined element (Therefore undefined error is returned)

In case the element really exists, you are calling select2 on an input element without supplying anything to select2, where it should fetch the data from. Typically, one calls .select2({data: [{id:"firstid", text:"firsttext"}]).

How to import functions from different js file in a Vue+webpack+vue-loader project

I was trying to organize my vue app code, and came across this question , since I have a lot of logic in my component and can not use other sub-coponents , it makes sense to use many functions in a separate js file and call them in the vue file, so here is my attempt

1)The Component (.vue file)

//MyComponent.vue file
<template>
  <div>
  <div>Hello {{name}}</div>
  <button @click="function_A">Read Name</button>
  <button @click="function_B">Write Name</button>
  <button @click="function_C">Reset</button>
  <div>{{message}}</div>
  </div>
 </template>


<script>
import Mylib from "./Mylib"; // <-- import
export default {
  name: "MyComponent",
  data() {
    return {
      name: "Bob",
      message: "click on the buttons"
    };
  },
  methods: {
    function_A() {
      Mylib.myfuncA(this); // <---read data
    },
    function_B() {
      Mylib.myfuncB(this); // <---write data
    },
    function_C() {
      Mylib.myfuncC(this); // <---write data
    }
  }
};
</script>

2)The External js file

//Mylib.js
let exports = {};

// this (vue instance) is passed as that , so we
// can read and write data from and to it as we please :)
exports.myfuncA = (that) => {
  that.message =
  "you hit ''myfuncA'' function that is located in Mylib.js  and data.name = " +
    that.name;
};

exports.myfuncB = (that) => {
  that.message =
  "you hit ''myfuncB'' function that is located in Mylib.js and now I will change the name to Nassim";
  that.name = "Nassim"; // <-- change name to Nassim
};

exports.myfuncC = (that) => {
  that.message =
  "you hit ''myfuncC'' function that is located in Mylib.js and now I will change the name back to Bob";
  that.name = "Bob"; // <-- change name to Bob
};

export default exports;

enter image description here 3)see it in action : https://codesandbox.io/s/distracted-pare-vuw7i?file=/src/components/MyComponent.vue


edit

after getting more experience with Vue , I found out that you could use mixins too to split your code into different files and make it easier to code and maintain see https://vuejs.org/v2/guide/mixins.html

How to recursively delete an entire directory with PowerShell 2.0?

There seems to be issues where Remove-Item -Force -Recurse can intermittently fail on Windows because the underlying filesystem is asynchronous. This answer seems to address it. The user has also been actively involved with the Powershell team on GitHub.

Hide the browse button on a input type=file

No, what you can do is a (ugly) workaround, but largely used

  1. Create a normal input and a image
  2. Create file input with opacity 0
  3. When the user click on the image, you simulate a click on the file input
  4. When file input change, you pass it's value to the normal input (so user can see the path)

Here you can see a full explanation, along with code:

http://www.quirksmode.org/dom/inputfile.html

How do I create a list of random numbers without duplicates?

The solution presented in this answer works, but it could become problematic with memory if the sample size is small, but the population is huge (e.g. random.sample(insanelyLargeNumber, 10)).

To fix that, I would go with this:

answer = set()
sampleSize = 10
answerSize = 0

while answerSize < sampleSize:
    r = random.randint(0,100)
    if r not in answer:
        answerSize += 1
        answer.add(r)

# answer now contains 10 unique, random integers from 0.. 100

Is there a performance difference between a for loop and a for-each loop?

From Item 46 in Effective Java by Joshua Bloch :

The for-each loop, introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely. The resulting idiom applies equally to collections and arrays:

// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {
    doSomething(e);
}

When you see the colon (:), read it as “in.” Thus, the loop above reads as “for each element e in elements.” Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once. While you can do this by hand (Item 45), programmers don’t always do so.

RSA: Get exponent and modulus given a public key

Apart from the above answers, we can use asn1parse to get the values

$ openssl asn1parse -i -in pub0.der -inform DER -offset 24
0:d=0  hl=4 l= 266 cons: SEQUENCE
4:d=1  hl=4 l= 257 prim:  INTEGER           :C9131430CCE9C42F659623BDC73A783029A23E4BA3FAF74FE3CF452F9DA9DAF29D6F46556E423FB02610BC4F84E19F87333EAD0BB3B390A3EFA7FB392E935065D80A27589A21CA051FA226195216D8A39F151BD0334965551744566AD3DAEB53EBA27783AE08BAAACA406C27ED8BE614518C8CD7D14BBE7AFEBE1D8D03374DAE7B7564CF1182A7B3BA115CD9416AB899C5803388EE66FA3676750A77AC870EDA027DC95E57B9B4E864A3C98F1BA99A4726C085178EA8FC6C549BE5EDF970CCB8D8F9AEDEE3F5CFDE574327D05ED04060B2525FB6711F1D78254FF59089199892A9ECC7D4E4950E0CD2246E1E613889722D73DB56B24E57F3943E11520776BC4F
265:d=1  hl=2 l= 3 prim:  INTEGER           :010001

Now, to get to this offset,we try the default asn1parse

$ openssl asn1parse -i -in pub0.der -inform DER
 0:d=0  hl=4 l= 290 cons: SEQUENCE
 4:d=1  hl=2 l=  13 cons:  SEQUENCE
 6:d=2  hl=2 l=   9 prim:   OBJECT            :rsaEncryption
17:d=2  hl=2 l=   0 prim:   NULL
19:d=1  hl=4 l= 271 prim:  BIT STRING

We need to get to the BIT String part, so we add the sizes

depth_0_header(4) + depth_1_full_size(2 + 13) + Container_1_EOC_bit + BIT_STRING_header(4) = 24

This can be better visialized at: ASN.1 Parser, if you hover at tags, you will see the offsets

Another amazing resource: Microsoft's ASN.1 Docs

How do I format a date in Jinja2?

There are two ways to do it. The direct approach would be to simply call (and print) the strftime() method in your template, for example

{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}

Another, sightly better approach would be to define your own filter, e.g.:

from flask import Flask
import babel

app = Flask(__name__)

@app.template_filter()
def format_datetime(value, format='medium'):
    if format == 'full':
        format="EEEE, d. MMMM y 'at' HH:mm"
    elif format == 'medium':
        format="EE dd.MM.y HH:mm"
    return babel.dates.format_datetime(value, format)

(This filter is based on babel for reasons regarding i18n, but you can use strftime too). The advantage of the filter is, that you can write

{{ car.date_of_manufacture|datetime }}
{{ car.date_of_manufacture|datetime('full') }}

which looks nicer and is more maintainable. Another common filter is also the "timedelta" filter, which evaluates to something like "written 8 minutes ago". You can use babel.dates.format_timedelta for that, and register it as filter similar to the datetime example given here.

Removing duplicates from a String in Java

I would use the help of LinkedHashSet. Removes dups (as we are using a Set, maintains the order as we are using linked list impl). This is kind of a dirty solution. there might be even a better way.

String s="aabbccdef";
Set<Character> set=new LinkedHashSet<Character>();
for(char c:s.toCharArray())
{
    set.add(Character.valueOf(c));
}

How get data from material-ui TextField, DropDownMenu components?

In 2020 for TextField, via functional components:

const Content = () => {
   ... 
      const textFieldRef = useRef();

      const readTextFieldValue = () => {
        console.log(textFieldRef.current.value)
      }
   ...
  
      return(
       ...
       <TextField
        id="myTextField"
        label="Text Field"
        variant="outlined"
        inputRef={textFieldRef}
       />
       ...
      )

}

Note that this isn't complete code.

Docker and securing passwords

Our team avoids putting credentials in repositories, so that means they're not allowed in Dockerfile. Our best practice within applications is to use creds from environment variables.

We solve for this using docker-compose.

Within docker-compose.yml, you can specify a file that contains the environment variables for the container:

 env_file:
- .env

Make sure to add .env to .gitignore, then set the credentials within the .env file like:

SOME_USERNAME=myUser
SOME_PWD_VAR=myPwd

Store the .env file locally or in a secure location where the rest of the team can grab it.

See: https://docs.docker.com/compose/environment-variables/#/the-env-file

Why use pointers?

  • In some cases, function pointers are required to use functions that are in a shared library (.DLL or .so). This includes performing stuff across languages, where oftentimes a DLL interface is provided.
  • Making compilers
  • Making scientific calculators, where you have an array or vector or string map of function pointers?
  • Trying to modify video memory directly - making your own graphics package
  • Making an API!
  • Data structures - node link pointers for special trees you are making

There are Lots of reasons for pointers. Having C name mangling especially is important in DLLs if you want to maintain cross-language compatibility.

How to add default value for html <textarea>?

If you want to bring information from a database into a textarea tag for editing: The input tag not to display data that occupy several lines: rows no work, tag input is one line.

<!--input class="article-input" id="article-input" type="text" rows="5" value="{{article}}" /-->

The textarea tag has no value, but work fine with handlebars

<textarea class="article-input" id="article-input" type="text" rows="9" >{{article}}</textarea> 

Reset Excel to default borders

Just go to Home> Cell Style > Normal

khir

Creating a segue programmatically

Here is the code sample for Creating a segue programmatically:

class ViewController: UIViewController {
    ...
    // 1. Define the Segue
    private var commonSegue: UIStoryboardSegue!
    ...
    override func viewDidLoad() {
        ...
        // 2. Initialize the Segue
        self.commonSegue = UIStoryboardSegue(identifier: "CommonSegue", source: ..., destination: ...) {
            self.commonSegue.source.showDetailViewController(self.commonSegue.destination, sender: self)
        }
        ...
    }
    ...
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // 4. Prepare to perform the Segue
        if self.commonSegue == segue {
            ...
        }
        ...
    }
    ...
    func actionFunction() {
        // 3. Perform the Segue
        self.prepare(for: self.commonSegue, sender: self)
        self.commonSegue.perform()
    }
    ...
}

Hunk #1 FAILED at 1. What's that mean?

Debugging Tips

  1. Add crlf to the end of the patch file and test if it works
  2. try the --ignore-whitespace command like in: markus@ubuntu:~$ patch -Np1 --ignore-whitespace -d software-1.0 < fix-bug.patch see tutorial by markus

Corrupted Access .accdb file: "Unrecognized Database Format"

After much struggle with this same issue I was able to solve the problem by installing the 32 bit version of the 2010 Access Database Engine. For some reason the 64bit version generates this error...

How to print table using Javascript?

One cheeky solution :

  function printDiv(divID) {
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;
        //Reset the page's HTML with div's HTML only
        document.body.innerHTML = 
          "<html><head><title></title></head><body>" + 
          divElements + "</body>";
        //Print Page
        window.print();
        //Restore orignal HTML
        document.body.innerHTML = oldPage;

    }

HTML :

<form id="form1" runat="server">
    <div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
        Print me I am in 1st Div
    </div>
    <div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
        I am not going to print
    </div>
    <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
</form>

Get GPS location from the web browser

Use this, and you will find all informations at http://www.w3schools.com/html/html5_geolocation.asp

<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
}
</script>

Convert timestamp to readable date/time PHP

Unless you need a custom date and time format, it's easier, less error-prone, and more readable to use one of the built-in date time format constants:

echo date(DATE_RFC822, 1368496604);

Are these methods thread safe?

The only problem with threads is accessing the same object from different threads without synchronization.

If each function only uses parameters for reading and local variables, they don't need any synchronization to be thread-safe.

Replacing few values in a pandas dataframe column with another value

Just wanted to show that there is no performance difference between the 2 main ways of doing it:

df = pd.DataFrame(np.random.randint(0,10,size=(100, 4)), columns=list('ABCD'))

def loc():
    df1.loc[df1["A"] == 2] = 5
%timeit loc
19.9 ns ± 0.0873 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)


def replace():
    df2['A'].replace(
        to_replace=2,
        value=5,
        inplace=True
    )
%timeit replace
19.6 ns ± 0.509 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

SQL ORDER BY date problem

Unsure what dbms you're using however I'd do it this way in Microsoft SQL:

select      [date]
from        tbemp 
order by    cast([date] as datetime) asc

How to catch segmentation fault in Linux?

For portability, one should probably use std::signal from the standard C++ library, but there is a lot of restriction on what a signal handler can do. Unfortunately, it is not possible to catch a SIGSEGV from within a C++ program without introducing undefined behavior because the specification says:

  1. it is undefined behavior to call any library function from within the handler other than a very narrow subset of the standard library functions (abort, exit, some atomic functions, reinstall current signal handler, memcpy, memmove, type traits, `std::move, std::forward, and some more).
  2. it is undefined behavior if handler use a throw expression.
  3. it is undefined behavior if the handler returns when handling SIGFPE, SIGILL, SIGSEGV

This proves that it is impossible to catch SIGSEGV from within a program using strictly standard and portable C++. SIGSEGV is still caught by the operating system and is normally reported to the parent process when a wait family function is called.

You will probably run into the same kind of trouble using POSIX signal because there is a clause that says in 2.4.3 Signal Actions:

The behavior of a process is undefined after it returns normally from a signal-catching function for a SIGBUS, SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill(), sigqueue(), or raise().

A word about the longjumps. Assuming we are using POSIX signals, using longjump to simulate stack unwinding won't help:

Although longjmp() is an async-signal-safe function, if it is invoked from a signal handler which interrupted a non-async-signal-safe function or equivalent (such as the processing equivalent to exit() performed after a return from the initial call to main()), the behavior of any subsequent call to a non-async-signal-safe function or equivalent is undefined.

This means that the continuation invoked by the call to longjump cannot reliably call usually useful library function such as printf, malloc or exit or return from main without inducing undefined behavior. As such, the continuation can only do a restricted operations and may only exit through some abnormal termination mechanism.

To put things short, catching a SIGSEGV and resuming execution of the program in a portable is probably infeasible without introducing UB. Even if you are working on a Windows platform for which you have access to Structured exception handling, it is worth mentioning that MSDN suggest to never attempt to handle hardware exceptions: Hardware Exceptions.

At last but not least, whether any SIGSEGV would be raised when dereferencing a null valued pointer (or invalid valued pointer) is not a requirement from the standard. Because indirection through a null valued pointer or any invalid valued pointer is an undefined behaviour, which means the compiler assumes your code will never attempt such a thing at runtime, the compiler is free to make code transformation that would elide such undefined behavior. For example, from cppreference,

int foo(int* p) {
    int x = *p;
    if(!p)
        return x; // Either UB above or this branch is never taken
    else
        return 0;
}
 
int main() {
    int* p = nullptr;
    std::cout << foo(p);
}

Here the true path of the if could be completely elided by the compiler as an optimization; only the else part could be kept. Said otherwise, the compiler infers foo() will never receive a null valued pointer at runtime since it would lead to an undefined behaviour. Invoking it with a null valued pointer, you may observe the value 0 printed to standard output and no crash, you may observe a crash with SIGSEG, in fact you could observe anything since no sensible requirements are imposed on programs that are not free of undefined behaviors.

How to fix docker: Got permission denied issue

A simple hack is to execute as a "Super User".

To access the super user or root user, follow:

At user@computer:

$sudo su

After you enter your password, you'll be at root@computer:

$docker run hello-world

What is an NP-complete in computer science?

NP Problem :-

  1. NP problem are such problem that can be solved in non-deterministic polynomial time.
  2. Non deterministic algorithm operate in two stage.
  3. Non deterministic guessing stage && Non deterministic verification stage.

Type of Np Problem

  1. NP complete
  2. NP Hard

NP Complete problem :-

1 Decision Problem A is called NP complete if it has following two properties:-

  1. It belong to class NP.
  2. Every other problem in NP can be transformed to P in polynomial time.

Some Ex :-

  • Knapsack problem
  • sub set sum problem
  • Vertex covering problem

How to import js-modules into TypeScript file?

I'm currently taking some legacy codebases and introducing minimal TypeScript changes to see if it helps our team. Depending on how strict you want to be with TypeScript, this may or may not be an option for you.

The most helpful way for us to get started was to extend our tsconfig.json file with this property:

// tsconfig.json excerpt:

{
  ...
  "compilerOptions": {
    ...
    "allowJs": true,
    ...
  }
  ...
}

This change lets our JS files that have JSDoc type hints get compiled. Also our IDEs (JetBrains IDEs and VS Code) can provide code-completion and Intellisense.

References:

git is not installed or not in the PATH

I did install git and tried again and got the same error. But running 'npm install' in a new command prompt window worked for me. Restarting the machine is not required.

How does String.Index work in Swift

Create a UITextView inside of a tableViewController. I used function: textViewDidChange and then checked for return-key-input. then if it detected return-key-input, delete the input of return key and dismiss keyboard.

func textViewDidChange(_ textView: UITextView) {
    tableView.beginUpdates()
    if textView.text.contains("\n"){
        textView.text.remove(at: textView.text.index(before: textView.text.endIndex))
        textView.resignFirstResponder()
    }
    tableView.endUpdates()
}

C# MessageBox dialog result

This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:

//var is of MessageBoxResult type
var result = MessageBox.Show(message, caption,
                             MessageBoxButtons.YesNo,
                             MessageBoxIcon.Question);

// If the no button was pressed ... 
if (result == DialogResult.No)
{
    ...
}

Hope it helps

How to determine total number of open/active connections in ms sql server 2005

As @jwalkerjr mentioned, you should be disposing of connections in code (if connection pooling is enabled, they are just returned to the connection pool). The prescribed way to do this is using the 'using' statement:

// Execute stored proc to read data from repository
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "LoadFromRepository";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@ID", fileID);

        conn.Open();
        using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            if (rdr.Read())
            {
                filename = SaveToFileSystem(rdr, folderfilepath);
            }
        }
    }
}

Changing text of UIButton programmatically swift

Swift 5.0

// Standard State
myButton.setTitle("Title", for: .normal)

How to change colour of blue highlight on select box dropdown

Just found this whilst looking for a solution. I've only tested it FF 32.0.3

box-shadow: 0 0 10px 100px #fff inset;

Splitting applicationContext to multiple files

@eljenso : intrafest-servlet.xml webapplication context xml will be used if the application uses SPRING WEB MVC.

Otherwise the @kosoant configuration is fine.

Simple example if you dont use SPRING WEB MVC, but want to utitlize SPRING IOC :

In web.xml:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application-context.xml</param-value>
</context-param>

Then, your application-context.xml will contain: <import resource="foo-services.xml"/> these import statements to load various application context files and put into main application-context.xml.

Thanks and hope this helps.

How to detect if CMD is running as Administrator/has elevated privileges?

I know I'm really late to this party, but here's my one liner to determine admin-hood.

It doesn't rely on error level, just on systeminfo:

for /f "tokens=1-6" %%a in ('"net user "%username%" | find /i "Local Group Memberships""') do (set admin=yes & if not "%%d" == "*Administrators" (set admin=no) & echo %admin%)

It returns either yes or no, depending on the user's admin status...

It also sets the value of the variable "admin" to equal yes or no accordingly.

TypeError: document.getElementbyId is not a function

Case sensitive: document.getElementById (notice the capital B).

Unable to Install Any Package in Visual Studio 2015

Simply restarting Visual Studio works for me.. try restarting Visual Studio.

How to get address location from latitude and longitude in Google Map.?

Simply pass latitude, longitude and your Google API Key to the following query string, you will get a json array, fetch your city from there.

https://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&key=YOUR_API_KEY

Note: Ensure that no space exists between the latitude and longitude values when passed in the latlng parameter.

Click here to get an API key

Why does Eclipse Java Package Explorer show question mark on some classes?

those icons are a way of Egit to show you status of the current file/folder in git. You might want to check this out:

image describing Eclipse icons for Egit

  • dirty (folder) - At least one file below the folder is dirty; that means that it has changes in the working tree that are neither in the index nor in the repository.
  • tracked - The resource is known to the Git repository. untracked - The resource is not known to the Git repository.
  • ignored - The resource is ignored by the Git team provider. Here only the preference settings under Team -> Ignored Resources and the "derived" flag are relevant. The .gitignore file is not taken into account.
  • dirty - The resource has changes in the working tree that are neither in the index nor in the repository.
  • staged - The resource has changes which are added to the index. Not that adding to the index is possible at the moment only on the commit dialog on the context menu of a resource.
  • partially-staged - The resource has changes which are added to the index and additionally changes in the working tree that are neither in the index nor in the repository.
  • added - The resource is not yet tracked by but added to the Git repository.
  • removed - The resource is staged for removal from the Git repository.
  • conflict - A merge conflict exists for the file.
  • assume-valid - The resource has the "assume unchanged" flag. This means that Git stops checking the working tree files for possible modifications, so you need to manually unset the bit to tell Git when you change the working tree file. This setting can be switched on with the menu action Team->Assume unchanged (or on the command line with git update-index--assume-unchanged).

Getting an Embedded YouTube Video to Auto Play and Loop

Here is the full list of YouTube embedded player parameters.

Relevant info:

autoplay (supported players: AS3, AS2, HTML5) Values: 0 or 1. Default is 0. Sets whether or not the initial video will autoplay when the player loads.

loop (supported players: AS3, HTML5) Values: 0 or 1. Default is 0. In the case of a single video player, a setting of 1 will cause the player to play the initial video again and again. In the case of a playlist player (or custom player), the player will play the entire playlist and then start again at the first video.

Note: This parameter has limited support in the AS3 player and in IFrame embeds, which could load either the AS3 or HTML5 player. Currently, the loop parameter only works in the AS3 player when used in conjunction with the playlist parameter. To loop a single video, set the loop parameter value to 1 and set the playlist parameter value to the same video ID already specified in the Player API URL:

http://www.youtube.com/v/VIDEO_ID?version=3&loop=1&playlist=VIDEO_ID

Use the URL above in your embed code (append other parameters too).

Fatal error: Class 'SoapClient' not found

I had to run

php-config --configure-options --enable-soap 

as root and restart apache.

That worked! Now my phpinfo() call shows the SOAP section.

Jquery each - Stop loop and return object

"We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration."

from http://api.jquery.com/jquery.each/

Yea, this is old BUT, JUST to answer the question, this can be a bit simpler:

_x000D_
_x000D_
function findXX(word) {_x000D_
  $.each(someArray, function(index, value) {_x000D_
    $('body').append('-> ' + index + ":" + value + '<br />');_x000D_
    return !(value == word);_x000D_
  });_x000D_
}_x000D_
$(function() {_x000D_
  someArray = new Array();_x000D_
  someArray[0] = 't5';_x000D_
  someArray[1] = 'z12';_x000D_
  someArray[2] = 'b88';_x000D_
  someArray[3] = 's55';_x000D_
  someArray[4] = 'e51';_x000D_
  someArray[5] = 'o322';_x000D_
  someArray[6] = 'i22';_x000D_
  someArray[7] = 'k954';_x000D_
  findXX('o322');_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

A bit more with comments:

_x000D_
_x000D_
function findXX(myA, word) {_x000D_
  let br = '<br />';//create once_x000D_
  let myHolder = $("<div />");//get a holder to not hit DOM a lot_x000D_
  let found = false;//default return_x000D_
  $.each(myA, function(index, value) {_x000D_
    found = (value == word);_x000D_
    myHolder.append('-> ' + index + ":" + value + br);_x000D_
    return !found;_x000D_
  });_x000D_
  $('body').append(myHolder.html());// hit DOM once_x000D_
  return found;_x000D_
}_x000D_
$(function() {_x000D_
  // no horrid global array, easier array setup;_x000D_
  let someArray = ['t5', 'z12', 'b88', 's55', 'e51', 'o322', 'i22', 'k954'];_x000D_
  // pass the array and the value we want to find, return back a value_x000D_
  let test = findXX(someArray, 'o322');_x000D_
  $('body').append("<div>Found:" + test + "</div>");_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

NOTE: array .includes() may better suit here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

Or just .find() to get that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

Causes of getting a java.lang.VerifyError

If you are migrating to java7 or using java7 then generally this error can be seen. I faced above errors and struggled a lot to find out the root cause, I would suggest to try adding "-XX:-UseSplitVerifier" JVM argument while running your application.

How to create multiple output paths in Webpack config

Webpack does support multiple output paths.

Set the output paths as the entry key. And use the name as output template.

webpack config:

entry: {
    'module/a/index': 'module/a/index.js',
    'module/b/index': 'module/b/index.js',
},
output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
}

generated:

+-- module
    +-- a
    ¦   +-- index.js
    +-- b
        +-- index.js

How do I format a number in Java?

As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using).

Use Spring's Numberformatter instead, which is thread safe.

How can I find out if an .EXE has Command-Line Options?

Sysinternals has another tool you could use, Strings.exe

Example:

strings.exe c:\windows\system32\wuauclt.exe > %temp%\wuauclt_strings.txt && %temp%\wuauclt_strings.txt

How to Flatten a Multidimensional Array?

If you have an array of objects and want to flatten it with a node, just use this function:

function objectArray_flatten($array,$childField) {
    $result = array();
    foreach ($array as $node)
    {
        $result[] = $node;
        if(isset($node->$childField))
        {
            $result = array_merge(
                $result, 
                objectArray_flatten($node->$childField,$childField)
            );
            unset($node->$childField);
        }

    }
    return $result;
}

how to re-format datetime string in php?

why not use date() just like below,try this

$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);

and will be output

09/04/13 16:37:05

How to put multiple statements in one line?

maybe with "and" or "or"

after false need to write "or"

after true need to write "and"

like

n=0
def returnsfalse():
    global n
    n=n+1
    print ("false %d" % (n))
    return False
def returnstrue():
    global n
    n=n+1
    print ("true %d" % (n))
    return True
n=0
returnsfalse() or  returnsfalse() or returnsfalse() or returnstrue() and returnsfalse()

result:

false 1
false 2
false 3
true 4
false 5

or maybe like

(returnsfalse() or true) and (returnstrue() or true) and ...

got here by searching google "how to put multiple statments in one line python", not answers question directly, maybe somebody else needs this.

laravel select where and where condition

You either need to use first() or get() to fetch the results :

$userRecord = $this->where('email', $email)->where('password', $password)->first();

You most likely need to use first() as you want only one result returned.

If the record isn't found null will be returned. If you are building this query from inside an Eloquent class you could use self .

for example :

$userRecord = self::where('email', $email)->where('password', $password)->first();

More info here

iOS 7 status bar overlapping UI

Here is my approach using CSS and Javascript:

1) Define the following in your CSS:

#ios7-statusbar-fix {
    width:100%;
    height:20px;
    background-color:white;
    position:fixed;
    z-index:10000;
    margin-top:-20px;
    display:none;
}

2) Add div-container with this id as very first element after your <body>-tag:

<body>
    <div id="ios7-statusbar-fix"></div>
…

3) Filter iOS 7 devices and apply changes via Javascript:

if (navigator.userAgent.match(/(iPad.*|iPhone.*|iPod.*);.*CPU.*OS 7_\d/i)) {
        document.body.style.marginTop = '20px';
        document.getElementById('ios7-statusbar-fix').style.display = 'block';
}

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

How do I install the OpenSSL libraries on Ubuntu?

You want the openssl-devel package. At least I think it's -devel on Ubuntu. Might be -dev. It's one of the two.

How do I get the full path to a Perl script that is executing?

The problem with __FILE__ is that it will print the core module ".pm" path not necessarily the ".cgi" or ".pl" script path that is running. I guess it depends on what your goal is.

It seems to me that Cwd just needs to be updated for mod_perl. Here is my suggestion:

my $path;

use File::Basename;
my $file = basename($ENV{SCRIPT_NAME});

if (exists $ENV{MOD_PERL} && ($ENV{MOD_PERL_API_VERSION} < 2)) {
  if ($^O =~/Win/) {
    $path = `echo %cd%`;
    chop $path;
    $path =~ s!\\!/!g;
    $path .= $ENV{SCRIPT_NAME};
  }
  else {
    $path = `pwd`;
    $path .= "/$file";
  }
  # add support for other operating systems
}
else {
  require Cwd;
  $path = Cwd::getcwd()."/$file";
}
print $path;

Please add any suggestions.

jQuery.ajax returns 400 Bad Request

I was getting the 400 Bad Request error, even after setting:

contentType: "application/json",
dataType: "json"

The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.

This was my initial code:

var data = {
    "TestId": testId,
    "PlayerId": parseInt(playerId),
    "Result": result
};

var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
    url: url,
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify(data), // issue with a property type in the data object
    dataType: "json",
    error: function (e) {
        console.log(e); // logging the error object to console
    },
    success: function () {
        console.log('Success saving test result');
    }
});

Now after making the request, I checked the console tab in the browser development tool.
It looked like this: enter image description here

responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.

Changing the data object creation like below fixed the issue for me:

var data = {
        "TestId": String(testId), //converting testId to a string
        "PlayerId": parseInt(playerId),
        "Result": result
};

I assume other possible errors could also be identified by logging and inspecting the error object.

How to backup Sql Database Programmatically in C#

            SqlConnection con = new SqlConnection();
            SqlCommand sqlcmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            DataTable dt = new DataTable();

            con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
            string backupDIR = "~/BackupDB";
            string path = Server.MapPath(backupDIR);

            try
            {
                var databaseName = "MyFirstDatabase";
                con.Open();
                string saveFileName = "HiteshBackup";
                sqlcmd = new SqlCommand("backup database" +databaseName.BKSDatabaseName + "to disk='" + path + "\\" + saveFileName + ".Bak'", con);
                sqlcmd.ExecuteNonQuery();
                con.Close();                 


                ViewBag.Success = "Backup database successfully";
                return View("Create");
            }
            catch (Exception ex)
            {
                ViewBag.Error = "Error Occured During DB backup process !<br>" + ex.ToString();
                return View("Create");
            }

textarea character limit

I believe if you use delegates, it would work..

$("textarea").on('change paste keyup', function () {
    var currText = $(this).val();
    if (currText.length > 500) {
        var text = $(this).text();
        $(this).text(text.substr(0, 500));
        alert("You have reached the maximum length for this field");
    }
});

Can I have multiple :before pseudo-elements for the same element?

I've resolved this using:

.element:before {
    font-family: "Font Awesome 5 Free" , "CircularStd";
    content: "\f017" " Date";
}

Using the font family "font awesome 5 free" for the icon, and after, We have to specify the font that we are using again because if we doesn't do this, navigator will use the default font (times new roman or something like this).

Java check to see if a variable has been initialized

Instance variables or fields, along with static variables, are assigned default values based on the variable type:

  • int: 0
  • char: \u0000 or 0
  • double: 0.0
  • boolean: false
  • reference: null

Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

MySQL LEFT JOIN Multiple Conditions

Correct answer is simply:

SELECT a.group_id
FROM a 
LEFT JOIN b ON a.group_id=b.group_id  and b.user_id = 4
where b.user_id is null
  and a.keyword like '%keyword%'

Here we are checking user_id = 4 (your user id from the session). Since we have it in the join criteria, it will return null values for any row in table b that does not match the criteria - ie, any group that that user_id is NOT in.

From there, all we need to do is filter for the null values, and we have all the groups that your user is not in.

demo here

How to loop through a dataset in powershell?

Here's a practical example (build a dataset from your current location):

$ds = new-object System.Data.DataSet
$ds.Tables.Add("tblTest")
[void]$ds.Tables["tblTest"].Columns.Add("Name",[string])
[void]$ds.Tables["tblTest"].Columns.Add("Path",[string])

dir | foreach {
    $dr = $ds.Tables["tblTest"].NewRow()
    $dr["Name"] = $_.name
    $dr["Path"] = $_.fullname
    $ds.Tables["tblTest"].Rows.Add($dr)
}


$ds.Tables["tblTest"]

$ds.Tables["tblTest"] is an object that you can manipulate just like any other Powershell object:

$ds.Tables["tblTest"] | foreach {
    write-host 'Name value is : $_.name
    write-host 'Path value is : $_.path
}

Why is the Android emulator so slow? How can we speed up the Android emulator?

I had intermittent slow emulator (SDK v8.0) load times, up to three minutes on Intel Core i7 920 2.67 GHz CPU running on Xubuntu 10.04 VirtualBox 3.2.12 guest with Eclipse (3.6.1) loaded. I changed the VirtualBox guest memory from 1024 MB to 2048 MB and from that point on, I never experienced the slowness again (load times consistent at 33 seconds, CPU load consistent at 20%). Both Eclipse and the emulator are memory hogs.

Swap DIV position with CSS only

Assuming Nothing Follows Them

If these two div elements are basically your main layout elements, and nothing follows them in the html, then there is a pure HMTL/CSS solution that takes the normal order shown in this fiddle and is able to flip it vertically as shown in this fiddle using one additional wrapper div like so:

HTML

<div class="wrapper flipit">
   <div id="first_div">first div</div>
   <div id="second_div">second div</div>
</div>

CSS

.flipit {
    position: relative;
}
.flipit #first_div {
    position: absolute;
    top: 100%;
    width: 100%;
}

This would not work if elements follow these div's, as this fiddle illustrates the issue if the following elements are not wrapped (they get overlapped by #first_div), and this fiddle illustrates the issue if the following elements are also wrapped (the #first_div changes position with both the #second_div and the following elements). So that is why, depending on your use case, this method may or may not work.

For an overall layout scheme, where all other elements exist inside the two div's, it can work. For other scenarios, it will not.

AngularJS: Basic example to use authentication in Single Page Application

I answered a similar question here: AngularJS Authentication + RESTful API


I've written an AngularJS module for UserApp that supports protected/public routes, rerouting on login/logout, heartbeats for status checks, stores the session token in a cookie, events, etc.

You could either:

  1. Modify the module and attach it to your own API, or
  2. Use the module together with UserApp (a cloud-based user management API)

https://github.com/userapp-io/userapp-angular

If you use UserApp, you won't have to write any server-side code for the user stuff (more than validating a token). Take the course on Codecademy to try it out.

Here's some examples of how it works:

  • How to specify which routes that should be public, and which route that is the login form:

    $routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
    $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
    $routeProvider.when('/home', {templateUrl: 'partials/home.html'});
    

    The .otherwise() route should be set to where you want your users to be redirected after login. Example:

    $routeProvider.otherwise({redirectTo: '/home'});

  • Login form with error handling:

    <form ua-login ua-error="error-msg">
        <input name="login" placeholder="Username"><br>
        <input name="password" placeholder="Password" type="password"><br>
        <button type="submit">Log in</button>
        <p id="error-msg"></p>
    </form>
    
  • Signup form with error handling:

    <form ua-signup ua-error="error-msg">
      <input name="first_name" placeholder="Your name"><br>
      <input name="login" ua-is-email placeholder="Email"><br>
      <input name="password" placeholder="Password" type="password"><br>
      <button type="submit">Create account</button>
      <p id="error-msg"></p>
    </form>
    
  • Log out link:

    <a href="#" ua-logout>Log Out</a>

    (Ends the session and redirects to the login route)

  • Access user properties:

    User properties are accessed using the user service, e.g: user.current.email

    Or in the template: <span>{{ user.email }}</span>

  • Hide elements that should only be visible when logged in:

    <div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>

  • Show an element based on permissions:

    <div ua-has-permission="admin">You are an admin</div>

And to authenticate to your back-end services, just use user.token() to get the session token and send it with the AJAX request. At the back-end, use the UserApp API (if you use UserApp) to check if the token is valid or not.

If you need any help, just let me know!

Angularjs - simple form submit

WARNING This is for Angular 1.x

If you are looking for Angular (v2+, currently version 8), try this answer or the official guide.


ORIGINAL ANSWER

I have rewritten your JS fiddle here: http://jsfiddle.net/YGQT9/

<div ng-app="myApp">

    <form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">

        First name:    <br/><input type="text" name="form.firstname">    
        <br/><br/>

        Email Address: <br/><input type="text" ng-model="form.emailaddress"> 
        <br/><br/>

        <textarea rows="3" cols="25">
          Describe your reason for submitting this form ... 
        </textarea> 
        <br/>

        <input type="radio" ng-model="form.gender" value="female" />Female
        <input type="radio" ng-model="form.gender" value="male" />Male 
        <br/><br/>

        <input type="checkbox" ng-model="form.member" value="true"/> Already a member
        <input type="checkbox" ng-model="form.member" value="false"/> Not a member
        <br/>

        <input type="file" ng-model="form.file_profile" id="file_profile">
        <br/>

        <input type="file" ng-model="form.file_avatar" id="file_avatar">
        <br/><br/>

        <input type="submit">
    </form>
</div>

Here I'm using lots of angular directives(ng-controller, ng-model, ng-submit) where you were using basic html form submission. Normally all alternatives to "The angular way" work, but form submission is intercepted and cancelled by Angular to allow you to manipulate the data before submission

BUT the JSFiddle won't work properly as it doesn't allow any type of ajax/http post/get so you will have to run it locally.

For general advice on angular form submission see the cookbook examples

UPDATE The cookbook is gone. Instead have a look at the 1.x guide for for form submission

The cookbook for angular has lots of sample code which will help as the docs aren't very user friendly.

Angularjs changes your entire web development process, don't try doing things the way you are used to with JQuery or regular html/js, but for everything you do take a look around for some sample code, as there is almost always an angular alternative.

How can I detect whether an iframe is loaded?

You can try onload event as well;

var createIframe = function (src) {
        var self = this;
        $('<iframe>', {
            src: src,
            id: 'iframeId',
            frameborder: 1,
            scrolling: 'no',
            onload: function () {
                self.isIframeLoaded = true;
                console.log('loaded!');
            }
        }).appendTo('#iframeContainer');

    };

How do I automatically set the $DISPLAY variable for my current session?

do you use Bash? Go to the file .bashrc in your home directory and set the variable, then export it.

DISPLAY=localhost:0.0 ; export DISPLAY

you can use /etc/bashrc if you want to do it for all the users.

You may also want to look in ~/.bash_profile and /etc/profile

EDIT:

function get_xserver ()
{
    case $TERM in
       xterm )
            XSERVER=$(who am i | awk '{print $NF}' | tr -d ')''(' )    
            XSERVER=${XSERVER%%:*}
            ;;
        aterm | rxvt)           
            ;;
    esac  
}

if [ -z ${DISPLAY:=""} ]; then
    get_xserver
    if [[ -z ${XSERVER}  || ${XSERVER} == $(hostname) || \
      ${XSERVER} == "unix" ]]; then 
        DISPLAY=":0.0"          # Display on local host.
    else
        DISPLAY=${XSERVER}:0.0  # Display on remote host.
    fi
fi

export DISPLAY

Checking that a List is not empty in Hamcrest

Well there's always

assertThat(list.isEmpty(), is(false));

... but I'm guessing that's not quite what you meant :)

Alternatively:

assertThat((Collection)list, is(not(empty())));

empty() is a static in the Matchers class. Note the need to cast the list to Collection, thanks to Hamcrest 1.2's wonky generics.

The following imports can be used with hamcrest 1.3

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.*;

Selecting a row in DataGridView programmatically

You can use the Select method if you have a datasource: http://msdn.microsoft.com/en-us/library/b51xae2y%28v=vs.71%29.aspx

Or use linq if you have objects in you datasource

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

Facebook Open Graph Error - Inferred Property

In my case an unexpected error notice in the source code stopped the facebook crawler from parsing the (correctly set) og-meta tags.

I was using the HTTP_ACCEPT_LANGUAGE header, which worked fine for regular browser requests but not for the crawler, as it obviously won't use/set it.

Therefore, it was crucial for me to use the facebook's debugger feature See exactly what our scraper sees for your URL, as the error notice only could only be seen there (but not through the regular 'view source code'-browser feature).

screenshot of the facebook debugger

Improving bulk insert performance in Entity framework

In Azure environment with Basic website that has 1 Instance.I tried to insert a Batch of 1000 records at a time out of 25000 records using for loop it took 11.5 min but in parallel execution it took less than a minute.So I recommend using TPL(Task Parallel Library).

         var count = (you collection / 1000) + 1;
         Parallel.For(0, count, x =>
        {
            ApplicationDbContext db1 = new ApplicationDbContext();
            db1.Configuration.AutoDetectChangesEnabled = false;

            var records = members.Skip(x * 1000).Take(1000).ToList();
            db1.Members.AddRange(records).AsParallel();

            db1.SaveChanges();
            db1.Dispose();
        });

Read file content from S3 bucket with boto3

boto3 offers a resource model that makes tasks like iterating through objects easier. Unfortunately, StreamingBody doesn't provide readline or readlines.

s3 = boto3.resource('s3')
bucket = s3.Bucket('test-bucket')
# Iterates through all the objects, doing the pagination for you. Each obj
# is an ObjectSummary, so it doesn't contain the body. You'll need to call
# get to get the whole body.
for obj in bucket.objects.all():
    key = obj.key
    body = obj.get()['Body'].read()

Difference between parameter and argument

Argument is often used in the sense of actual argument vs. formal parameter.

The formal parameter is what is given in the function declaration/definition/prototype, while the actual argument is what is passed when calling the function — an instance of a formal parameter, if you will.

That being said, they are often used interchangeably, their exact use depending on different programming languages and their communities. For example, I have also heard actual parameter etc.

So here, x and y would be formal parameters:

int foo(int x, int y) {
    ...
}

Whereas here, in the function call, 5 and z are the actual arguments:

foo(5, z);

excel formula to subtract number of days from a date

You can paste it like this:

= "2010-12-20" - 180

And don't forget to format the cell as a Date [CTRL]+[F1] / Number Tab

How to get value of selected radio button?

var rates = document.getElementById('rates').value;

The rates element is a div, so it won't have a value. This is probably where the undefined is coming from.

The checked property will tell you whether the element is selected:

if (document.getElementById('r1').checked) {
  rate_value = document.getElementById('r1').value;
}

RegEx for matching "A-Z, a-z, 0-9, _" and "."

Working from what you've given I'll assume you want to check that someone has NOT entered any letters other than the ones you've listed. For that to work you want to search for any characters other than those listed:

[^A-Za-z0-9_.]

And use that in a match in your code, something like:

if ( /[^A-Za-z0-9_.]/.match( your_input_string ) ) {
   alert( "you have entered invalid data" );
}

Hows that?

Use of PUT vs PATCH methods in REST API real life scenarios

To conclude the discussion on the idempotency, I should note that one can define idempotency in the REST context in two ways. Let's first formalize a few things:

A resource is a function with its codomain being the class of strings. In other words, a resource is a subset of String × Any, where all the keys are unique. Let's call the class of the resources Res.

A REST operation on resources, is a function f(x: Res, y: Res): Res. Two examples of REST operations are:

  • PUT(x: Res, y: Res): Res = x, and
  • PATCH(x: Res, y: Res): Res, which works like PATCH({a: 2}, {a: 1, b: 3}) == {a: 2, b: 3}.

(This definition is specifically designed to argue about PUT and POST, and e.g. doesn't make much sense on GET and POST, as it doesn't care about persistence).

Now, by fixing x: Res (informatically speaking, using currying), PUT(x: Res) and PATCH(x: Res) are univariate functions of type Res ? Res.

  1. A function g: Res ? Res is called globally idempotent, when g ? g == g, i.e. for any y: Res, g(g(y)) = g(y).

  2. Let x: Res a resource, and k = x.keys. A function g = f(x) is called left idempotent, when for each y: Res, we have g(g(y))|? == g(y)|?. It basically means that the result should be same, if we look at the applied keys.

So, PATCH(x) is not globally idempotent, but is left idempotent. And left idempotency is the thing that matters here: if we patch a few keys of the resource, we want those keys to be same if we patch it again, and we don't care about the rest of the resource.

And when RFC is talking about PATCH not being idempotent, it is talking about global idempotency. Well, it's good that it's not globally idempotent, otherwise it would have been a broken operation.


Now, Jason Hoetger's answer is trying to demonstrate that PATCH is not even left idempotent, but it's breaking too many things to do so:

  • First of all, PATCH is used on a set, although PATCH is defined to work on maps / dictionaries / key-value objects.
  • If someone really wants to apply PATCH to sets, then there is a natural translation that should be used: t: Set<T> ? Map<T, Boolean>, defined with x in A iff t(A)(x) == True. Using this definition, patching is left idempotent.
  • In the example, this translation was not used, instead, the PATCH works like a POST. First of all, why is an ID generated for the object? And when is it generated? If the object is first compared to the elements of the set, and if no matching object is found, then the ID is generated, then again the program should work differently ({id: 1, email: "[email protected]"} must match with {email: "[email protected]"}, otherwise the program is always broken and the PATCH cannot possibly patch). If the ID is generated before checking against the set, again the program is broken.

One can make examples of PUT being non-idempotent with breaking half of the things that are broken in this example:

  • An example with generated additional features would be versioning. One may keep record of the number of changes on a single object. In this case, PUT is not idempotent: PUT /user/12 {email: "[email protected]"} results in {email: "...", version: 1} the first time, and {email: "...", version: 2} the second time.
  • Messing with the IDs, one may generate a new ID every time the object is updated, resulting in a non-idempotent PUT.

All the above examples are natural examples that one may encounter.


My final point is, that PATCH should not be globally idempotent, otherwise won't give you the desired effect. You want to change the email address of your user, without touching the rest of the information, and you don't want to overwrite the changes of another party accessing the same resource.

How to call a function after a div is ready?

Through jQuery.ready function you can specify function that's executed when DOM is loaded. Whole DOM, not any div you want.

So, you should use ready in a bit different way

$.ready(function() {
    createGrid();
});

This is in case when you dont use AJAX to load your div

Count distinct values

You can do a distinct count as follows:

SELECT COUNT(DISTINCT column_name) FROM table_name;

EDIT:

Following your clarification and update to the question, I see now that it's quite a different question than we'd originally thought. "DISTINCT" has special meaning in SQL. If I understand correctly, you want something like this:

  • 2 customers had 1 pets
  • 3 customers had 2 pets
  • 1 customers had 3 pets

Now you're probably going to want to use a subquery:

select COUNT(*) column_name FROM (SELECT DISTINCT column_name);

Let me know if this isn't quite what you're looking for.

How to make the python interpreter correctly handle non-ASCII characters in string operations?

I know it's an old thread, but I felt compelled to mention the translate method, which is always a good way to replace all character codes above 128 (or other if necessary).

Usage : str.translate(table[, deletechars])

>>> trans_table = ''.join( [chr(i) for i in range(128)] + [' '] * 128 )

>>> 'Résultat'.translate(trans_table)
'R sultat'
>>> '6Â 918Â 417Â 712'.translate(trans_table)
'6  918  417  712'

Starting with Python 2.6, you can also set the table to None, and use deletechars to delete the characters you don't want as in the examples shown in the standard docs at http://docs.python.org/library/stdtypes.html.

With unicode strings, the translation table is not a 256-character string but a dict with the ord() of relevant characters as keys. But anyway getting a proper ascii string from a unicode string is simple enough, using the method mentioned by truppo above, namely : unicode_string.encode("ascii", "ignore")

As a summary, if for some reason you absolutely need to get an ascii string (for instance, when you raise a standard exception with raise Exception, ascii_message ), you can use the following function:

trans_table = ''.join( [chr(i) for i in range(128)] + ['?'] * 128 )
def ascii(s):
    if isinstance(s, unicode):
        return s.encode('ascii', 'replace')
    else:
        return s.translate(trans_table)

The good thing with translate is that you can actually convert accented characters to relevant non-accented ascii characters instead of simply deleting them or replacing them by '?'. This is often useful, for instance for indexing purposes.

How to change the font size on a matplotlib plot

If you are a control freak like me, you may want to explicitly set all your font sizes:

import matplotlib.pyplot as plt

SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 12

plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title

Note that you can also set the sizes calling the rc method on matplotlib:

import matplotlib

SMALL_SIZE = 8
matplotlib.rc('font', size=SMALL_SIZE)
matplotlib.rc('axes', titlesize=SMALL_SIZE)

# and so on ...

How to get values from selected row in DataGrid for Windows Form Application?

Description

Assuming i understand your question.

You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.

Sample

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Information

AngularJS : Difference between the $observe and $watch methods

Why is $observe different than $watch?

The watchExpression is evaluated and compared to the previous value each digest() cycle, if there's a change in the watchExpression value, the watch function is called.

$observe is specific to watching for interpolated values. If a directive's attribute value is interpolated, eg dir-attr="{{ scopeVar }}", the observe function will only be called when the interpolated value is set (and therefore when $digest has already determined updates need to be made). Basically there's already a watcher for the interpolation, and the $observe function piggybacks off that.

See $observe & $set in compile.js

How to use auto-layout to move other views when a view is hidden?

I think this is the most simple answer. Please verify that it works:

        StackFullView.layer.isHidden = true
        Task_TopSpaceSections.constant = 0.   //your constraint of top view

check here https://www.youtube.com/watch?v=EBulMWMoFuw

creating a random number using MYSQL

As RAND produces a number 0 <= v < 1.0 (see documentation) you need to use ROUND to ensure that you can get the upper bound (500 in this case) and the lower bound (100 in this case)

So to produce the range you need:

SELECT name, address, ROUND(100.0 + 400.0 * RAND()) AS random_number
FROM users

How to use classes from .jar files?

Not every jar file is executable.

Now, you need to import the classes, which are there under the jar, in your java file. For example,

import org.xml.sax.SAXException;

If you are working on an IDE, then you should refer its documentation. Or at least specify which one you are using here in this thread. It would definitely enable us to help you further.

And if you are not using any IDE, then please look at javac -cp option. However, it's much better idea to package your program in a jar file, and include all the required jars within that. Then, in order to execute your jar, like,

java -jar my_program.jar

you should have a META-INF/MANIFEST.MF file in your jar. See here, for how-to.

How to pass variable as a parameter in Execute SQL Task SSIS?

A little late to the party, but this is how I did it for an insert:

DECLARE @ManagerID AS Varchar (25) = 'NA'
DECLARE @ManagerEmail AS Varchar (50) = 'NA'
Declare @RecordCount AS int = 0

SET @ManagerID = ?
SET @ManagerEmail = ?
SET @RecordCount = ?

INSERT INTO...

Difference between using "chmod a+x" and "chmod 755"

Yes - different

chmod a+x will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others and group.

chmod 755 will always make the file with perms 755 no matter what initial permissions were.

This may or may not matter for your script.

Get file from project folder java

If you don't specify any path and put just the file (Just like you did), the default directory is always the one of your project (It's not inside the "src" folder. It's just inside the folder of your project).

How to left align a fixed width string?

With the new and popular f-strings in Python 3.6, here is how we left-align say a string with 16 padding length:

string = "Stack Overflow"
print(f"{string:<16}..")
Stack Overflow  ..

If you have variable padding length:

k = 20
print(f"{string:<{k}}..")
Stack Overflow      .. 

f-strings are more compact.

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

how to kill hadoop jobs

Run list to show all the jobs, then use the jobID/applicationID in the appropriate command.

Kill mapred jobs:

mapred job -list
mapred job -kill <jobId>

Kill yarn jobs:

yarn application -list
yarn application -kill <ApplicationId>

Gets byte array from a ByteBuffer in java

final ByteBuffer buffer;
if (buffer.hasArray()) {
    final byte[] array = buffer.array();
    final int arrayOffset = buffer.arrayOffset();
    return Arrays.copyOfRange(array, arrayOffset + buffer.position(),
                              arrayOffset + buffer.limit());
}
// do something else

iTerm2 keyboard shortcut - split pane navigation

From the documentation:

Cmd] and Cmd[ navigates among split panes in order of use.

How to change the JDK for a Jenkins job?

Be careful with jobs

1 - if you have a job based in maven, Jenkins takes your default java configuration and you decide the compilation level in your POM.XML.

2 - if you have a free style job, in the the configuration option of the job you can select the JDK that you want to use.

Hope this help.

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

This is quite late but anyone going through the same problem might benefit from this answer.First try to add browser by running below command ionic platform add browser and then run command ionic run browser.

which is the difference between ionic serve and ionic run browser?

Ionic serve - runs your app as a website (meaning it doesn't have any Cordova capabilities). Ionic run browser - runs your app in the Cordova browser platform, which will inject cordova.js and any plugins that have browser capabilities

You can refer this link to know more difference between ionic serve and ionic run browser command

Update

From Ionic 3 this command has been changed. Use the command below instead;

ionic cordova platform add browser

ionic cordova run browser

You can find out which version of ionic you are using by running: ionic --version

Failed to load AppCompat ActionBar with unknown error in android studio

I also had this problem with implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'.

The solution for me was to go File -> Invalidate Caches / Restart -> Invalidate -> Close Project -> Remove project from project window -> Open Project (from project window).

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

A new (Keller) method is supposed to improve speed over the -9999px method:

.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}

recommended here:http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/

Specify an SSH key for git push for a given domain

From git 2.10 upwards it is also possible to use the gitconfig sshCommand setting. Docs state :

If this variable is set, git fetch and git push will use the specified command instead of ssh when they need to connect to a remote system. The command is in the same form as the GIT_SSH_COMMAND environment variable and is overridden when the environment variable is set.

An usage example would be: git config core.sshCommand "ssh -i ~/.ssh/[insert_your_keyname]

In some cases this doesn't work because ssh_config overriding the command, in this case try ssh -i ~/.ssh/[insert_your_keyname] -F /dev/null to not use the ssh_config.

In Angular, how to add Validator to FormControl after control is created?

To add onto what @Delosdos has posted.

Set a validator for a control in the FormGroup: this.myForm.controls['controlName'].setValidators([Validators.required])

Remove the validator from the control in the FormGroup: this.myForm.controls['controlName'].clearValidators()

Update the FormGroup once you have run either of the above lines. this.myForm.controls['controlName'].updateValueAndValidity()

This is an amazing way to programmatically set your form validation.

Converting characters to integers in Java

43 is the dec ascii number for the "+" symbol. That explains why you get a 43 back. http://en.wikipedia.org/wiki/ASCII

Avoiding NullPointerException in Java

If null-values are not allowed

If your method is called externally, start with something like this:

public void method(Object object) {
  if (object == null) {
    throw new IllegalArgumentException("...");
  }

Then, in the rest of that method, you'll know that object is not null.

If it is an internal method (not part of an API), just document that it cannot be null, and that's it.

Example:

public String getFirst3Chars(String text) {
  return text.subString(0, 3);
}

However, if your method just passes the value on, and the next method passes it on etc. it could get problematic. In that case you may want to check the argument as above.

If null is allowed

This really depends. If find that I often do something like this:

if (object == null) {
  // something
} else {
  // something else
}

So I branch, and do two completely different things. There is no ugly code snippet, because I really need to do two different things depending on the data. For example, should I work on the input, or should I calculate a good default value?


It's actually rare for me to use the idiom "if (object != null && ...".

It may be easier to give you examples, if you show examples of where you typically use the idiom.

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

Process with an ID #### is not running in visual studio professional 2013 update 3

Easily solved:

  1. Open Visual Studio as an administrator
  2. Right-click your project and click on 'Unload Project'
  3. Again, right-click your project and click on 'Edit PROJECT_NAME.csproj'
  4. Find the code below and delete it:

    <DevelopmentServerPort>63366</DevelopmentServerPort>
    <DevelopmentServerVPath>/</DevelopmentServerVPath>
    <IISUrl>http://localhost:63366/</IISUrl>
    
  5. Save and close the file .csproj

  6. Right-click your project and reload it
  7. See its working

Shortcut to open file in Vim

Consider using CtrlP plug-in.

It is included in Janus Distributive.

Allows you to find files in the current directory, open buffers or most recently used files using "fuzzy matching" or regular expression.

Install .ipa to iPad with or without iTunes

I try to face with these problems and I use : https://www.installonair.com . It's free and not have limit like diawi.

  1. You need to add device UDID to apple developer account devices part.
  2. Build your project and archieve it ad hoc with your certificate
  3. Open that link and upload your ad hoc ipa file to website
  4. Get qr code and link to download.

Git Pull vs Git Rebase

In a nutshell :

-> Git Merge: It will simply merge your local changes and remote changes, and that will create another commit history record

-> Git Rebase: It will put your changes above all new remote changes, and rewrite commit history, so your commit history will be much cleaner than git merge. Rebase is a destructive operation. That means, if you do not apply it correctly, you could lose committed work and/or break the consistency of other developer's repositories.

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

How to style a div to be a responsive square?

HTML

<div class='square-box'>
    <div class='square-content'>
        <h3>test</h3>
    </div>
</div>

CSS

.square-box{
    position: relative;
    width: 50%;
    overflow: hidden;
    background: #4679BD;
}
.square-box:before{
    content: "";
    display: block;
    padding-top: 100%;
}
.square-content{
    position:  absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    color: white;
    text-align: center;
}

http://jsfiddle.net/38Tnx/1425/

How to calculate the time interval between two time strings

Try this

import datetime
import time
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
time.sleep(5)
end_time = datetime.datetime.now().time().strftime('%H:%M:%S')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
print total_time

OUTPUT :

0:00:05

How to pause for specific amount of time? (Excel/VBA)

Just a cleaned up version of clemo's code - works in Access, which doesn't have the Application.Wait function.

Public Sub Pause(sngSecs As Single)
    Dim sngEnd As Single
    sngEnd = Timer + sngSecs
    While Timer < sngEnd
        DoEvents
    Wend
End Sub

Public Sub TestPause()
    Pause 1
    MsgBox "done"
End Sub

C#: Converting byte array to string and printing out to console

I've used this simple code in my codebase:

static public string ToReadableByteArray(byte[] bytes)
{
    return string.Join(", ", bytes);
}

To use:

Console.WriteLine(ToReadableByteArray(bytes));

List file using ls command in Linux with full path

For listing everything with full path, only in current directory

find $PWD -maxdepth 1

Same as above but only matches a particular extension, case insensitive (.sh files in this case)

find $PWD -maxdepth 1 -iregex '.+\.sh'

$PWD is for current directory, it can be replaced with any directory

mydir="/etc/sudoers.d/" ; find $mydir -maxdepth 1

maxdepth prevents find from going into subdirectories, for example you can set it to "2" for listing items in children as well. Simply remove it if you need it recursive.

To limit it to only files, can use -type f option.

find $PWD -maxdepth 1 -type f

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

I had installed Python 32 bit version and psycopg2 64 bit version to get this problem. I installed psycopg2 32 bit version and then it worked.

How to reverse MD5 to get the original string?

No, that's not really possible, as

  • there can be more than one string giving the same MD5
  • it was designed to be hard to "reverse"

The goal of the MD5 and its family of hashing functions is

  • to get short "extracts" from long string
  • to make it hard to guess where they come from
  • to make it hard to find collisions, that is other words having the same hash (which is a very similar exigence as the second one)

Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.

This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...

Setting format and value in input type="date"

The format is YYYY-MM-DD. You cannot change it.

$('#myinput').val('2013-12-31'); sets value

Left Join With Where Clause

When making OUTER JOINs (ANSI-89 or ANSI-92), filtration location matters because criteria specified in the ON clause is applied before the JOIN is made. Criteria against an OUTER JOINed table provided in the WHERE clause is applied after the JOIN is made. This can produce very different result sets. In comparison, it doesn't matter for INNER JOINs if the criteria is provided in the ON or WHERE clauses -- the result will be the same.

  SELECT  s.*, 
          cs.`value`
     FROM SETTINGS s
LEFT JOIN CHARACTER_SETTINGS cs ON cs.setting_id = s.id
                               AND cs.character_id = 1

Call to undefined function oci_connect()

Download from Instant Client for Microsoft Windows (x64) and extract the files below to "c:\oracle":

instantclient-basic-windows.x64-12.1.0.2.0.zip

instantclient-sqlplus-windows.x64-12.1.0.2.0.zip

instantclient-sdk-windows.x64-12.1.0.2.0.zip This will create the following folder "C:\Oracle\instantclient_12_1".

Finally, add the "C:\Oracle\instantclient_12_1" folder to the PATH enviroment variable, placing it on the leftmost place.

Then Restart your server.

How do I write outputs to the Log in Android?

Please see the logs as this way,

Log.e("ApiUrl = ", "MyApiUrl") (error)
Log.w("ApiUrl = ", "MyApiUrl") (warning)
Log.i("ApiUrl = ", "MyApiUrl") (information)
Log.d("ApiUrl = ", "MyApiUrl") (debug)
Log.v("ApiUrl = ", "MyApiUrl") (verbose)

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

As Darren commented, Apache don't understand php.ini relative paths in Windows.

To fix it, change the relative paths in your php.ini to absolute paths.

extension_dir="C:\full\path\to\php\ext\dir"

Button background as transparent

Add this in your Xml - android:background="@android:color/transparent"

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Button"
            android:background="@android:color/transparent"
            android:textStyle="bold"/>

How can I run multiple curl requests processed sequentially?

Another crucial method not mentioned here is using the same TCP connection for multiple HTTP requests, and exactly one curl command for this.

This is very useful to save network bandwidth, client and server resources, and overall the need of using multiple curl commands, as curl by default closes the connection when end of command is reached.

Keeping the connection open and reusing it is very common for standard clients running a web-app.

Starting curl version 7.36.0, the --next or -: command-line option allows to chain multiple requests, and usable both in command-line and scripting.

For example:

  • Sending multiple requests on the same TCP connection:

curl http://example.com/?update_=1 -: http://example.com/foo

  • Sending multiple different HTTP requests on the same connection:

curl http://example.com/?update_=1 -: -d "I am posting this string" http://example.com/?update_=2

  • Sending multiple HTTP requests with different curl options for each request:

curl -o 'my_output_file' http://example.com/?update_=1 -: -d "my_data" -s -m 10 http://example.com/foo -: -o /dev/null http://example.com/random

From the curl manpage:

-:, --next

Tells curl to use a separate operation for the following URL and associated options. This allows you to send several URL requests, each with their own specific options, for example, such as different user names or custom requests for each.

-:, --next will reset all local options and only global ones will have their values survive over to the operation following the -:, --next instruction. Global options include -v, --verbose, --trace, --trace-ascii and --fail-early.

For example, you can do both a GET and a POST in a single command line:

curl www1.example.com --next -d postthis www2.example.com

Added in 7.36.0.

Regular Expression to match valid dates

I landed here because the title of this question is broad and I was looking for a regex that I could use to match on a specific date format (like the OP). But I then discovered, as many of the answers and comments have comprehensively highlighted, there are many pitfalls that make constructing an effective pattern very tricky when extracting dates that are mixed-in with poor quality or non-structured source data.

In my exploration of the issues, I have come up with a system that enables you to build a regular expression by arranging together four simpler sub-expressions that match on the delimiter, and valid ranges for the year, month and day fields in the order you require.

These are :-

Delimeters

[^\w\d\r\n:] 

This will match anything that is not a word character, digit character, carriage return, new line or colon. The colon has to be there to prevent matching on times that look like dates (see my test Data)

You can optimise this part of the pattern to speed up matching, but this is a good foundation that detects most valid delimiters.

Note however; It will match a string with mixed delimiters like this 2/12-73 that may not actually be a valid date.

Year Values

(\d{4}|\d{2})

This matches a group of two or 4 digits, in most cases this is acceptable, but if you're dealing with data from the years 0-999 or beyond 9999 you need to decide how to handle that because in most cases a 1, 3 or >4 digit year is garbage.

Month Values

(0?[1-9]|1[0-2])

Matches any number between 1 and 12 with or without a leading zero - note: 0 and 00 is not matched.

Date Values

(0?[1-9]|[12]\d|30|31)

Matches any number between 1 and 31 with or without a leading zero - note: 0 and 00 is not matched.

This expression matches Date, Month, Year formatted dates

(0?[1-9]|[12]\d|30|31)[^\w\d\r\n:](0?[1-9]|1[0-2])[^\w\d\r\n:](\d{4}|\d{2})

But it will also match some of the Year, Month Date ones. It should also be bookended with the boundary operators to ensure the whole date string is selected and prevent valid sub-dates being extracted from data that is not well-formed i.e. without boundary tags 20/12/194 matches as 20/12/19 and 101/12/1974 matches as 01/12/1974

Compare the results of the next expression to the one above with the test data in the nonsense section (below)

\b(0?[1-9]|[12]\d|30|31)[^\w\d\r\n:](0?[1-9]|1[0-2])[^\w\d\r\n:](\d{4}|\d{2})\b

There's no validation in this regex so a well-formed but invalid date such as 31/02/2001 would be matched. That is a data quality issue, and as others have said, your regex shouldn't need to validate the data.

Because you (as a developer) can't guarantee the quality of the source data you do need to perform and handle additional validation in your code, if you try to match and validate the data in the RegEx it gets very messy and becomes difficult to support without very concise documentation.

Garbage in, garbage out.

Having said that, if you do have mixed formats where the date values vary, and you have to extract as much as you can; You can combine a couple of expressions together like so;

This (disastrous) expression matches DMY and YMD dates

(\b(0?[1-9]|[12]\d|30|31)[^\w\d\r\n:](0?[1-9]|1[0-2])[^\w\d\r\n:](\d{4}|\d{2})\b)|(\b(0?[1-9]|1[0-2])[^\w\d\r\n:](0?[1-9]|[12]\d|30|31)[^\w\d\r\n:](\d{4}|\d{2})\b)

BUT you won't be able to tell if dates like 6/9/1973 are the 6th of September or the 9th of June. I'm struggling to think of a scenario where that is not going to cause a problem somewhere down the line, it's bad practice and you shouldn't have to deal with it like that - find the data owner and hit them with the governance hammer.

Finally, if you want to match a YYYYMMDD string with no delimiters you can take some of the uncertainty out and the expression looks like this

\b(\d{4})(0[1-9]|1[0-2])(0[1-9]|[12]\d|30|31)\b

But note again, it will match on well-formed but invalid values like 20010231 (31th Feb!) :)

Test data

In experimenting with the solutions in this thread I ended up with a test data set that includes a variety of valid and non-valid dates and some tricky situations where you may or may not want to match i.e. Times that could match as dates and dates on multiple lines.

I hope this is useful to someone.

Valid Dates in various formats

Day, month, year
2/11/73
02/11/1973
2/1/73
02/01/73
31/1/1973
02/1/1973
31.1.2011
31-1-2001
29/2/1973
29/02/1976 
03/06/2010
12/6/90

month, day, year
02/24/1975 
06/19/66 
03.31.1991
2.29.2003
02-29-55
03-13-55
03-13-1955
12\24\1974
12\30\1974
1\31\1974
03/31/2001
01/21/2001
12/13/2001

Match both DMY and MDY
12/12/1978
6/6/78
06/6/1978
6/06/1978

using whitespace as a delimiter

13 11 2001
11 13 2001
11 13 01 
13 11 01
1 1 01
1 1 2001

Year Month Day order
76/02/02
1976/02/29
1976/2/13
76/09/31

YYYYMMDD sortable format
19741213
19750101

Valid dates before Epoch
12/1/10
12/01/660
12/01/00
12/01/0000

Valid date after 2038

01/01/2039
01/01/39

Valid date beyond the year 9999

01/01/10000

Dates with leading or trailing characters

12/31/21/
31/12/1921AD
31/12/1921.10:55
12/10/2016  8:26:00.39
wfuwdf12/11/74iuhwf
fwefew13/11/1974
01/12/1974vdwdfwe
01/01/99werwer
12321301/01/99

Times that look like dates

12:13:56
13:12:01
1:12:01PM
1:12:01 AM

Dates that runs across two lines

1/12/19
74

01/12/19
74/13/1946

31/12/20
08:13

Invalid, corrupted or nonsense dates

0/1/2001
1/0/2001
00/01/2100
01/0/2001
0101/2001
01/131/2001
31/31/2001
101/12/1974
56/56/56
00/00/0000
0/0/1999
12/01/0
12/10/-100
74/2/29
12/32/45
20/12/194

2/12-73

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

no such table found is mainly when you have not opened the SQLiteOpenHelper class with getwritabledata() and before this you also have to call make constructor with databasename & version. And OnUpgrade is called whenever there is upgrade value in version number given in SQLiteOpenHelper class.

Below is the code snippet (No such column found may be because of spell in column name):

public class database_db {
    entry_data endb;
    String file_name="Record.db";
    SQLiteDatabase sq;
    public database_db(Context c)
    {
        endb=new entry_data(c, file_name, null, 8);
    }
    public database_db open()
    {
        sq=endb.getWritableDatabase();
        return this;
    }
    public Cursor getdata(String table)
    {
        return sq.query(table, null, null, null, null, null, null);
    }
    public long insert_data(String table,ContentValues value)
    {
        return sq.insert(table, null, value);
    }
    public void close()
    {
        sq.close();
    }
    public void delete(String table)
    {
        sq.delete(table,null,null);
    }
}
class entry_data extends SQLiteOpenHelper
{

    public entry_data(Context context, String name, SQLiteDatabase.CursorFactory factory,
                      int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase sqdb) {
        // TODO Auto-generated method stub

        sqdb.execSQL("CREATE TABLE IF NOT EXISTS 'YOUR_TABLE_NAME'(Column_1 text not null,Column_2 text not null);");

    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          onCreate(db);
    }

}

How to get a index value from foreach loop in jstl

I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.

It can use for use to read for Zeor base index or 1 one base index.

${loop.count}` it will give 1 starting base index.

${loop.index} it will give 0 base index as normal Index of array start from 0.

For Example :

<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
   <source srcset="${currentImage}" media="(min-width: 1000px)"></source>
   <source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
   <img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>

For more Info please refer this link

Swift: Convert enum value to String?

The idiomatic interface for 'getting a String' is to use the CustomStringConvertible interface and access the description getter. Define your enum as:

enum Foo : CustomStringConvertible {
  case Bing
  case Bang
  case Boom
  
  var description : String { 
    switch self {
    // Use Internationalization, as appropriate.
    case .Bing: return "Bing"
    case .Bang: return "Bang"
    case .Boom: return "Boom"
    }
  }
}

In action:

 > let foo = Foo.Bing
foo: Foo = Bing
 > println ("String for 'foo' is \(foo)"
String for 'foo' is Bing

Updated: For Swift >= 2.0, replaced Printable with CustomStringConvertible

Note: Using CustomStringConvertible allows Foo to adopt a different raw type. For example enum Foo : Int, CustomStringConvertible { ... } is possible. This freedom can be useful.

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

This works fine for me

 // assuming this fills the List
 List<Dictionary<string, string>> obj = this.getData(); 

 List<Dictionary<string, string>> objCopy = new List<Dictionary<string, string>>(obj);

As Tomer Wolberg describes in the comments, this does not work if the value type is a mutable class.

onclick or inline script isn't working in extension

Reason

This does not work, because Chrome forbids any kind of inline code in extensions via Content Security Policy.

Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).

How to detect

If this is indeed the problem, Chrome would produce the following error in the console:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

To access a popup's JavaScript console (which is useful for debug in general), right-click your extension's button and select "Inspect popup" from the context menu.

More information on debugging a popup is available here.

How to fix

One needs to remove all inline JavaScript. There is a guide in Chrome documentation.

Suppose the original looks like:

<a onclick="handler()">Click this</a> <!-- Bad -->

One needs to remove the onclick attribute and give the element a unique id:

<a id="click-this">Click this</a> <!-- Fixed -->

And then attach the listener from a script (which must be in a .js file, suppose popup.js):

// Pure JS:
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("click-this").addEventListener("click", handler);
});

// The handler also must go in a .js file
function handler() {
  /* ... */
}

Note the wrapping in a DOMContentLoaded event. This ensures that the element exists at the time of execution. Now add the script tag, for instance in the <head> of the document:

<script src="popup.js"></script>

Alternative if you're using jQuery:

// jQuery
$(document).ready(function() {
  $("#click-this").click(handler);
});

Relaxing the policy

Q: The error mentions ways to allow inline code. I don't want to / can't change my code, how do I enable inline scripts?

A: Despite what the error says, you cannot enable inline script:

There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes 'unsafe-inline' will have no effect.

Update: Since Chrome 46, it's possible to whitelist specific inline code blocks:

As of Chrome 46, inline scripts can be whitelisted by specifying the base64-encoded hash of the source code in the policy. This hash must be prefixed by the used hash algorithm (sha256, sha384 or sha512). See Hash usage for <script> elements for an example.

However, I do not readily see a reason to use this, and it will not enable inline attributes like onclick="code".

How to count duplicate rows in pandas dataframe?

If you like to count duplicates on particular column(s):

len(df['one'])-len(df['one'].drop_duplicates())

If you want to count duplicates on entire dataframe:

len(df)-len(df.drop_duplicates())

Or simply you can use DataFrame.duplicated(subset=None, keep='first'):

df.duplicated(subset='one', keep='first').sum()

where

subset : column label or sequence of labels(by default use all of the columns)

keep : {‘first’, ‘last’, False}, default ‘first’

  • first : Mark duplicates as True except for the first occurrence.
  • last : Mark duplicates as True except for the last occurrence.
  • False : Mark all duplicates as True.

What is the difference between atan and atan2 in C++?

I guess the main question tries to figure out: "when should I use one or the other", or "which should I use", or "Am I using the right one"?

I guess the important point is atan only was intended to feed positive values in a right-upwards direction curve like for time-distance vectors. Cero is always at the bottom left, and thigs can only go up and right, just slower or faster. atan doesn't return negative numbers, so you can't trace things in the 4 directions on a screen just by adding/subtracting its result.

atan2 is intended for the origin to be in the middle, and things can go backwards or down. That's what you'd use in a screen representation, because it DOES matter what direction you want the curve to go. So atan2 can give you negative numbers, because its cero is in the center, and its result is something you can use to trace things in 4 directions.

Java: Date from unix timestamp

Date d = new Date(i * 1000 + TimeZone.getDefault().getRawOffset());

Better way to find index of item in ArrayList?

Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.

Undoing a git rebase

If you don't want to do a hard reset...

You can checkout the commit from the reflog, and then save it as a new branch:

git reflog

Find the commit just before you started rebasing. You may need to scroll further down to find it (press Enter or PageDown). Take note of the HEAD number and replace 57:

git checkout HEAD@{57}

Review the branch/commits, and if it's correct then create a new branch using this HEAD:

git checkout -b new_branch_name

What is the exact meaning of Git Bash?

At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.

What is Git Bash?

Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.

source : https://www.atlassian.com/git/tutorials/git-bash

VMWare Player vs VMWare Workstation

One main reason we went with Workstation over Player at my job is because we need to run VMs that use a physical disk as their hard drive instead of a virtual disk. Workstation supports using physical disks while Player does not.

HTML5 Video not working in IE 11

I used MP4Box to decode the atom tags in the mp4. (MP4Box -v myfile.mp4) I also used ffmpeg to convert the mp41 to mp42. After comparing the differences and experimenting, I found that IE11 did not like that my original mp4 had two avC1 atoms inside stsd.

After deleting the duplicate avC1 in my original mp41 mp4, IE11 would play the mp4.

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

If you already have it as a DateTime, use:

string x = dt.ToString("yyyy-MM-dd");

See the MSDN documentation for more details. You can specify CultureInfo.InvariantCulture to enforce the use of Western digits etc. This is more important if you're using MMM for the month name and similar things, but it wouldn't be a bad idea to make it explicit:

string x = dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

If you have a string to start with, you'll need to parse it and then reformat... of course, that means you need to know the format of the original string.

Search a whole table in mySQL for a string

Identify all the fields that could be related to your search and then use a query like:

SELECT * FROM clients
WHERE field1 LIKE '%Mary%'
   OR field2 LIKE '%Mary%'
   OR field3 LIKE '%Mary%'
   OR field4 LIKE '%Mary%'
   ....
   (do that for each field you want to check)

Using LIKE '%Mary%' instead of = 'Mary' will look for the fields that contains someCaracters + 'Mary' + someCaracters.

How do I make a redirect in PHP?

Like others here said, sending the location header with:

header( "Location: http://www.mywebsite.com/otherpage.php" );

but you need to do it before you've sent any other output to the browser.

Also, if you're going to use this to block un-authenticated users from certain pages, like you mentioned, keep in mind that some user agents will ignore this and continue on the current page anyway, so you'll need to die() after you send it.

VBA Excel - Insert row below with same format including borders and frames

The easiest option is to make use of the Excel copy/paste.

Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub

Write to rails console

I think you should use the Rails debug options:

logger.debug "Person attributes hash: #{@person.attributes.inspect}"
logger.info "Processing the request..."
logger.fatal "Terminating application, raised unrecoverable error!!!"

https://guides.rubyonrails.org/debugging_rails_applications.html

SQL WITH clause example

The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. The name assigned to the sub-query is treated as though it was an inline view or table. The SQL WITH clause is basically a drop-in replacement to the normal sub-query.

Syntax For The SQL WITH Clause

The following is the syntax of the SQL WITH clause when using a single sub-query alias.

WITH <alias_name> AS (sql_subquery_statement)
SELECT column_list FROM <alias_name>[,table_name]
[WHERE <join_condition>]

When using multiple sub-query aliases, the syntax is as follows.

WITH <alias_name_A> AS (sql_subquery_statement),
<alias_name_B> AS(sql_subquery_statement_from_alias_name_A
or sql_subquery_statement )
SELECT <column_list>
FROM <alias_name_A>, <alias_name_B> [,table_names]
[WHERE <join_condition>]

In the syntax documentation above, the occurrences of alias_name is a meaningful name you would give to the sub-query after the AS clause. Each sub-query should be separated with a comma Example for WITH statement. The rest of the queries follow the standard formats for simple and complex SQL SELECT queries.

For more information: http://www.brighthub.com/internet/web-development/articles/91893.aspx

How to style components using makeStyles and still have lifecycle methods in Material UI?

Another one solution can be used for class components - just override default MUI Theme properties with MuiThemeProvider. This will give more flexibility in comparison with other methods - you can use more than one MuiThemeProvider inside your parent component.

simple steps:

  1. import MuiThemeProvider to your class component
  2. import createMuiTheme to your class component
  3. create new theme
  4. wrap target MUI component you want to style with MuiThemeProvider and your custom theme

please, check this doc for more details: https://material-ui.com/customization/theming/

_x000D_
_x000D_
import React from 'react';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';

import { MuiThemeProvider } from '@material-ui/core/styles';
import { createMuiTheme } from '@material-ui/core/styles';

const InputTheme = createMuiTheme({
    overrides: {
        root: {
            background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
            border: 0,
            borderRadius: 3,
            boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
            color: 'white',
            height: 48,
            padding: '0 30px',
        },
    }
});

class HigherOrderComponent extends React.Component {

    render(){
        const { classes } = this.props;
        return (
            <MuiThemeProvider theme={InputTheme}>
                <Button className={classes.root}>Higher-order component</Button>
            </MuiThemeProvider>
        );
    }
}

HigherOrderComponent.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default HigherOrderComponent;
_x000D_
_x000D_
_x000D_

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

So far, the accepted answer has worked best for me. However, my concern has always been that there is a likely scenario where I might refactor the notebooks directory into subdirectories, requiring to change the module_path in every notebook. I decided to add a python file within each notebook directory to import the required modules.

Thus, having the following project structure:

project
|__notebooks
   |__explore
      |__ notebook1.ipynb
      |__ notebook2.ipynb
      |__ project_path.py
   |__ explain
       |__notebook1.ipynb
       |__project_path.py
|__lib
   |__ __init__.py
   |__ module.py

I added the file project_path.py in each notebook subdirectory (notebooks/explore and notebooks/explain). This file contains the code for relative imports (from @metakermit):

import sys
import os

module_path = os.path.abspath(os.path.join(os.pardir, os.pardir))
if module_path not in sys.path:
    sys.path.append(module_path)

This way, I just need to do relative imports within the project_path.py file, and not in the notebooks. The notebooks files would then just need to import project_path before importing lib. For example in 0.0-notebook.ipynb:

import project_path
import lib

The caveat here is that reversing the imports would not work. THIS DOES NOT WORK:

import lib
import project_path

Thus care must be taken during imports.

SSL certificate is not trusted - on mobile only

The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.

If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)

You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.

PHP cURL custom headers

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12'
));

http://www.php.net/manual/en/function.curl-setopt.php

git replace local version with remote version

My understanding is that, for example, you wrongly saved a file you had updated for testing purposes only. Then, when you run "git status" the file appears as "Modified" and you say some bad words. You just want the old version back and continue to work normally.

In that scenario you can just run the following command:

git checkout -- path/filename

Copy file(s) from one project to another using post build event...VS2010

If you want to take into consideration the platform (x64, x86 etc) and the configuration (Debug or Release) it would be something like this:

xcopy "$(SolutionDir)\$(Platform)\$(Configuration)\$(TargetName).dll" "$(SolutionDir)TestDirectory\bin\$(Platform)\$(Configuration)\" /F /Y 

jQuery override default validation error message display (Css) Popup/Tooltip like

You can use the errorPlacement option to override the error message display with little css. Because css on its own will not be enough to produce the effect you need.

$(document).ready(function(){
    $("#myForm").validate({
        rules: {
            "elem.1": {
                required: true,
                digits: true
            },
            "elem.2": {
                required: true
            }
        },
        errorElement: "div",
        wrapper: "div",  // a wrapper around the error message
        errorPlacement: function(error, element) {
            offset = element.offset();
            error.insertBefore(element)
            error.addClass('message');  // add a class to the wrapper
            error.css('position', 'absolute');
            error.css('left', offset.left + element.outerWidth());
            error.css('top', offset.top);
        }

    });
});

You can play with the left and top css attributes to show the error message on top, left, right or bottom of the element. For example to show the error on the top:

    errorPlacement: function(error, element) {
        element.before(error);
        offset = element.offset();
        error.css('left', offset.left);
        error.css('top', offset.top - element.outerHeight());
    }

And so on. You can refer to jQuery documentation about css for more options.

Here is the css I used. The result looks exactly like the one you want. With as little CSS as possible:

div.message{
    background: transparent url(msg_arrow.gif) no-repeat scroll left center;
    padding-left: 7px;
}

div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid none;
    border-width: 2px;
    padding: 5px;
}

And here is the background image you need:

alt text
(source: scriptiny.com)

If you want the error message to be displayed after a group of options or fields. Then group all those elements inside one container a 'div' or a 'fieldset'. Add a special class to all of them 'group' for example. And add the following to the begining of the errorPlacement function:

errorPlacement: function(error, element) {
    if (element.hasClass('group')){
        element = element.parent();
    }
    ...// continue as previously explained

If you only want to handle specific cases you can use attr instead:

if (element.attr('type') == 'radio'){
    element = element.parent();
}

That should be enough for the error message to be displayed next to the parent element.

You may need to change the width of the parent element to be less than 100%.


I've tried your code and it is working perfectly fine for me. Here is a preview: alt text

I just made a very small adjustment to the message padding to make it fit in the line:

div.error {
    padding: 2px 5px;
}

You can change those numbers to increase/decrease the padding on top/bottom or left/right. You can also add a height and width to the error message. If you are still having issues, try to replace the span with a div

<div class="group">
<input type="radio" class="checkbox" value="P" id="radio_P" name="radio_group_name"/>
<label for="radio_P">P</label>
<input type="radio" class="checkbox" value="S" id="radio_S" name="radio_group_name"/>
<label for="radio_S">S</label>
</div>

And then give the container a width (this is very important)

div.group {
    width: 50px; /* or any other value */
}

About the blank page. As I said I tried your code and it is working for me. It might be something else in your code that is causing the issue.

Stop Visual Studio from mixing line endings in files

With VS2010+ there is a plugin solution: Line Endings Unifier.

With the plugin installed you can right click files and folders in the solution explorer and invoke the menu item Unify Line Endings in this file

Configuration for this is available via

Tools -> Options -> Line Endings Unifier.

The default file extension list that is included is pretty narrow:

 .cpp; .c; .h; .hpp; .cs; .js; .vb; .txt;

Might want to use something like:

 .cpp; .c; .h; .hpp; .cs; .js; .vb; .txt; .scss; .coffee; .ts; .jsx; .markdown; .config

How can I create a copy of an Oracle table without copying the data?

create table xyz_new as select * from xyz where rownum = -1;

To avoid iterate again and again and insert nothing based on the condition where 1=2

How do I calculate a trendline for a graph?

If anyone needs the JS code for calculating the trendline of many points on a graph, here's what worked for us in the end:

_x000D_
_x000D_
/**@typedef {{_x000D_
 * x: Number;_x000D_
 * y:Number;_x000D_
 * }} Point_x000D_
 * @param {Point[]} data_x000D_
 * @returns {Function} */_x000D_
function _getTrendlineEq(data) {_x000D_
    const xySum = data.reduce((acc, item) => {_x000D_
        const xy = item.x * item.y_x000D_
        acc += xy_x000D_
        return acc_x000D_
    }, 0)_x000D_
    const xSum = data.reduce((acc, item) => {_x000D_
        acc += item.x_x000D_
        return acc_x000D_
    }, 0)_x000D_
    const ySum = data.reduce((acc, item) => {_x000D_
        acc += item.y_x000D_
        return acc_x000D_
    }, 0)_x000D_
    const aTop = (data.length * xySum) - (xSum * ySum)_x000D_
    const xSquaredSum = data.reduce((acc, item) => {_x000D_
        const xSquared = item.x * item.x_x000D_
        acc += xSquared_x000D_
        return acc_x000D_
    }, 0)_x000D_
    const aBottom = (data.length * xSquaredSum) - (xSum * xSum)_x000D_
    const a = aTop / aBottom_x000D_
    const bTop = ySum - (a * xSum)_x000D_
    const b = bTop / data.length_x000D_
    return function trendline(x) {_x000D_
        return a * x + b_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

It takes an array of (x,y) points and returns the function of a y given a certain x Have fun :)

Does java.util.List.isEmpty() check if the list itself is null?

You can use your own isEmpty (for multiple collection) method too. Add this your Util class.

public static boolean isEmpty(Collection... collections) {
    for (Collection collection : collections) {
        if (null == collection || collection.isEmpty())
            return true;
    }
    return false;
}

sql insert into table with select case values

Also you can use COALESCE instead of CASE expression. Because result of concatenating anything to NULL, even itself, is always NULL

INSERT TblStuff(FullName,Address,City,Zip)
SELECT COALESCE(Fname + ' ' + Middle + ' ' + Lname, Fname + LName) AS FullName,
       COALESCE(Address1 + ', ' + Address2, Address1) AS Address, City, Zip
FROM tblImport

Demo on SQLFiddle

JavaScript "cannot read property "bar" of undefined

If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:

if (thing && thing.foo)
   alert(thing.foo.bar);

I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:

function someFunc(parameterName) {
   if (parameterName && parameterName.foo)
       alert(parameterName.foo.bar);
}

How to call a JavaScript function from PHP?

I always just use echo "<script> function(); </script>"; or something similar. you're not technically calling the function in PHP, but this as close as your going to get.

Undo a merge by pull request?

I use this place all the time, thanks.

I was searching for how to undo a pull request and got here.

I was about to just git reset --hard to "a long time ago" and do a fast forward back to where I was before doing the pull request.

Besides looking here, I also asked my co-worker what he would do, and he had a typically good answer: using the example output in the first answer above:

git reset --hard 9271e6e

As with most things in Git, if you're doing it some way that's not easy, you're probably doing it wrong.

How can I add a line to a file in a shell script?

Use perl -i, with a command that replaces the beginning of line 1 with what you want to insert (the .bk will have the effect that your original file is backed up):

perl -i.bk -pe 's/^/column1, column2, column3\n/ if($.==1)' testfile.csv  

How to set the locale inside a Debian/Ubuntu Docker container?

I actually happened to have suffered from the same problem, but none of the provided answers are 100% working with debian:latest, even if they provide good hints.

The biggest difference is that you should make sure both locales and locales-all are installed, the latter already containing en_US.UTF-8, so you don't have to generate it with local-gen or dpkg-reconfigure.

Here's what I've done in my Dockerfile to make it work:

FROM debian:latest
RUN apt-get update
RUN apt-get install -y locales locales-all
ENV LC_ALL en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US.UTF-8

How to change the Content of a <textarea> with JavaScript

Put the textarea to a form, naming them, and just use the DOM objects easily, like this:

<body onload="form1.box.value = 'Welcome!'">
  <form name="form1">
    <textarea name="box"></textarea>
  </form>
</body>

react-router (v4) how to go back?

Maybe this can help someone.

I was using history.replace() to redirect, so when i tried to use history.goBack(), i was send to the previous page before the page i was working with. So i changed the method history.replace() to history.push() so the history could be saved and i would be able to go back.

Disable ONLY_FULL_GROUP_BY

This is a permanent solution for MySql 5.7+ on Ubuntu 14+:

$ sudo bash -c "echo -e \"\nsql_mode=IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\"  >> /etc/mysql/mysql.conf.d/mysqld.cnf"
$ sudo service mysql restart
# Check if login attempt throws any errors
$ mysql -u[user] -p # replace [user] with your own user name

If you are able to login without errors - you should be all set now.

Force re-download of release dependency using Maven

You cannot make Maven re-download dependencies, but what you can do instead is to purge dependencies that were incorrectly downloaded using mvn dependency:purge-local-repository

See: http://maven.apache.org/plugins/maven-dependency-plugin/purge-local-repository-mojo.html