Programs & Examples On #Progressive

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

Download TS files from video stream

  • Get one Link from Network tab of developer tools
  • Remove index and ts extension from link

With following script you can save movie to Videos folder

Example usage:

download-video.sh https://url.com/video.mp4 video-name

download-video.sh

#!/bin/bash
LINK=$1
NAME=$2

START=0
END=2000

help()
{
    echo "download-video.sh <url> <output-name>"
    echo "<url>: x.mp4 (without .ts)"
    echo "<output-name>: x (without .mp4)"
} 

create_folders()
{
    # create folder for streaming media
    cd ~/Videos
    mkdir download-videos
    cd download-videos
}

print_variables()
{
    echo "Execute Download with following parameters"
    echo "Link $LINK"
    echo "Name $NAME"
}

check_video()
{
    i=$START
    while [[ $i -le $END ]]
    do
        URL=$LINK'-'$i.ts
        STATUS_CODE=$(curl -o /dev/null --silent --head --write-out '%{http_code}\n' $URL)
        if [ "$STATUS_CODE" == "200" ]; then
            break
        fi
        ((i = i + 1))
    done

    if [ "$STATUS_CODE" == "200" ]; then
        START=$i
        echo "START is $START"
    else 
        echo "File not found"
    fi
} 


download_video()
{
    i=$START
    e=$END
    while [[ $i -le $END ]]
    do
        URL=$LINK'-'$i.ts
        STATUS_CODE=$(curl -o /dev/null --silent --head --write-out '%{http_code}\n' $URL)
        if [ "$STATUS_CODE" != "200" ]; then
            break
        fi
        wget $URL
        e=$i
        ((i = i + 1))
    done

    END=$e
}

concat_videos()
{
    DIR="${LINK##*/}"

    i=$START
    echo "i is $i"
    while [[ $i -le $END ]]
    do
        FILE=$DIR'-'$i.ts
        echo $FILE | tr " " "\n" >> tslist
        ((i = i + 1))
    done
    while read line; 
    do 
        echo "gugu"$line
        cat $line >> $NAME.mp4; 
    done < tslist

    rm *.ts tslist
}

if [ "$1" == "" ]; then
    echo "No video url provided"
    help
else
    LINK=$1
    if [ "$2" == "" ]; then
        echo "No video output-name provided"
        help
    else
        NAME=$2
        create_folders
        print_variables
        check_video
        download_video
        concat_videos
    fi
fi

How can I delay a :hover effect in CSS?

div {
     background: #dbdbdb;
    -webkit-transition: .5s all;   
    -webkit-transition-delay: 5s; 
    -moz-transition: .5s all;   
    -moz-transition-delay: 5s; 
    -ms-transition: .5s all;   
    -ms-transition-delay: 5s; 
    -o-transition: .5s all;   
    -o-transition-delay: 5s; 
    transition: .5s all;   
    transition-delay: 5s; 
}

div:hover {
    background:#5AC900;
    -webkit-transition-delay: 0s;
    -moz-transition-delay: 0s;
    -ms-transition-delay: 0s;
    -o-transition-delay: 0s;
    transition-delay: 0s;
}

This will add a transition delay, which will be applicable to almost every browser..

Get HTML5 localStorage keys

We can also read by the name.

Say we have saved the value with name 'user' like this

localStorage.setItem('user', user_Detail);

Then we can read it by using

localStorage.getItem('user');

I used it and it is working smooth, no need to do the for loop

drag drop files into standard html file input

Awesome work by @BjarkeCK. I made some modifications to his work, to use it as method in jquery:

$.fn.dropZone = function() {
  var buttonId = "clickHere";
  var mouseOverClass = "mouse-over";

  var dropZone = this[0];
  var $dropZone = $(dropZone);
  var ooleft = $dropZone.offset().left;
  var ooright = $dropZone.outerWidth() + ooleft;
  var ootop = $dropZone.offset().top;
  var oobottom = $dropZone.outerHeight() + ootop;
  var inputFile = $dropZone.find("input[type='file']");
  dropZone.addEventListener("dragleave", function() {
    this.classList.remove(mouseOverClass);
  });
  dropZone.addEventListener("dragover", function(e) {
    console.dir(e);
    e.preventDefault();
    e.stopPropagation();
    this.classList.add(mouseOverClass);
    var x = e.pageX;
    var y = e.pageY;

    if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
      inputFile.offset({
        top: y - 15,
        left: x - 100
      });
    } else {
      inputFile.offset({
        top: -400,
        left: -400
      });
    }

  }, true);
  dropZone.addEventListener("drop", function(e) {
    this.classList.remove(mouseOverClass);
  }, true);
}

$('#drop-zone').dropZone();

Working Fiddle

MVC 3: How to render a view without its layout page when loaded via ajax?

For a Ruby on Rails application, I was able to prevent a layout from loading by specifying render layout: false in the controller action that I wanted to respond with ajax html.

CSS3's border-radius property and border-collapse:collapse don't mix. How can I use border-radius to create a collapsed table with rounded corners?

Table with rounded corners and with bordered cells. Using @Ramon Tayag solution.

The key is to use border-spacing: 0 as he points out.

Solution using SCSS.

$line: 1px solid #979797;
$radius: 5px;

table {
  border: $line;
  border-radius: $radius;
  border-spacing: 0;
  th,
  tr:not(:last-child) td {
    border-bottom: $line;
  }
  th:not(:last-child),
  td:not(:last-child) {
    border-right: $line;
  }
}

How to automatically generate N "distinct" colors?

Like Uri Cohen's answer, but is a generator instead. Will start by using colors far apart. Deterministic.

Sample, left colors first: sample

#!/usr/bin/env python3.5
from typing import Iterable, Tuple
import colorsys
import itertools
from fractions import Fraction
from pprint import pprint

def zenos_dichotomy() -> Iterable[Fraction]:
    """
    http://en.wikipedia.org/wiki/1/2_%2B_1/4_%2B_1/8_%2B_1/16_%2B_%C2%B7_%C2%B7_%C2%B7
    """
    for k in itertools.count():
        yield Fraction(1,2**k)

def fracs() -> Iterable[Fraction]:
    """
    [Fraction(0, 1), Fraction(1, 2), Fraction(1, 4), Fraction(3, 4), Fraction(1, 8), Fraction(3, 8), Fraction(5, 8), Fraction(7, 8), Fraction(1, 16), Fraction(3, 16), ...]
    [0.0, 0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875, 0.0625, 0.1875, ...]
    """
    yield Fraction(0)
    for k in zenos_dichotomy():
        i = k.denominator # [1,2,4,8,16,...]
        for j in range(1,i,2):
            yield Fraction(j,i)

# can be used for the v in hsv to map linear values 0..1 to something that looks equidistant
# bias = lambda x: (math.sqrt(x/3)/Fraction(2,3)+Fraction(1,3))/Fraction(6,5)

HSVTuple = Tuple[Fraction, Fraction, Fraction]
RGBTuple = Tuple[float, float, float]

def hue_to_tones(h: Fraction) -> Iterable[HSVTuple]:
    for s in [Fraction(6,10)]: # optionally use range
        for v in [Fraction(8,10),Fraction(5,10)]: # could use range too
            yield (h, s, v) # use bias for v here if you use range

def hsv_to_rgb(x: HSVTuple) -> RGBTuple:
    return colorsys.hsv_to_rgb(*map(float, x))

flatten = itertools.chain.from_iterable

def hsvs() -> Iterable[HSVTuple]:
    return flatten(map(hue_to_tones, fracs()))

def rgbs() -> Iterable[RGBTuple]:
    return map(hsv_to_rgb, hsvs())

def rgb_to_css(x: RGBTuple) -> str:
    uint8tuple = map(lambda y: int(y*255), x)
    return "rgb({},{},{})".format(*uint8tuple)

def css_colors() -> Iterable[str]:
    return map(rgb_to_css, rgbs())

if __name__ == "__main__":
    # sample 100 colors in css format
    sample_colors = list(itertools.islice(css_colors(), 100))
    pprint(sample_colors)

how to find my angular version in my project?

you can use ng --version for angular version 7

How to get error message when ifstream open fails

You can also throw a std::system_error as shown in the test code below. This method seems to produce more readable output than f.exception(...).

#include <exception> // <-- requires this
#include <fstream>
#include <iostream>

void process(const std::string& fileName) {
    std::ifstream f;
    f.open(fileName);

    // after open, check f and throw std::system_error with the errno
    if (!f)
        throw std::system_error(errno, std::system_category(), "failed to open "+fileName);

    std::clog << "opened " << fileName << std::endl;
}

int main(int argc, char* argv[]) {
    try {
        process(argv[1]);
    } catch (const std::system_error& e) {
        std::clog << e.what() << " (" << e.code() << ")" << std::endl;
    }
    return 0;
}

Example output (Ubuntu w/clang):

$ ./test /root/.profile
failed to open /root/.profile: Permission denied (system:13)
$ ./test missing.txt
failed to open missing.txt: No such file or directory (system:2)
$ ./test ./test
opened ./test
$ ./test $(printf '%0999x')
failed to open 000...000: File name too long (system:36)

git replacing LF with CRLF

Git has three modes of how it treats line endings:

$ git config core.autocrlf
# that command will print "true" or "false" or "input"

You can set the mode to use by adding an additional parameter of true or false to the above command line.

If core.autocrlf is set to true, that means that any time you add a file to the git repo that git thinks is a text file, it will turn all CRLF line endings to just LF before it stores it in the commit. Whenever you git checkout something, all text files automatically will have their LF line endings converted to CRLF endings. This allows development of a project across platforms that use different line-ending styles without commits being very noisy because each editor changes the line ending style as the line ending style is always consistently LF.

The side-effect of this convenient conversion, and this is what the warning you're seeing is about, is that if a text file you authored originally had LF endings instead of CRLF, it will be stored with LF as usual, but when checked out later it will have CRLF endings. For normal text files this is usually just fine. The warning is a "for your information" in this case, but in case git incorrectly assesses a binary file to be a text file, it is an important warning because git would then be corrupting your binary file.

If core.autocrlf is set to false, no line-ending conversion is ever performed, so text files are checked in as-is. This usually works ok, as long as all your developers are either on Linux or all on Windows. But in my experience I still tend to get text files with mixed line endings that end up causing problems.

My personal preference is to leave the setting turned ON, as a Windows developer.

See http://kernel.org/pub/software/scm/git/docs/git-config.html for updated info that includes the "input" value.

How do I add images in laravel view?

If Image folder location is public/assets/img/default.jpg. You can try in view

   <img src="{{ URL::to('/assets/img/default.jpg') }}">

How to check whether Kafka Server is running?

Firstly you need to create AdminClient bean:

 @Bean
 public AdminClient adminClient(){
   Map<String, Object> configs = new HashMap<>();
   configs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,
   StringUtils.arrayToCommaDelimitedString(new Object[]{"your bootstrap server address}));
   return AdminClient.create(configs);
 }

Then, you can use this script:

while (true) {
   Map<String, ConsumerGroupDescription> groupDescriptionMap =
         adminClient.describeConsumerGroups(Collections.singletonList(groupId))
         .all()
         .get(10, TimeUnit.SECONDS);

   ConsumerGroupDescription consumerGroupDescription = groupDescriptionMap.get(groupId);

   log.debug("Kafka consumer group ({}) state: {}",
                groupId,
                consumerGroupDescription.state());

   if (consumerGroupDescription.state().equals(ConsumerGroupState.STABLE)) {
        boolean isReady = true;
        for (MemberDescription member : consumerGroupDescription.members()) {
            if (member.assignment() == null || member.assignment().topicPartitions().isEmpty()) {
            isReady = false;
            }
        }

        if (isReady) {
            break;
           }
        }

        log.debug("Kafka consumer group ({}) is not ready. Waiting...", groupId);
        TimeUnit.SECONDS.sleep(1);
}

This script will check the state of the consumer group every second till the state will be STABLE. Because all consumers assigned to topic partitions, you can conclude that server is running and ready.

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

You can do this:

IEnumerable<object> list = new List<object>(){1, 4, 5}.AsEnumerable();
CallFunction(list);

What does -Xmn jvm option stands for

From GC Performance Tuning training documents of Oracle:

-Xmn[size]: Size of young generation heap space.

Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.

In short, it sets the NewSize and MaxNewSize values of New generation to the same value.

Javascript - validation, numbers only

var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
   elem[i].addEventListener('keypress', function(event){
      var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
      var validIndex = keys.indexOf(event.charCode);
      if(validIndex == -1){
         event.preventDefault();
      }
  });
}

Determining if an Object is of primitive type

Get ahold of BeanUtils from Spring http://static.springsource.org/spring/docs/3.0.x/javadoc-api/

Probably the Apache variation (commons beans) has similar functionality.

Entry point for Java applications: main(), init(), or run()?

The main method is the entry point of a Java application.

Specifically?when the Java Virtual Machine is told to run an application by specifying its class (by using the java application launcher), it will look for the main method with the signature of public static void main(String[]).

From Sun's java command page:

The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.

The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. The method declaration must look like the following:

public static void main(String args[])

For additional resources on how an Java application is executed, please refer to the following sources:

  1. Chapter 12: Execution from the Java Language Specification, Third Edition.
  2. Chapter 5: Linking, Loading, Initializing from the Java Virtual Machine Specifications, Second Edition.
  3. A Closer Look at the "Hello World" Application from the Java Tutorials.

The run method is the entry point for a new Thread or an class implementing the Runnable interface. It is not called by the Java Virutal Machine when it is started up by the java command.

As a Thread or Runnable itself cannot be run directly by the Java Virtual Machine, so it must be invoked by the Thread.start() method. This can be accomplished by instantiating a Thread and calling its start method in the main method of the application:

public class MyRunnable implements Runnable
{
    public void run()
    {
        System.out.println("Hello World!");
    }

    public static void main(String[] args)
    {
        new Thread(new MyRunnable()).start();
    }
}

For more information and an example of how to start a subclass of Thread or a class implementing Runnable, see Defining and Starting a Thread from the Java Tutorials.


The init method is the first method called in an Applet or JApplet.

When an applet is loaded by the Java plugin of a browser or by an applet viewer, it will first call the Applet.init method. Any initializations that are required to use the applet should be executed here. After the init method is complete, the start method is called.

For more information about when the init method of an applet is called, please read about the lifecycle of an applet at The Life Cycle of an Applet from the Java Tutorials.

See also: How to Make Applets from the Java Tutorial.

Reverse / invert a dictionary mapping

I think the best way to do this is to define a class. Here is an implementation of a "symmetric dictionary":

class SymDict:
    def __init__(self):
        self.aToB = {}
        self.bToA = {}

    def assocAB(self, a, b):
        # Stores and returns a tuple (a,b) of overwritten bindings
        currB = None
        if a in self.aToB: currB = self.bToA[a]
        currA = None
        if b in self.bToA: currA = self.aToB[b]

        self.aToB[a] = b
        self.bToA[b] = a
        return (currA, currB)

    def lookupA(self, a):
        if a in self.aToB:
            return self.aToB[a]
        return None

    def lookupB(self, b):
        if b in self.bToA:
            return self.bToA[b]
        return None

Deletion and iteration methods are easy enough to implement if they're needed.

This implementation is way more efficient than inverting an entire dictionary (which seems to be the most popular solution on this page). Not to mention, you can add or remove values from your SymDict as much as you want, and your inverse-dictionary will always stay valid -- this isn't true if you simply reverse the entire dictionary once.

Adobe Acrobat Pro make all pages the same dimension

The above works,(having an original document with mixed pages of 11' and 16' wide). However auto rotate needs to be off otherwise landscape pages are saved with page white top and bottom, so dont work in full screen view.

Solution is to re open the new PDF in acrobat and crop the first image (carefully to avoid white border), then select page range i.e. all, this then applies to all pages. job done !

How to display loading image while actual image is downloading

Use a javascript constructor with a callback that fires when the image has finished loading in the background. Just used it and works great for me cross-browser. Here's the thread with the answer.

Difference between ApiController and Controller in ASP.NET MVC

Which would you rather write and maintain?

ASP.NET MVC

public class TweetsController : Controller {
  // GET: /Tweets/
  [HttpGet]
  public ActionResult Index() {
    return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
  }
}

ASP.NET Web API

public class TweetsController : ApiController {
  // GET: /Api/Tweets/
  public List<Tweet> Get() {
    return Twitter.GetTweets();
  }
}

Android Studio AVD - Emulator: Process finished with exit code 1

This works to me:

click in Sdk manager in SDK Tools and: enter image description here

Unistal and install the Android Emulator: enter image description here

Hope to help!

Angularjs $q.all

In javascript there are no block-level scopes only function-level scopes:

Read this article about javaScript Scoping and Hoisting.

See how I debugged your code:

var deferred = $q.defer();
deferred.count = i;

console.log(deferred.count); // 0,1,2,3,4,5 --< all deferred objects

// some code

.success(function(data){
   console.log(deferred.count); // 5,5,5,5,5,5 --< only the last deferred object
   deferred.resolve(data);
})
  • When you write var deferred= $q.defer(); inside a for loop it's hoisted to the top of the function, it means that javascript declares this variable on the function scope outside of the for loop.
  • With each loop, the last deferred is overriding the previous one, there is no block-level scope to save a reference to that object.
  • When asynchronous callbacks (success / error) are invoked, they reference only the last deferred object and only it gets resolved, so $q.all is never resolved because it still waits for other deferred objects.
  • What you need is to create an anonymous function for each item you iterate.
  • Since functions do have scopes, the reference to the deferred objects are preserved in a closure scope even after functions are executed.
  • As #dfsq commented: There is no need to manually construct a new deferred object since $http itself returns a promise.

Solution with angular.forEach:

Here is a demo plunker: http://plnkr.co/edit/NGMp4ycmaCqVOmgohN53?p=preview

UploadService.uploadQuestion = function(questions){

    var promises = [];

    angular.forEach(questions , function(question) {

        var promise = $http({
            url   : 'upload/question',
            method: 'POST',
            data  : question
        });

        promises.push(promise);

    });

    return $q.all(promises);
}

My favorite way is to use Array#map:

Here is a demo plunker: http://plnkr.co/edit/KYeTWUyxJR4mlU77svw9?p=preview

UploadService.uploadQuestion = function(questions){

    var promises = questions.map(function(question) {

        return $http({
            url   : 'upload/question',
            method: 'POST',
            data  : question
        });

    });

    return $q.all(promises);
}

How to describe "object" arguments in jsdoc?

From the @param wiki page:


Parameters With Properties

If a parameter is expected to have a particular property, you can document that immediately after the @param tag for that parameter, like so:

 /**
  * @param userInfo Information about the user.
  * @param userInfo.name The name of the user.
  * @param userInfo.email The email of the user.
  */
 function logIn(userInfo) {
        doLogIn(userInfo.name, userInfo.email);
 }

There used to be a @config tag which immediately followed the corresponding @param, but it appears to have been deprecated (example here).

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

First you should learn about loops, in this case most suitable is for loop. For instance let's initialize whole table with increasing values starting with 0:

final int SIZE = 10;
int[] array = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
    array[i] = i;
}

Now you can modify it to initialize your table with values as per your assignment. But what happen if you replace condition i < SIZE with i < 11? Well, you will get IndexOutOfBoundException, as you try to access (at some point) an object under index 10, but the highest index in 10-element array is 9. So you are trying, in other words, to find friend's home with number 11, but there are only 10 houses in the street.

In case of the code you presented, well, there must be more of it, as you can not get this error (exception) from that code.

What is the difference between .yaml and .yml extension?

File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml, .yaml or indeed anything else.

The (rather sparse) YAML FAQ recommends that you use .yaml in preference to .yml, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml instead.

So, what really matters is what is inside the file, rather than what its extension is.

PHP absolute path to root

This is my way to find the rootstart. Create at ROOT start a file with name mainpath.php

<?php 
## DEFINE ROOTPATH
$check_data_exist = ""; 

$i_surf = 0;

// looking for mainpath.php at the aktiv folder or higher folder

while (!file_exists($check_data_exist."mainpath.php")) {
  $check_data_exist .= "../"; 
  $i_surf++;
  // max 7 folder deep
  if ($i_surf == 7) { 
   return false;
  }
}

define("MAINPATH", ($check_data_exist ? $check_data_exist : "")); 
?>

For me is that the best and easiest way to find them. ^^

How to use jQuery to call an ASP.NET web service?

Here is an example to call your webservice using jQuery.get:

$.get("http://domain.com/webservice.asmx", { name: "John", time: "2pm" },
  function(data){
    alert("Data Loaded: " + data);
  });

In the example above, we call "webservice.asmx", passing two parameters: name and time. Then, getting the service output in the call back function.

How to Parse a JSON Object In Android

JSONArray jsonArray = new JSONArray(yourJsonString);

for (int i = 0; i < jsonArray.length(); i++) {
     JSONObject obj1 = jsonArray.getJSONObject(i);
     JSONArray results = patient.getJSONArray("results");
     String indexForPhone =  patientProfile.getJSONObject(0).getString("indexForPhone"));
}

Change to JSONArray, then convert to JSONObject.

Android WebView progress bar

This is how I did it with Kotlin to show progress with percentage.

My fragment layout.

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

<WebView
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

<ProgressBar
    android:layout_marginLeft="32dp"
    android:layout_marginRight="32dp"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:id="@+id/progressBar"/>
</FrameLayout>

My kotlin fragment in onViewCreated

    progressBar.max = 100;
    webView.webChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            progressBar.progress = newProgress;
        }
    }

    webView!!.webViewClient = object : WebViewClient() {

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            progressBar.visibility = View.VISIBLE
            progressBar.progress = 0;
            super.onPageStarted(view, url, favicon)
        }

        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            view?.loadUrl(url)
            return true
        }

        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                view?.loadUrl(request?.url.toString())
            }
            return true
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            progressBar.visibility = View.GONE
        }
    }

    webView.loadUrl(url)

Gradle error: could not execute build using gradle distribution

I updated to 0.3.0 and had the same issue. I had to end up changing my Gradle version to classpath 'com.android.tools.build:gradle:0.6.1+' and in build.gradle and also changing the distributionUrl to distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-bin.zip in the gradle-wrapper.properties file. Then I did a local import of the Gradle file. That worked for me.

What is the .idea folder?

When you use the IntelliJ IDE, all the project-specific settings for the project are stored under the .idea folder.

Project settings are stored with each specific project as a set of xml files under the .idea folder. If you specify the default project settings, these settings will be automatically used for each newly created project.

Check this documentation for the IDE settings and here is their recommendation on Source Control and an example .gitignore file.

Note: If you are using git or some version control system, you might want to set this folder "ignore". Example - for git, add this directory to .gitignore. This way, the application is not IDE-specific.

How to enable production mode?

When ng build command is used it overwrite environment.ts file

By default when ng build command is used it set dev environment

In order to use production environment, use following command ng build --env=prod

This will enable production mode and automatically update environment.ts file

Query to display all tablespaces in a database and datafiles

If you want to get a list of all tablespaces used in the current database instance, you can use the DBA_TABLESPACES view as shown in the following SQL script example:

SQL> connect SYSTEM/fyicenter
Connected.

SQL> SELECT TABLESPACE_NAME, STATUS, CONTENTS
  2  FROM USER_TABLESPACES;
TABLESPACE_NAME                STATUS    CONTENTS
------------------------------ --------- ---------
SYSTEM                         ONLINE    PERMANENT
UNDO                           ONLINE    UNDO
SYSAUX                         ONLINE    PERMANENT
TEMP                           ONLINE    TEMPORARY
USERS                          ONLINE    PERMANENT

http://dba.fyicenter.com/faq/oracle/Show-All-Tablespaces-in-Current-Database.html

Standardize data columns in R

You can easily normalize the data also using data.Normalization function in clusterSim package. It provides different method of data normalization.

    data.Normalization (x,type="n0",normalization="column")

Arguments

x
vector, matrix or dataset type
type of normalization: n0 - without normalization

n1 - standardization ((x-mean)/sd)

n2 - positional standardization ((x-median)/mad)

n3 - unitization ((x-mean)/range)

n3a - positional unitization ((x-median)/range)

n4 - unitization with zero minimum ((x-min)/range)

n5 - normalization in range <-1,1> ((x-mean)/max(abs(x-mean)))

n5a - positional normalization in range <-1,1> ((x-median)/max(abs(x-median)))

n6 - quotient transformation (x/sd)

n6a - positional quotient transformation (x/mad)

n7 - quotient transformation (x/range)

n8 - quotient transformation (x/max)

n9 - quotient transformation (x/mean)

n9a - positional quotient transformation (x/median)

n10 - quotient transformation (x/sum)

n11 - quotient transformation (x/sqrt(SSQ))

n12 - normalization ((x-mean)/sqrt(sum((x-mean)^2)))

n12a - positional normalization ((x-median)/sqrt(sum((x-median)^2)))

n13 - normalization with zero being the central point ((x-midrange)/(range/2))

normalization
"column" - normalization by variable, "row" - normalization by object

In Node.js, how do I turn a string to a json?

You need to use this function.

JSON.parse(yourJsonString);

And it will return the object / array that was contained within the string.

Initialize a string variable in Python: "" or None?

None is used to indicate "not set", whereas any other value is used to indicate a "default" value.

Hence, if your class copes with empty strings and you like it as a default value, use "". If your class needs to check if the variable was set at all, use None.

Notice that it doesn't matter if your variable is a string initially. You can change it to any other type/value at any other moment.

Php, wait 5 seconds before executing an action

before starting your actions, use

 sleep(5);

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

Typescript interface default values

Can I tell the interface to default the properties I don't supply to null? What would let me do this

No. You cannot provide default values for interfaces or type aliases as they are compile time only and default values need runtime support

Alternative

But values that are not specified default to undefined in JavaScript runtimes. So you can mark them as optional:

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

And now when you create it you only need to provide a:

let x: IX = {
    a: 'abc'
};

You can provide the values as needed:

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

Are Git forks actually Git clones?

Forking is done when you decide to contribute to some project. You would make a copy of the entire project along with its history logs. This copy is made entirely in your repository and once you make these changes, you issue a pull request. Now its up-to the owner of the source to accept your pull request and incorporate the changes into the original code.

Git clone is an actual command that allows users to get a copy of the source. git clone [URL] This should create a copy of [URL] in your own local repository.

Add Variables to Tuple

You can start with a blank tuple with something like t = (). You can add with +, but you have to add another tuple. If you want to add a single element, make it a singleton: t = t + (element,). You can add a tuple of multiple elements with or without that trailing comma.

>>> t = ()
>>> t = t + (1,)
>>> t
(1,)
>>> t = t + (2,)
>>> t
(1, 2)
>>> t = t + (3, 4, 5)
>>> t
(1, 2, 3, 4, 5)
>>> t = t + (6, 7, 8,)
>>> t
(1, 2, 3, 4, 5, 6, 7, 8)

How do you add CSS with Javascript?

This is my solution to add a css rule at the end of the last style sheet list:

var css = new function()
{
    function addStyleSheet()
    {
        let head = document.head;
        let style = document.createElement("style");

        head.appendChild(style);
    }

    this.insert = function(rule)
    {
        if(document.styleSheets.length == 0) { addStyleSheet(); }

        let sheet = document.styleSheets[document.styleSheets.length - 1];
        let rules = sheet.rules;

        sheet.insertRule(rule, rules.length);
    }
}

css.insert("body { background-color: red }");

Get Category name from Post ID

     <?php  
     // in woocommerce.php
     $cat = get_queried_object();
     $cat->term_id;
     $cat->name;
     ?>

    <?php
    // get product cat image
        if ( is_product_category() ){
            $cat = get_queried_object();
            $thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
            $image = wp_get_attachment_url( $thumbnail_id );
            if ( $image ) {
                echo '<img src="' . $image . '" alt="" />';
            }       
}
?>

How to fix Ora-01427 single-row subquery returns more than one row in select?

Use the following query:

SELECT E.I_EmpID AS EMPID,
       E.I_EMPCODE AS EMPCODE,
       E.I_EmpName AS EMPNAME,
       REPLACE(TO_CHAR(A.I_REQDATE, 'DD-Mon-YYYY'), ' ', '') AS FROMDATE,
       REPLACE(TO_CHAR(A.I_ENDDATE, 'DD-Mon-YYYY'), ' ', '') AS TODATE,
       TO_CHAR(NOD) AS NOD,
       DECODE(A.I_DURATION,
              'FD',
              'FullDay',
              'FN',
              'ForeNoon',
              'AN',
              'AfterNoon') AS DURATION,
       L.I_LeaveType AS LEAVETYPE,
       REPLACE(TO_CHAR((SELECT max(C.I_WORKDATE)
                         FROM T_COMPENSATION C
                        WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
                          AND C.I_EMPID = A.I_EMPID),
                       'DD-Mon-YYYY'),
               ' ',
               '') AS WORKDATE,
       A.I_REASON AS REASON,
       AP.I_REJECTREASON AS REJECTREASON
  FROM T_LEAVEAPPLY A
 INNER JOIN T_EMPLOYEE_MS E
    ON A.I_EMPID = E.I_EmpID
   AND UPPER(E.I_IsActive) = 'YES'
   AND A.I_STATUS = '1'
 INNER JOIN T_LeaveType_MS L
    ON A.I_LEAVETYPEID = L.I_LEAVETYPEID
  LEFT OUTER JOIN T_APPROVAL AP
    ON A.I_REQDATE = AP.I_REQDATE
   AND A.I_EMPID = AP.I_EMPID
   AND AP.I_APPROVALSTATUS = '1'
 WHERE E.I_EMPID <> '22'
 ORDER BY A.I_REQDATE DESC

The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?

How to push to History in React Router v4?

so the way I do it is: - instead of redirecting using history.push, I just use Redirect component from react-router-dom When using this component you can just pass push=true, and it will take care of the rest

import * as React from 'react';
import { Redirect } from 'react-router-dom';
class Example extends React.Component {
  componentDidMount() {
    this.setState({
      redirectTo: '/test/path'
    });
  }

  render() {
    const { redirectTo } = this.state;

    return <Redirect to={{pathname: redirectTo}} push={true}/>
  }
}

Should a RESTful 'PUT' operation return something

I used RESTful API in my services, and here is my opinion: First we must get to a common view: PUT is used to update an resource not create or get.

I defined resources with: Stateless resource and Stateful resource:

  • Stateless resources For these resources, just return the HttpCode with empty body, it's enough.

  • Stateful resources For example: the resource's version. For this kind of resources, you must provide the version when you want to change it, so return the full resource or return the version to the client, so the client need't to send a get request after the update action.

But, for a service or system, keep it simple, clearly, easy to use and maintain is the most important thing.

What do these three dots in React do?

Those are called spreads. Just as the name implies. It means it's putting whatever the value of it in those array or objects.

Such as :

let a = [1, 2, 3];
let b = [...a, 4, 5, 6];
console.log(b);
> [1, 2, 3, 4, 5, 6]

What is the difference between React Native and React?

I know there are already many answers to it but after reading all these I believe there is still room for explanation.

React

React = Vaila JS + ES6 + HTML + CSS = JSX = Web Apps(Front end)

So let's talk about react first because react-native also based on react and the same concept of JS is been used there.

React is a JS library which is used to make beautiful, flexible, performant single page web applications, So now a question will appear in your mind what is single page web app.

Single-Page Application

A single-page application is an app that works inside a browser and does not require page reloading during use. You are using this type of applications every day. These are, for instance: Gmail, Google Maps, Facebook, or GitHub. SPAs are all about serving an outstanding UX by trying to imitate a “natural” environment in the browser — no page reloads, no extra wait time. It is just one web page that you visit which then loads all other content using JavaScript — which they heavily depend on. SPA requests the markup and data independently and renders pages straight in the browser. We can do this thanks to advanced JavaScript frameworks like AngularJS, Ember.js, Meteor.js, Knockout.js, React.js, Vue.js. Single-page sites help keep the user in one, comfortable web space where content is presented to the user in a simple, easy, and workable fashion.

How it works

Now you know what is SPA, So as you know it's a web app so it will use HTML elements for running into the browser and also used JS for handling all the functionality related to these elements. It used Virtual Dom to render new changes in the components.

React-Native

Now you have a bit of an idea about react so let's talk about react-native

React-Native = React (Vaila JS + ES6 + Bridge between JS and Native code) + Native(IOS, Android) = Mobile Apps(Android, IOS, also supported web but have some limitations)

React-Native used to make beautiful cross-platform mobile apps(Android, IOS) using React.

How it works

In React-Native there are two threads.

  1. JS Thread

  2. Native Thread

All of the react code executed inside JS thread and the final value passes to the native thread which draws layout on the screen with the final value.

JS thread performs all of the calculations and passes data to native, How?

React uses an Async Bridge to pass data to Native thread in JSON format is called react-native

So we use Native components for making a presentational view in react-native and use that bridge to communicate between these two different worlds.

JS thread is fast enough to execute javascript and the native thread is also fast enough to execute native code but as react used async bridge to communicate between these two worlds, overloading this bridge causes performance issues.

Let's talk about the common and differences between these two frameworks.

|---------------------|------------------|---------------------|
|      Feature        |     React        |  React-Native       |
|---------------------|------------------|---------------------|
|    Platform         |        Web       |  Android, IOS, JS   |
|---------------------|------------------|---------------------|
|   Open Source       |        Yes       |        Yes          |
|---------------------|------------------|---------------------|
| Presentational View |   HTML + CSS     | Native Components   |
|---------------------|------------------|---------------------|
|  Arichtecure        |  Virtual Dom     | Virtual Dom + Bridge|
|---------------------|------------------|---------------------|
|   Animations        | CSS Animations   | Native Animations   | 
|---------------------|------------------|---------------------|
|     Styling         |     CSS          | JS Stylesheets      |
|---------------------|------------------|---------------------|
|  Developed By       |  Facebook        |      Facebook       |
|---------------------|------------------|---------------------|

What's the C++ version of Java's ArrayList

A couple of additional points re use of vector here.

Unlike ArrayList and Array in Java, you don't need to do anything special to treat a vector as an array - the underlying storage in C++ is guaranteed to be contiguous and efficiently indexable.

Unlike ArrayList, a vector can efficiently hold primitive types without encapsulation as a full-fledged object.

When removing items from a vector, be aware that the items above the removed item have to be moved down to preserve contiguous storage. This can get expensive for large containers.

Make sure if you store complex objects in the vector that their copy constructor and assignment operators are efficient. Under the covers, C++ STL uses these during container housekeeping.

Advice about reserve()ing storage upfront (ie. at vector construction or initialilzation time) to minimize memory reallocation on later extension carries over from Java to C++.

Node.JS: Getting error : [nodemon] Internal watch failed: watch ENOSPC

Try reopening VS code or Atom with more specific directory where your app.js is present. I had a lot of folders opened and this problem occured. But once I opened my specific folder and tried once again, it worked.

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

For those who want to use simpleUML in Android Studio and having issues in running SimpleUML.

First download simpleUML jar from here https://plugins.jetbrains.com/plugin/4946-simpleumlce

Now follow the below steps.

Step 1:

Click on File and go to Settings (File ? Settings)

Step 2

Select Plugins from Left Panel and click Install plugin from disk


1]

Step 3:

Locate the SimpleUML jar file and select it.

2]

Step 4:

Now Restart Android Studio (File ? Invalidate Caches/Restart ? Just Restart)

Step 5:

After you restart Right Click the Package name and Select New Diagram or Add to simpleUML Diagram ? New Diagram.

3

Step 6:

Set a file name and create UML file. I created with name NewDiagram

enter image description here Step 7:

Now Right Click the Package name and Select the file you created. In my case it was NewDiagram

enter image description here

Step 8:

All files are stacked on top of one another. You can just drag and drop them and set a hierarchy.

enter image description here

Like this below, you can drag these classes

enter image description here

Proper way to renew distribution certificate for iOS

Your live apps will not be taken down. Nothing will happen to anything that is live in the app store.

Once they formally expire, the only thing that will be impacted is your ability to sign code (and thus make new builds and provide updates).

Regarding your distribution certificate, once it expires, it simply disappears from the ‘Certificates, Identifier & Profiles’ section of Member Center. If you want to renew it before it expires, revoke the current certificate and you will get a button to request a new one.

Regarding the provisioning profile, don't worry about it before expiration, just keep using it. It's easy enough to just renew it once it expires.

The peace of mind is that nothing will happen to your live app in the store.

ValueError: setting an array element with a sequence

When the shape is not regular or the elements have different data types, the dtype argument passed to np.array only can be object.

import numpy as np

# arr1 = np.array([[10, 20.], [30], [40]], dtype=np.float32)  # error
arr2 = np.array([[10, 20.], [30], [40]])  # OK, and the dtype is object
arr3 = np.array([[10, 20.], 'hello'])     # OK, and the dtype is also object

``

How can I read the client's machine/computer name from the browser?

There is no way to do so, as JavaScript does not have an access to computer name, file system and other local info. Security is the main purpose.

Remove blank values from array using C#

If you are using .NET 3.5+ you could use LINQ (Language INtegrated Query).

test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();

Add text at the end of each line

You could try using something like:

sed -n 's/$/:80/' ips.txt > new-ips.txt

Provided that your file format is just as you have described in your question.

The s/// substitution command matches (finds) the end of each line in your file (using the $ character) and then appends (replaces) the :80 to the end of each line. The ips.txt file is your input file... and new-ips.txt is your newly-created file (the final result of your changes.)


Also, if you have a list of IP numbers that happen to have port numbers attached already, (as noted by Vlad and as given by aragaer,) you could try using something like:

sed '/:[0-9]*$/ ! s/$/:80/' ips.txt > new-ips.txt

So, for example, if your input file looked something like this (note the :80):

127.0.0.1
128.0.0.0:80
121.121.33.111

The final result would look something like this:

127.0.0.1:80
128.0.0.0:80
121.121.33.111:80

How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved

org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

That URI is for JSTL 1.0, but you're actually using JSTL 1.2 which uses URIs with an additional /jsp path (because JSTL, who invented EL expressions, was since version 1.1 integrated as part of JSP in order to share/reuse the EL logic in plain JSP too).

So, fix the taglib URI accordingly based on JSTL documentation:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Further you need to make absolutely sure that you do not throw multiple different versioned JSTL JAR files together into the runtime classpath. This is a pretty common mistake among Tomcat users. The problem with Tomcat is that it does not offer JSTL out the box and thus you have to manually install it. This is not necessary in normal Jakarta EE servers. See also What exactly is Java EE?

In your specific case, your pom.xml basically tells you that you have jstl-1.2.jar and standard-1.1.2.jar together. This is wrong. You're basically mixing JSTL 1.2 API+impl from Oracle with JSTL 1.1 impl from Apache. You should stick to only one JSTL implementation.

Installing JSTL on Tomcat 10+

In case you're already on Tomcat 10 or newer (the first Jakartified version, with jakarta.* package instead of javax.* package), use JSTL 2.0 via this sole dependency:

<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>2.0.0</version>
</dependency>

Non-Maven users can achieve the same by dropping the following two physical files in /WEB-INF/lib folder of the web application project (do absolutely not drop standard*.jar or any loose .tld files in there! remove them if necessary).

Installing JSTL on Tomcat 9-

In case you're not on Tomcat 10 yet, but still on Tomcat 9 or older, use JSTL 1.2 via this sole dependency:

<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>1.2.6</version>
</dependency>

Non-Maven users can achieve the same by dropping the following two physical files in /WEB-INF/lib folder of the web application project (do absolutely not drop standard*.jar or any loose .tld files in there! remove them if necessary).

Installing JSTL on normal JEE server

In case you're actually using a normal Jakarta EE server such as WildFly, Payara, etc instead of a barebones servletcontainer such as Tomcat, Jetty, etc, then you don't need to explicitly install JSTL at all. Normal Jakarta EE servers already provide JSTL out the box. In other words, you don't need to add JSTL to pom.xml nor to drop any JAR/TLD files in webapp. Solely the provided scoped Jakarta EE coordinate is sufficient:

<dependency>
    <groupId>jakarta.platform</groupId>
    <artifactId>jakarta.jakartaee-api</artifactId>
    <version><!-- 9.0.0, 8.0.0, etc depending on your server --></version>
    <scope>provided</scope>
</dependency>

Make sure web.xml version is right

Further you should also make sure that your web.xml is declared conform at least Servlet 2.4 and thus not as Servlet 2.3 or older. Otherwise EL expressions inside JSTL tags would in turn fail to work. Pick the highest version matching your target container and make sure that you don't have a <!DOCTYPE> anywhere in your web.xml. Here's a Servlet 5.0 (Tomcat 10) compatible example:

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
    xmlns="https://jakarta.ee/xml/ns/jakartaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
    version="5.0">

    <!-- Config here. -->

</web-app>

And here's a Servlet 4.0 (Tomcat 9) compatible example:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">

    <!-- Config here. -->

</web-app>

See also:

Why do we not have a virtual constructor in C++?

You shouldn't call virtual function within your constructor either. See : http://www.artima.com/cppsource/nevercall.html

In addition I'm not sure that you really need a virtual constructor. You can achieve polymorphic construction without it: you can write a function that will construct your object according to the needed parameters.

How to use Checkbox inside Select Option

The best plugin so far is Bootstrap Multiselect

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<title>jQuery Multi Select Dropdown with Checkboxes</title>

<link rel="stylesheet" href="css/bootstrap-3.1.1.min.css" type="text/css" />
<link rel="stylesheet" href="css/bootstrap-multiselect.css" type="text/css" />

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/bootstrap-3.1.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap-multiselect.js"></script>

</head>

<body>

<form id="form1">

<div style="padding:20px">

<select id="chkveg" multiple="multiple">

    <option value="cheese">Cheese</option>
    <option value="tomatoes">Tomatoes</option>
    <option value="mozarella">Mozzarella</option>
    <option value="mushrooms">Mushrooms</option>
    <option value="pepperoni">Pepperoni</option>
    <option value="onions">Onions</option>

</select>

<br /><br />

<input type="button" id="btnget" value="Get Selected Values" />

<script type="text/javascript">

$(function() {

    $('#chkveg').multiselect({

        includeSelectAllOption: true
    });

    $('#btnget').click(function(){

        alert($('#chkveg').val());
    });
});

</script>

</div>

</form>

</body>
</html>

Here's the DEMO

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $('#chkveg').multiselect({_x000D_
    includeSelectAllOption: true_x000D_
  });_x000D_
_x000D_
  $('#btnget').click(function() {_x000D_
    alert($('#chkveg').val());_x000D_
  });_x000D_
});
_x000D_
.multiselect-container>li>a>label {_x000D_
  padding: 4px 20px 3px 20px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://davidstutz.de/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>_x000D_
<link href="https://davidstutz.de/bootstrap-multiselect/docs/css/bootstrap-3.3.2.min.css" rel="stylesheet"/>_x000D_
<link href="https://davidstutz.de/bootstrap-multiselect/dist/css/bootstrap-multiselect.css" rel="stylesheet"/>_x000D_
<script src="https://davidstutz.de/bootstrap-multiselect/docs/js/bootstrap-3.3.2.min.js"></script>_x000D_
_x000D_
<form id="form1">_x000D_
  <div style="padding:20px">_x000D_
_x000D_
    <select id="chkveg" multiple="multiple">_x000D_
      <option value="cheese">Cheese</option>_x000D_
      <option value="tomatoes">Tomatoes</option>_x000D_
      <option value="mozarella">Mozzarella</option>_x000D_
      <option value="mushrooms">Mushrooms</option>_x000D_
      <option value="pepperoni">Pepperoni</option>_x000D_
      <option value="onions">Onions</option>_x000D_
    </select>_x000D_
    _x000D_
    <br /><br />_x000D_
_x000D_
    <input type="button" id="btnget" value="Get Selected Values" />_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How can I decrypt a password hash in PHP?

The passwords cannot be decrypted as will makes a vulnerability for users. So, you can simply use password_verify() method to compare the passwords.

if(password_verify($upass, $userRow['user_pass'])){
     //code for redirecting to login screen }

where, $upass is password entered by user and $userRow['user_pass'] is user_pass field in database which is encrypted by password_hash() function.

Is there a printf converter to print in binary format?

Here is a small variation of paniq's solution that uses templates to allow printing of 32 and 64 bit integers:

template<class T>
inline std::string format_binary(T x)
{
    char b[sizeof(T)*8+1] = {0};

    for (size_t z = 0; z < sizeof(T)*8; z++)
        b[sizeof(T)*8-1-z] = ((x>>z) & 0x1) ? '1' : '0';

    return std::string(b);
}

And can be used like:

unsigned int value32 = 0x1e127ad;
printf( "  0x%x: %s\n", value32, format_binary(value32).c_str() );

unsigned long long value64 = 0x2e0b04ce0;
printf( "0x%llx: %s\n", value64, format_binary(value64).c_str() );

Here is the result:

  0x1e127ad: 00000001111000010010011110101101
0x2e0b04ce0: 0000000000000000000000000000001011100000101100000100110011100000

What is the different between RESTful and RESTless

REST stands for REpresentational State Transfer and goes a little something like this:

We have a bunch of uniquely addressable 'entities' that we want made available via a web application. Those entities each have some identifier and can be accessed in various formats. REST defines a bunch of stuff about what GET, POST, etc mean for these purposes.

the basic idea with REST is that you can attach a bunch of 'renderers' to different entities so that they can be available in different formats easily using the same HTTP verbs and url formats.

For more clarification on what RESTful means and how it is used google rails. Rails is a RESTful framework so there's loads of good information available in its docs and associated blog posts. Worth a read even if you arent keen to use the framework. For example: http://www.sitepoint.com/restful-rails-part-i/

RESTless means not restful. If you have a web app that does not adhere to RESTful principles then it is not RESTful

The declared package does not match the expected package ""

Solution 1 : One solution that worked for me when this error "The declared package does not match the expected package" occured for a project I checked-out from eclipse CVS :

1.Right click the project in the navigation bar and click 'delete'
2.Make sure 'Delete project contents on disk' option is NOT checked, and click OK.
3.Now after the project is deleted, go to File -> Import -> General -> Existing Projects into Workspace
4.Select your workspace from the directory listing and check the box next to your project name. Click 'Finish'

Solution 2 : Once again I got this error with the following message

Eclipse build errors - java.lang.Object cannot be resolved I had to follow another route mention here and the error went away.

In the mean time, the work around is to remove the JRE System Library from the project and then add it back again. Here are the steps:

  1. Go to properties of project with the build error (right click > Properties) View the "Libraries" tab in the "Build Path" section Find the "JRE System Library" in the list (if this is missing then this error message is not an eclipse bug but a mis-configured project)
  2. Remove the "JRE System Library"
  3. Hit "Add Library ...", Select "JRE System Library" and add the appropriate JRE for the project (eg. 'Workspace default JRE')
  4. Hit "Finish" in the library selection and "OK" in the project properties and then wait for the re-build of the project

Hopefully the error will be resolved ...

one line if statement in php

You can use Ternary operator logic Ternary operator logic is the process of using "(condition)? (true return value) : (false return value)" statements to shorten your if/else structures. i.e

/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true

Looping through all rows in a table column, Excel-VBA

If this is in fact a ListObject table (Insert Table from the ribbon) then you can use the table's .DataBodyRange object to get the number of rows and columns. This ignores the header row.

Sub TableTest()

Dim tbl As ListObject
Dim tRows As Long
Dim tCols As Long

Set tbl = ActiveSheet.ListObjects("Table1")  '## modify to your table name.

With tbl.DataBodyRange
    tRows = .Rows.Count
    tCols = .Columns.Count
End With

MsgBox tbl.Name & " contains " & tRows & " rows and " & tCols & " columns.", vbInformation

End Sub

If you need to use the header row, instead of using tbl.DataBodyRange just use tbl.Range.

How to make a radio button unchecked by clicking it?

I'm surprised no-one has posted this "neat trick" version which doesn't use any JavaScript, it only uses CSS.

_x000D_
_x000D_
#radio1 {
    display: none;
}

#wrapper {
    /* NOTE: This wrapper div is not needed provided you can position the label for #radio1 on top of #radio2 using some other technique. */
    position: relative;
}

#radio1:not(:checked) ~ * label[for="radio1"] {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
#radio1:checked ~ * label[for="radio1"] {
    display: none;
}

/* Non-essential styles: */ 

label[for],
label:not([for="radio1"]) {
    cursor: pointer;
    border-radius: 7px;
}
label[for]:hover + label,
label:not([for="radio1"]):hover {
    background-color: #ccc;
}
_x000D_
<input type="radio" name="group1" id="radio1" checked="checked"  />

<p>Look mum, <strong>no JavaScript!</strong></p>

<div id="wrapper">
    <label for="radio1"></label>
    <label>
        <input type="radio" name="group1" id="radio2" />
        You can toggle me on and off!
    </label>
</div>
_x000D_
_x000D_
_x000D_


Explanation:

  • #radio1 (<input type="radio" id="radio2" />) is always hidden.
  • Using CSS's :checked and :not(:checked) pseudo-class selectors with sibling selectors (+ and ~) allow other elements' style to be affected depending on whether or not an <input type="checkbox" /> or <input type="radio" /> is checked.
    • So when #radio1 is un-checked (or when #radio2 is checked) that causes a <label> to be overlayed on-top of #radio2 and that label has for="radio1", so clicking it will cause #radio1 to be checked, not #radio2.
    • IMPORTANT CAVEAT: CSS's sibling selector rules only allows selectors to select elements based on their ancestors and their ancestors earlier siblings. So you cannot style an element based on any other descendants of its ancestors.
      • This limitation will be removed when CSS4's :has() selector function is supported but as of November 2020 only PrinceXML supports :has() and it's currently looking like :has() will be dropped from CSS4 entirely owing to the difficulty of implementation.

This approach can be scaled to support multiple radio buttons:

_x000D_
_x000D_
#uncheckAll {
    display: none;
}

#uncheckAll:checked ~ * label[for="uncheckAll"] {
    display: none;
}

label {
    cursor: pointer;
}

label:not([for]) {
    position: relative;
}

label[for="uncheckAll"] {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

input[name="group1"]:not(:checked) + label[for="uncheckAll"] {
    display: none;
}
_x000D_
<input type="radio" name="group1" id="uncheckAll" checked="checked"  />

<label>
    <input type="radio" name="group1" id="radio2" />
    <label for="uncheckAll"></label>
    You can toggle me on and off!
</label>

<label>
    <input type="radio" name="group1" id="radio3" />
    <label for="uncheckAll"></label>
    And me!
</label>

<label>
    <input type="radio" name="group1" id="aragorn" />
    <label for="uncheckAll"></label>
    And my sword!
</label>

<label>
    <input type="radio" name="group1" id="gimli" />
    <label for="uncheckAll"></label>
    And my axe!
</label>
_x000D_
_x000D_
_x000D_

Removing Spaces from a String in C?

The easiest and most efficient way to remove spaces from a string is to simply remove the spaces from the string literal. For example, use your editor to 'find and replace' "hello world" with "helloworld", and presto!

Okay, I know that's not what you meant. Not all strings come from string literals, right? Supposing this string you want spaces removed from doesn't come from a string literal, we need to consider the source and destination of your string... We need to consider your entire algorithm, what actual problem you're trying to solve, in order to suggest the simplest and most optimal methods.

Perhaps your string comes from a file (e.g. stdin) and is bound to be written to another file (e.g. stdout). If that's the case, I would question why it ever needs to become a string in the first place. Just treat it as though it's a stream of characters, discarding the spaces as you come across them...

#include <stdio.h>

int main(void) {
    for (;;) {
        int c = getchar();
        if (c == EOF) { break;    }
        if (c == ' ') { continue; }
        putchar(c);
    }
}

By eliminating the need for storage of a string, not only does the entire program become much, much shorter, but theoretically also much more efficient.

Local and global temporary tables in SQL Server

I didn't see any answers that show users where we can find a Global Temp table. You can view Local and Global temp tables in the same location when navigating within SSMS. Screenshot below taken from this link.

Databases --> System Databases --> tempdb --> Temporary Tables

enter image description here

OS X: equivalent of Linux's wget

You could use curl instead. It is installed by default into /usr/bin.

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

I had the same problem. I tried 'yyyy-mm-dd' format i.e. '2013-26-11' and got rid of this problem...

How to check if a number is between two values?

It's an old question, however might be useful for someone like me.

lodash has _.inRange() function https://lodash.com/docs/4.17.4#inRange

Example:

_.inRange(3, 2, 4);
// => true

Please note that this method utilizes the Lodash utility library, and requires access to an installed version of Lodash.

Root user/sudo equivalent in Cygwin?

A new proposal to enhance SUDO for CygWin from GitHub in this thread, named TOUACExt:

  • Automatically opens sudoserver.py.
  • Automatically closes sudoserver.py after timeout (15 minutes default).
  • Request UAC elevation prompt Yes/No style for admin users.
  • Request Admin user/password for non-admin users.
  • Works remotely (SSH) with admin accounts.
  • Creates log.

Still in Pre-Beta, but seems to be working.

How to return value from an asynchronous callback function?

If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/

It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.

Connecting to SQL Server using windows authentication

Your connection string is wrong

<connectionStrings>
   <add name="ConnStringDb1" connectionString="Data Source=localhost\SQLSERVER;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

How do I vertically center an H1 in a div?

you can achieve vertical aligning with display:table-cell:

#section1 {
    height: 90%; 
    text-align:center; 
    display:table;
    width:100%;
}

#section1 h1 {display:table-cell; vertical-align:middle}

Example

Update - CSS3

For an alternate way to vertical align, you can use the following css 3 which should be supported in all the latest browsers:

#section1 {
    height: 90%; 
    width:100%;
    display:flex;
    align-items: center;
    justify-content: center;
}

Updated fiddle

Error pushing to GitHub - insufficient permission for adding an object to repository database

chmod should be chown, so the correct line is:

sudo chown -R gituser:gituser objects

Creating a thumbnail from an uploaded image

Image Upload with thumbnail generate

upload.php

<?php
function generate_thumb_now($field_name = '',$target_folder ='',$file_name = '', $thumb = FALSE, $thumb_folder = '', $thumb_width = '',$thumb_height = ''){
         //folder path setup
         $target_path = $target_folder;
         $thumb_path = $thumb_folder;   
         //file name setup
    $filename_err = explode(".",$_FILES[$field_name]['name']);
    $filename_err_count = count($filename_err);
    $file_ext = $filename_err[$filename_err_count-1];
     if($file_name != '')
     {
        $fileName = $file_name.'.'.$file_ext;
      }
    else
    {
        $fileName = $_FILES[$field_name]['name'];
    }   
    //upload image path
    $upload_image = $target_path.basename($fileName);   
    //upload image
    if(move_uploaded_file($_FILES[$field_name]['tmp_name'],$upload_image))
    {
         //thumbnail creation
        if($thumb == TRUE)
        {
            $thumbnail = $thumb_path.$fileName;
            list($width,$height) = getimagesize($upload_image);
            $thumb_create = imagecreatetruecolor($thumb_width,$thumb_height);
            switch($file_ext){
                case 'jpg':
                    $source = imagecreatefromjpeg($upload_image);
                    break;
                case 'jpeg':
                    $source = imagecreatefromjpeg($upload_image);
                    break;
                case 'png':
                    $source = imagecreatefrompng($upload_image);
                    break;
                case 'gif':
                    $source = imagecreatefromgif($upload_image);
                     break;
                default:
                    $source = imagecreatefromjpeg($upload_image);
            }
       imagecopyresized($thumb_create, $source, 0, 0, 0, 0, $thumb_width, $thumb_height, $width,$height);
            switch($file_ext){
                case 'jpg' || 'jpeg':
                    imagejpeg($thumb_create,$thumbnail,100);
                    break;
                case 'png':
                    imagepng($thumb_create,$thumbnail,100);
                    break;
                case 'gif':
                    imagegif($thumb_create,$thumbnail,100);
                     break;
                default:
                    imagejpeg($thumb_create,$thumbnail,100);
            }
        }
        return $fileName;
     }
    else
    {
        return false;
     }
    }
    if(!empty($_FILES['image']['name'])){       
    $upload_img = generate_thumb_now('image','uploads/','',TRUE,'uploads /thumbs/','400','320');

    //full path of the thumbnail image
    $thumb_src = 'uploads/thumbs/'.$upload_img;

    //set success and error messages
    $message = $upload_img?"<span style='color:#008000;'>Image thumbnail created successfully.</span>":"<span style='color:#F00000;'>Some error occurred, please try again.</span>";

    }else{

    //if form is not submitted, below variable should be blank
    $thumb_src = '';
    $message = '';
    }
    ?>

    <html>
    <head>Image upload and generate thumbnail</head>
     <body>
     <div class="messages"><?php echo $message; ?></div>
      <form method="post" enctype="multipart/form-data">
      <input type="file" name="image"/>
      <input type="submit" name="submit" value="Upload"/>
    </form>
    <?php if($thumb_src != ''){ ?>
    <div class="gallery">
    <ul>
        <li><img src="<?php echo $thumb_src; ?>" alt=""></li>
    </ul>
   </div>
    <?php } ?>
    </body>
    </html>

Is there a .NET/C# wrapper for SQLite?

sqlite-net is an open source, minimal library to allow .NET and Mono applications to store data in SQLite 3 databases. More information at the wiki page.

It is written in C# and is meant to be simply compiled in with your projects. It was first designed to work with MonoTouch on the iPhone, but has grown up to work on all the platforms (Mono for Android, .NET, Silverlight, WP7, WinRT, Azure, etc.).

It is available as a Nuget package, where it is the 2nd most popular SQLite package with over 60,000 downloads as of 2014.

sqlite-net was designed as a quick and convenient database layer. Its design follows from these goals:

  • Very easy to integrate with existing projects and with MonoTouch projects.
  • Thin wrapper over SQLite and should be fast and efficient. (The library should not be the performance bottleneck of your queries.)
  • Very simple methods for executing CRUD operations and queries safely (using parameters) and for retrieving the results of those query in a strongly typed fashion.
  • Works with your data model without forcing you to change your classes. (Contains a small reflection-driven ORM layer.)
  • 0 dependencies aside from a compiled form of the sqlite2 library.

Non-goals include:

  • Not an ADO.NET implementation. This is not a full SQLite driver. If you need that, use System.Data.SQLite.

How to set Internet options for Android emulator?

for the records since this is an old post and since nobody mentioned it, check if you forgot (as I did) to set the android.permission.INTERNET flag in AndroidManifest.xml as, i.e.:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.webviewdemo">
<uses-permission android:name="android.permission.INTERNET"/>
    <application android:icon="@drawable/icon">
        <activity android:name=".WebViewDemo" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

AttributeError: 'tuple' object has no attribute

Variables names are only locally meaningful.

Once you hit

return s1,s2,s3,s4

at the end of the method, Python constructs a tuple with the values of s1, s2, s3 and s4 as its four members at index 0, 1, 2 and 3 - NOT a dictionary of variable names to values, NOT an object with variable names and their values, etc.

If you want the variable names to be meaningful after you hit return in the method, you must create an object or dictionary.

How do I read a large csv file with pandas?

If you use pandas read large file into chunk and then yield row by row, here is what I have done

import pandas as pd

def chunck_generator(filename, header=False,chunk_size = 10 ** 5):
   for chunk in pd.read_csv(filename,delimiter=',', iterator=True, chunksize=chunk_size, parse_dates=[1] ): 
        yield (chunk)

def _generator( filename, header=False,chunk_size = 10 ** 5):
    chunk = chunck_generator(filename, header=False,chunk_size = 10 ** 5)
    for row in chunk:
        yield row

if __name__ == "__main__":
filename = r'file.csv'
        generator = generator(filename=filename)
        while True:
           print(next(generator))

Convert all data frame character columns to factors

The easiest way would be to use the code given below. It would automate the whole process of converting all the variables as factors in a dataframe in R. it worked perfectly fine for me. food_cat here is the dataset which I am using. Change it to the one which you are working on.

    for(i in 1:ncol(food_cat)){

food_cat[,i] <- as.factor(food_cat[,i])

}

How to make a JSON call to a url?

DickFeynman's answer is a workable solution for any circumstance in which JQuery is not a good fit, or isn't otherwise necessary. As ComFreek notes, this requires setting the CORS headers on the server-side. If it's your service, and you have a handle on the bigger question of security, then that's entirely feasible.

Here's a listing of a Flask service, setting the CORS headers, grabbing data from a database, responding with JSON, and working happily with DickFeynman's approach on the client-side:

#!/usr/bin/env python 
from __future__ import unicode_literals
from flask      import Flask, Response, jsonify, redirect, request, url_for
from your_model import *
import os
try:
    import simplejson as json;
except ImportError:
    import json
try:
    from flask.ext.cors import *
except:
    from flask_cors import *

app = Flask(__name__)

@app.before_request
def before_request():
try:
    # Provided by an object in your_model
    app.session = SessionManager.connect()
except:
    print "Database connection failed."

@app.teardown_request
def shutdown_session(exception=None):
    app.session.close()

# A route with a CORS header, to enable your javascript client to access 
# JSON created from a database query.
@app.route('/whatever-data/', methods=['GET', 'OPTIONS'])
@cross_origin(headers=['Content-Type'])
def json_data():
    whatever_list = []
    results_json  = None
    try:
        # Use SQL Alchemy to select all Whatevers, WHERE size > 0.
        whatevers = app.session.query(Whatever).filter(Whatever.size > 0).all()
        if whatevers and len(whatevers) > 0:
            for whatever in whatevers:
                # Each whatever is able to return a serialized version of itself. 
                # Refer to your_model.
                whatever_list.append(whatever.serialize())
             # Convert a list to JSON. 
             results_json = json.dumps(whatever_list)
    except SQLAlchemyError as e:
        print 'Error {0}'.format(e)
        exit(0)

    if len(whatevers) < 1 or not results_json:
        exit(0)
    else:
        # Because we used json.dumps(), rather than jsonify(), 
        # we need to create a Flask Response object, here.
        return Response(response=str(results_json), mimetype='application/json')

if __name__ == '__main__':
    #@NOTE Not suitable for production. As configured, 
    #      your Flask service is in debug mode and publicly accessible.  
    app.run(debug=True, host='0.0.0.0', port=5001) # http://localhost:5001/

your_model contains the serialization method for your whatever, as well as the database connection manager (which could stand a little refactoring, but suffices to centralize the creation of database sessions, in bigger systems or Model/View/Control architectures). This happens to use postgreSQL, but could just as easily use any server side data store:

#!/usr/bin/env python 
# Filename: your_model.py
import time
import psycopg2
import psycopg2.pool
import psycopg2.extras
from   psycopg2.extensions        import adapt, register_adapter, AsIs
from   sqlalchemy                 import update
from   sqlalchemy.orm             import *
from   sqlalchemy.exc             import *
from   sqlalchemy.dialects        import postgresql
from   sqlalchemy                 import Table, Column, Integer, ForeignKey
from   sqlalchemy.ext.declarative import declarative_base

class SessionManager(object):
    @staticmethod
    def connect():
        engine = create_engine('postgresql://id:passwd@localhost/mydatabase', 
                                echo = True)
        Session = sessionmaker(bind = engine, 
                               autoflush = True, 
                               expire_on_commit = False, 
                               autocommit = False)
    session = Session()
    return session

  @staticmethod
  def declareBase():
      engine = create_engine('postgresql://id:passwd@localhost/mydatabase', echo=True)
      whatever_metadata = MetaData(engine, schema ='public')
      Base = declarative_base(metadata=whatever_metadata)
      return Base

Base = SessionManager.declareBase()

class Whatever(Base):
    """Create, supply information about, and manage the state of one or more whatever.
    """
    __tablename__         = 'whatever'
    id                    = Column(Integer, primary_key=True)
    whatever_digest       = Column(VARCHAR, unique=True)
    best_name             = Column(VARCHAR, nullable = True)
    whatever_timestamp    = Column(BigInteger, default = time.time())
    whatever_raw          = Column(Numeric(precision = 1000, scale = 0), default = 0.0)
    whatever_label        = Column(postgresql.VARCHAR, nullable = True)
    size                  = Column(BigInteger, default = 0)

    def __init__(self, 
                 whatever_digest = '', 
                 best_name = '', 
                 whatever_timestamp = 0, 
                 whatever_raw = 0, 
                 whatever_label = '', 
                 size = 0):
        self.whatever_digest         = whatever_digest
        self.best_name               = best_name
        self.whatever_timestamp      = whatever_timestamp
        self.whatever_raw            = whatever_raw
        self.whatever_label          = whatever_label

    # Serialize one way or another, just handle appropriately in the client.  
    def serialize(self):
        return {
            'best_name'     :self.best_name,
            'whatever_label':self.whatever_label,
            'size'          :self.size,
        }

In retrospect, I might have serialized the whatever objects as lists, rather than a Python dict, which might have simplified their processing in the Flask service, and I might have separated concerns better in the Flask implementation (The database call probably shouldn't be built-in the the route handler), but you can improve on this, once you have a working solution in your own development environment.

Also, I'm not suggesting people avoid JQuery. But, if JQuery's not in the picture, for one reason or another, this approach seems like a reasonable alternative.

It works, in any case.

Here's my implementation of DickFeynman's approach, in the the client:

<script type="text/javascript">
    var addr = "dev.yourserver.yourorg.tld"
    var port = "5001"

    function Get(whateverUrl){
        var Httpreq = new XMLHttpRequest(); // a new request
        Httpreq.open("GET",whateverUrl,false);
        Httpreq.send(null);
        return Httpreq.responseText;          
    }

    var whatever_list_obj = JSON.parse(Get("http://" + addr + ":" + port + "/whatever-data/"));
    whatever_qty = whatever_list_obj.length;
    for (var i = 0; i < whatever_qty; i++) {
        console.log(whatever_list_obj[i].best_name);
    }
</script>

I'm not going to list my console output, but I'm looking at a long list of whatever.best_name strings.

More to the point: The whatever_list_obj is available for use in my javascript namespace, for whatever I care to do with it, ...which might include generating graphics with D3.js, mapping with OpenLayers or CesiumJS, or calculating some intermediate values which have no particular need to live in my DOM.

How to view data saved in android database(SQLite)?

If you don't want to download anything, you can use sqlite3 tool which is provided with adb :

Examining sqlite3 databases from a remote shell

and :

Command Line Shell For SQLite

Execute PowerShell Script from C# with Commandline Arguments

For me, the most flexible way to run PowerShell script from C# was using PowerShell.Create().AddScript()

The snippet of the code is

string scriptDirectory = Path.GetDirectoryName(
    ConfigurationManager.AppSettings["PathToTechOpsTooling"]);

var script =    
    "Set-Location " + scriptDirectory + Environment.NewLine +
    "Import-Module .\\script.psd1" + Environment.NewLine +
    "$data = Import-Csv -Path " + tempCsvFile + " -Encoding UTF8" + 
        Environment.NewLine +
    "New-Registration -server " + dbServer + " -DBName " + dbName + 
       " -Username \"" + user.Username + "\" + -Users $userData";

_powershell = PowerShell.Create().AddScript(script);
_powershell.Invoke<User>();
foreach (var errorRecord in _powershell.Streams.Error)
    Console.WriteLine(errorRecord);

You can check if there's any error by checking Streams.Error. It was really handy to check the collection. User is the type of object the PowerShell script returns.

Get UTC time in seconds

I believe +%s is seconds since epoch. It's timezone invariant.

How to solve java.lang.NullPointerException error?

A NullPointerException means that one of the variables you are passing is null, but the code tries to use it like it is not.

For example, If I do this:

Integer myInteger = null;
int n = myInteger.intValue();

The code tries to grab the intValue of myInteger, but since it is null, it does not have one: a null pointer exception happens.

What this means is that your getTask method is expecting something that is not a null, but you are passing a null. Figure out what getTask needs and pass what it wants!

port forwarding in windows

I've used this little utility whenever the need arises: http://www.analogx.com/contents/download/network/pmapper/freeware.htm

The last time this utility was updated was in 2009. I noticed on my Win10 machine, it hangs for a few seconds when opening new windows sometimes. Other then that UI glitch, it still does its job fine.

jQuery how to bind onclick event to dynamically added HTML element

How about the Live method?

$('.add_to_this a').live('click', function() {
    alert('hello from binded function call');
});

Still, what you did about looks like it should work. There's another post that looks pretty similar.

Run a php app using tomcat?

tomcat is designed as JSP servlet container. Apache is designed PHP web server. Use apache as web server, responding for PHP request, and direct JSP servlet request to tomcat container. should be better implementation.

Direct casting vs 'as' operator?

string s = (string)o; // 1

Throws InvalidCastException if o is not a string. Otherwise, assigns o to s, even if o is null.

string s = o as string; // 2

Assigns null to s if o is not a string or if o is null. For this reason, you cannot use it with value types (the operator could never return null in that case). Otherwise, assigns o to s.

string s = o.ToString(); // 3

Causes a NullReferenceException if o is null. Assigns whatever o.ToString() returns to s, no matter what type o is.


Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions).

3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.

How to compare two Dates without the time portion?

This is what worked for me:

var Date1 = new Date(dateObject1.toDateString()); //this sets time to 00:00:00
var Date2 = new Date(dateObject2.toDateString()); 
//do a normal compare
if(Date1 > Date2){ //do something }

What is the most efficient/quickest way to loop through rows in VBA (excel)?

If you are just looping through 10k rows in column A, then dump the row into a variant array and then loop through that.

You can then either add the elements to a new array (while adding rows when needed) and using Transpose() to put the array onto your range in one move, or you can use your iterator variable to track which row you are on and add rows that way.

Dim i As Long
Dim varray As Variant

varray = Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value

For i = 1 To UBound(varray, 1)
    ' do stuff to varray(i, 1)
Next

Here is an example of how you could add rows after evaluating each cell. This example just inserts a row after every row that has the word "foo" in column A. Not that the "+2" is added to the variable i during the insert since we are starting on A2. It would be +1 if we were starting our array with A1.

Sub test()

Dim varray As Variant
Dim i As Long

varray = Range("A2:A10").Value

'must step back or it'll be infinite loop
For i = UBound(varray, 1) To LBound(varray, 1) Step -1
    'do your logic and evaluation here
    If varray(i, 1) = "foo" Then
       'not how to offset the i variable 
       Range("A" & i + 2).EntireRow.Insert
    End If
Next

End Sub

How do you dynamically add elements to a ListView on Android?

        This is the simple answer how to add datas dynamically in listview android kotlin


class MainActivity : AppCompatActivity(){
        
            var listItems = arrayListOf<String>()
            val array = arrayOf("a","b","c","d","e")
            var listView: ListView? = null
    
            private lateinit var adapter: listViewAdapter
        
            override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)
                setContentView(R.layout.scrollview_layout)
        
                listItems.add("a")
                listItems.add("b")
                listItems.add("c")
                listItems.add("d")
                listItems.add("e")
        
                //if you want to add array items to a list you can try this for each loop
                for(items in array)
                    listItems.add(items)
                
                //check the result in console
                Log.e("TAG","listItems array: $listItems")
    
            adapter = ListViewAdapter()
            adapter.updateList(listItems)
            adapter.notifyDataSetChanged()
        
            }
        }


//Here is the adapter class
    class ListviewAdapter : BaseAdapter(){
    
    private var itemsList = arrayListOf<String>()
    
    override fun getView(position: Int, container: View?, parent: ViewGroup?): View {
            var view  = container
            val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            if (view == null)
                view = inflater.inflate(R.layout.list_pc_summary, parent, false)
    
    return view
    }
    
    override fun getItem(position: Int): Any  = itemsList[position]
    
    override fun getItemId(position: Int): Long = position.toLong()
    
    override fun getCount(): Int = itemsList.size
    
    fun updateList(listItems: ArrayList<String>()){
        this.itemsList = listItems
        notifyDatSetChanged
    
    }
   
        }
       
    //Here I just explained two ways, we can do this many ways.

Angular and debounce

HTML file:

<input [ngModel]="filterValue"
       (ngModelChange)="filterValue = $event ; search($event)"
        placeholder="Search..."/>

TS file:

timer = null;
time = 250;
  search(searchStr : string) : void {
    clearTimeout(this.timer);
    this.timer = setTimeout(()=>{
      console.log(searchStr);
    }, time)
  }

MySQL foreign key constraints, cascade delete

I think (I'm not certain) that foreign key constraints won't do precisely what you want given your table design. Perhaps the best thing to do is to define a stored procedure that will delete a category the way you want, and then call that procedure whenever you want to delete a category.

CREATE PROCEDURE `DeleteCategory` (IN category_ID INT)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
BEGIN

DELETE FROM
    `products`
WHERE
    `id` IN (
        SELECT `products_id`
        FROM `categories_products`
        WHERE `categories_id` = category_ID
    )
;

DELETE FROM `categories`
WHERE `id` = category_ID;

END

You also need to add the following foreign key constraints to the linking table:

ALTER TABLE `categories_products` ADD
    CONSTRAINT `Constr_categoriesproducts_categories_fk`
    FOREIGN KEY `categories_fk` (`categories_id`) REFERENCES `categories` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT `Constr_categoriesproducts_products_fk`
    FOREIGN KEY `products_fk` (`products_id`) REFERENCES `products` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE

The CONSTRAINT clause can, of course, also appear in the CREATE TABLE statement.

Having created these schema objects, you can delete a category and get the behaviour you want by issuing CALL DeleteCategory(category_ID) (where category_ID is the category to be deleted), and it will behave how you want. But don't issue a normal DELETE FROM query, unless you want more standard behaviour (i.e. delete from the linking table only, and leave the products table alone).

Default interface methods are only supported starting with Android N

You should use Java 8 to solve this, based on the Android documentation you can do this by

clicking File > Project Structure

and change Source Compatibility and Target Compatibility.

enter image description here

and you can also configure it directly in the app-level build.gradle file:

android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

I've managed to find a CSS workaround to preventing bouncing of the viewport. The key was to wrap the content in 3 divs with -webkit-touch-overflow:scroll applied to them. The final div should have a min-height of 101%. In addition, you should explicitly set fixed widths/heights on the body tag representing the size of your device. I've added a red background on the body to demonstrate that it is the content that is now bouncing and not the mobile safari viewport.

Source code below and here is a plunker (this has been tested on iOS7 GM too). http://embed.plnkr.co/NCOFoY/preview

If you intend to run this as a full-screen app on iPhone 5, modify the height to 1136px (when apple-mobile-web-app-status-bar-style is set to 'black-translucent' or 1096px when set to 'black'). 920x is the height of the viewport once the chrome of mobile safari has been taken into account).

<!doctype html>
<html>

<head>
    <meta name="viewport" content="initial-scale=0.5,maximum-scale=0.5,minimum-scale=0.5,user-scalable=no" />
    <style>
        body { width: 640px; height: 920px; overflow: hidden; margin: 0; padding: 0; background: red; }
        .no-bounce { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
        .no-bounce > div { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
        .no-bounce > div > div { width: 100%; min-height: 101%; font-size: 30px; }
        p { display: block; height: 50px; }
    </style>
</head>

<body>

    <div class="no-bounce">
        <div>
            <div>
                <h1>Some title</h1>
                <p>item 1</p>
                <p>item 2</p>
                <p>item 3</p>
                <p>item 4</p>
                <p>item 5</p>
                <p>item 6</p>
                <p>item 7</p>
                <p>item 8</p>
                <p>item 9</p>
                <p>item 10</p>
                <p>item 11</p>
                <p>item 12</p>
                <p>item 13</p>
                <p>item 14</p>
                <p>item 15</p>
                <p>item 16</p>
                <p>item 17</p>
                <p>item 18</p>
                <p>item 19</p>
                <p>item 20</p>
            </div>
        </div>
    </div>

</body>

</html>

Removing single-quote from a string in php

$replace_str = array('"', "'", ",");
$FileName = str_replace($replace_str, "", $UserInput);

How to stash my previous commit?

I solving doing this:

Remove the target commit

git revert --strategy resolve 222

Save commit 222 to patch file

git diff HEAD~2 HEAD~1 > 222.patch

Apply this patch to unstage

patch -p1 < 222.patch

Push to stash

git stash

Remove temp file

rm -f 222.patch

Very simple strategy in my opinion

How to redirect stdout to both file and console with scripting?

I tried this:

"""
Transcript - direct print output to a file, in addition to terminal.

Usage:
    import transcript
    transcript.start('logfile.log')
    print("inside file")
    transcript.stop()
    print("outside file")
"""

import sys

class Transcript(object):

    def __init__(self, filename):
        self.terminal = sys.stdout, sys.stderr
        self.logfile = open(filename, "a")

    def write(self, message):
        self.terminal.write(message)
        self.logfile.write(message)

    def flush(self):
        # this flush method is needed for python 3 compatibility.
        # this handles the flush command by doing nothing.
        # you might want to specify some extra behavior here.
        pass

def start(filename):
    """Start transcript, appending print output to given filename"""
    sys.stdout = Transcript(filename)

def stop():
    """Stop transcript and return print functionality to normal"""
    sys.stdout.logfile.close()
    sys.stdout = sys.stdout.terminal
    sys.stderr = sys.stderr.terminal

twitter bootstrap text-center when in xs mode

Bootstrap 4

<div class="col-md-9 col-xs-12 text-md-left text-center">md left, xs center</div>
<div class="col-md-9 col-xs-12 text-md-right text-center">md right, xs center</div>

ArrayList filter

write your self a filter function

 public List<T> filter(Predicate<T> criteria, List<T> list) {
        return list.stream().filter(criteria).collect(Collectors.<T>toList());
 }

And then use

    list = new Test().filter(x -> x > 2, list);

This is the most neat version in Java, but needs JDK 1.8 to support lambda calculus

Getting activity from context in android

Context may be an Application, a Service, an Activity, and more.

Normally the context of Views in an Activity is the Activity itself so you may think you can just cast this Context to Activity but actually you can't always do it, because the context can also be a ContextThemeWrapper in this case.

ContextThemeWrapper is used heavily in the recent versions of AppCompat and Android (thanks to the android:theme attribute in layouts) so I would personally never perform this cast.

So short answer is: you can't reliably retrieve an Activity from a Context in a View. Pass the Activity to the view by calling a method on it which takes the Activity as parameter.

HTML table sort

Another approach to sort HTML table. (based on W3.JS HTML Sort)

_x000D_
_x000D_
let tid = "#usersTable";_x000D_
let headers = document.querySelectorAll(tid + " th");_x000D_
_x000D_
// Sort the table element when clicking on the table headers_x000D_
headers.forEach(function(element, i) {_x000D_
  element.addEventListener("click", function() {_x000D_
    w3.sortHTML(tid, ".item", "td:nth-child(" + (i + 1) + ")");_x000D_
  });_x000D_
});
_x000D_
th {_x000D_
  cursor: pointer;_x000D_
  background-color: coral;_x000D_
}
_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="usersTable" class="w3-table-all">_x000D_
  <!--     _x000D_
  <tr>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(1)')">Name</th>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(2)')">Address</th>_x000D_
    <th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(3)')">Sales Person</th>_x000D_
  </tr> _x000D_
  -->_x000D_
  <tr>_x000D_
    <th>Name</th>_x000D_
    <th>Address</th>_x000D_
    <th>Sales Person</th>_x000D_
  </tr>_x000D_
_x000D_
  <tr class="item">_x000D_
    <td>user:2911002</td>_x000D_
    <td>UK</td>_x000D_
    <td>Melissa</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2201002</td>_x000D_
    <td>France</td>_x000D_
    <td>Justin</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2901092</td>_x000D_
    <td>San Francisco</td>_x000D_
    <td>Judy</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2801002</td>_x000D_
    <td>Canada</td>_x000D_
    <td>Skipper</td>_x000D_
  </tr>_x000D_
  <tr class="item">_x000D_
    <td>user:2901009</td>_x000D_
    <td>Christchurch</td>_x000D_
    <td>Alex</td>_x000D_
  </tr>_x000D_
_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do I return an int from EditText? (Android)

Set the digits attribute to true, which will cause it to only allow number inputs.

Then do Integer.valueOf(editText.getText()) to get an int value out.

Limit number of characters allowed in form input text field

The following code includes a counted...

_x000D_
_x000D_
var count = 1;_x000D_
_x000D_
do {_x000D_
    function count_down(obj, count){_x000D_
_x000D_
    let element = document.getElementById('count'+ count);_x000D_
_x000D_
    element.innerHTML = 80 - obj.value.length;_x000D_
_x000D_
    if(80 - obj.value.length < 5){_x000D_
        element.style.color = "firebrick";_x000D_
    }else{_x000D_
        element.style.color = "#333";_x000D_
    }_x000D_
}_x000D_
count++;_x000D_
} while (count < 20); 
_x000D_
.text-input {_x000D_
    padding: 8px 16px;_x000D_
    width: 50%;_x000D_
    margin-bottom: 5px;_x000D_
    margin-top: 10px;_x000D_
    font-size: 20px;_x000D_
    font-weight: 700;_x000D_
    font-family: Raleway;_x000D_
    border: 1px solid dodgerblue;_x000D_
  }
_x000D_
<p><input placeholder="Title" id="bike-input-title" onkeyup="count_down(this, 3)" maxlength="80"  class="text-input" name="bikeTitle" ></p>_x000D_
        <span id="count3" style="float: right; font-family: Raleway; font-size:20px; font-weight:600; margin-top:-5px;">80</span><br>
_x000D_
_x000D_
_x000D_

Why is IoC / DI not common in Python?

Haven't used Python in several years, but I would say that it has more to do with it being a dynamically typed language than anything else. For a simple example, in Java, if I wanted to test that something wrote to standard out appropriately I could use DI and pass in any PrintStream to capture the text being written and verify it. When I'm working in Ruby, however, I can dynamically replace the 'puts' method on STDOUT to do the verify, leaving DI completely out of the picture. If the only reason I'm creating an abstraction is to test the class that's using it (think File system operations or the clock in Java) then DI/IoC creates unnecessary complexity in the solution.

Javascript: Easier way to format numbers?

Here's the YUI version if anyone's interested:

http://developer.yahoo.com/yui/docs/YAHOO.util.Number.html

var str = YAHOO.util.Number.format(12345, { thousandsSeparator: ',' } );

How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

I think it is better to update your "mysql-connector" lib package, so database can be still more safe.

I am using mysql of version 8.0.12. When I updated the mysql-connector-java to version 8.0.11, the problem was gone.

Rotate a div using javascript

To rotate a DIV we can add some CSS that, well, rotates the DIV using CSS transform rotate.

To toggle the rotation we can keep a flag, a simple variable with a boolean value that tells us what way to rotate.

var rotated = false;

document.getElementById('button').onclick = function() {
    var div = document.getElementById('div'),
        deg = rotated ? 0 : 66;

    div.style.webkitTransform = 'rotate('+deg+'deg)'; 
    div.style.mozTransform    = 'rotate('+deg+'deg)'; 
    div.style.msTransform     = 'rotate('+deg+'deg)'; 
    div.style.oTransform      = 'rotate('+deg+'deg)'; 
    div.style.transform       = 'rotate('+deg+'deg)'; 

    rotated = !rotated;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

To add some animation to the rotation all we have to do is add CSS transitions

div {
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

Another way to do it is using classes, and setting all the styles in a stylesheet, thus keeping them out of the javascript

document.getElementById('button').onclick = function() {
    document.getElementById('div').classList.toggle('rotated');
}

_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    document.getElementById('div').classList.toggle('rotated');_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
#div.rotated {_x000D_
    -webkit-transform : rotate(66deg); _x000D_
    -moz-transform : rotate(66deg); _x000D_
    -ms-transform : rotate(66deg); _x000D_
    -o-transform : rotate(66deg); _x000D_
    transform : rotate(66deg); _x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

How do I install Eclipse Marketplace in Eclipse Classic?

help=>install new software=>workwith choice Juno - http://download.eclipse.org/releases/juno and search in the below "type filter text" --------------market

you will see this plugs Marketplace Client

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

Here is a simple method to troubleshoot connection issues:

  1. Create an empty file called test.udl using a text editor
  2. Double click the file test.udl, then specify your connection properties
  3. Hit the "Test Connection" button.

How can I check if a value is of type Integer?

If you have a double/float/floating point number and want to see if it's an integer.

public boolean isDoubleInt(double d)
{
    //select a "tolerance range" for being an integer
    double TOLERANCE = 1E-5;
    //do not use (int)d, due to weird floating point conversions!
    return Math.abs(Math.floor(d) - d) < TOLERANCE;
}

If you have a string and want to see if it's an integer. Preferably, don't throw out the Integer.valueOf() result:

public boolean isStringInt(String s)
{
    try
    {
        Integer.parseInt(s);
        return true;
    } catch (NumberFormatException ex)
    {
        return false;
    }
}

If you want to see if something is an Integer object (and hence wraps an int):

public boolean isObjectInteger(Object o)
{
    return o instanceof Integer;
}

Android SeekBar setOnSeekBarChangeListener

onProgressChanged() should be called on every progress changed, not just on first and last touch (that why you have onStartTrackingTouch() and onStopTrackingTouch() methods).

Make sure that your SeekBar have more than 1 value, that is to say your MAX>=3.

In your onCreate:

 yourSeekBar=(SeekBar) findViewById(R.id.yourSeekBar);
 yourSeekBar.setOnSeekBarChangeListener(new yourListener());

Your listener:

private class yourListener implements SeekBar.OnSeekBarChangeListener {

        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
                            // Log the progress
            Log.d("DEBUG", "Progress is: "+progress);
                            //set textView's text
            yourTextView.setText(""+progress);
        }

        public void onStartTrackingTouch(SeekBar seekBar) {}

        public void onStopTrackingTouch(SeekBar seekBar) {}

    }

Please share some code and the Log results for furter help.

JavaScript - document.getElementByID with onClick

The onclick property is all lower-case, and accepts a function, not a string.

document.getElementById("test").onclick = foo2;

See also addEventListener.

Get Element value with minidom with Python

The question has been answered, my contribution consists in clarifying one thing that may confuse beginners:

Some of the suggested and correct answers used firstChild.data and others used firstChild.nodeValue instead. In case you are wondering what is the different between them, you should remember they do the same thing because nodeValue is just an alias for data.

The reference to my statement can be found as a comment on the source code of minidom:

#nodeValue is an alias for data

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

Python assigning multiple variables to same value? list behavior

The code that does what I need could be this:

# test

aux=[[0 for n in range(3)] for i in range(4)]
print('aux:',aux)

# initialization

a,b,c,d=[[0 for n in range(3)] for i in range(4)]

# changing values

a[0]=1
d[2]=5
print('a:',a)
print('b:',b)
print('c:',c)
print('d:',d)

Result:

('aux:', [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])
('a:', [1, 0, 0])
('b:', [0, 0, 0])
('c:', [0, 0, 0])
('d:', [0, 0, 5])

How to add an object to an array

With push you can even add multiple objects to an array

  let myArray = [];

   myArray.push(
              {name:"James", dataType:TYPES.VarChar, Value: body.Name},
              {name:"Boo", dataType:TYPES.VarChar, Value: body.Name},
              {name:"Alina", dataType:TYPES.VarChar, Value: body.Name}
             );

JavaScript: undefined !== undefined?

A). I never have and never will trust any tool which purports to produce code without the user coding, which goes double where it's a graphical tool.

B). I've never had any problem with this with Facebook Connect. It's all still plain old JavaScript code running in a browser and undefined===undefined wherever you are.

In short, you need to provide evidence that your object.x really really was undefined and not null or otherwise, because I believe it is impossible for what you're describing to actually be the case - no offence :) - I'd put money on the problem existing in the Tersus code.

How can I create a dynamic button click event on a dynamic button?

Let's say you have 25 objects and want one process to handle any one objects click event. You could write 25 delegates or use a loop to handle the click event.

public form1()
{
    foreach (Panel pl  in Container.Components)
    {
        pl.Click += Panel_Click;
    }
}

private void Panel_Click(object sender, EventArgs e)
{
    // Process the panel clicks here
    int index = Panels.FindIndex(a => a == sender);
    ...
}

How to check for DLL dependency?

  1. There is a program called "Depends"
  2. If you have cygwin installed, nothing simpler then ldd file.exe

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

java.io.IOException: Server returned HTTP response code: 500

HTTP status code 500 usually means that the webserver code has crashed. You need to determine the status code beforehand using HttpURLConnection#getResponseCode() and in case of errors, read the HttpURLConnection#getErrorStream() instead. It may namely contain information about the problem.

If the host has blocked you, you would rather have gotten a 4nn status code like 401 or 403.

See also:

What does \d+ mean in regular expression terms?

\d is a digit, + is 1 or more, so a sequence of 1 or more digits

Save the console.log in Chrome to a file

These days it's very easy - right click any item displayed in the console log and select save as and save the whole log output to a file on your computer.

Git: How to rebase to a specific commit?

You can avoid using the --onto parameter by making a temp branch on the commit you like and then use rebase in its simple form:

git branch temp master^
git checkout topic
git rebase temp
git branch -d temp

Git commit in terminal opens VIM, but can't get back to terminal

To save your work and exit press Esc and then :wq (w for write and q for quit).

Alternatively, you could both save and exit by pressing Esc and then :x

To set another editor run export EDITOR=myFavoriteEdioron your terminal, where myFavoriteEdior can be vi, gedit, subl(for sublime) etc.

Reversing a string in C

bool reverse_string(char* str) {
    if(str == NULL){
        return false;
    }
    if(strlen(str) < 2){
        return false;
    }
    
    char* first = str;
    char* last = str + strlen(str) - 1; // Minus 1 accounts for Index offset
    char temp;

    do{
        temp = *first;
        *first = *last;
        *last = temp;
    }
    while (++first < --last); // Update Pointer Addresses and check for equality

    return true;
}

This solution is based on GManNickG's post with a few modifications. The initial logical statement may be dangerous if !str is not evaluated before the strlen operation (For a NULL ptr). This wasn't the case with my compiler. I thought I would add this code because its a nice example of a do-while loop.

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

FromBody string parameter is giving null

I know this answer is kinda old and there are some very good answers who already solve the problem. In order to expand the issue I'd like to mention one more thing that has driven me crazy for the last 4 or 5 hours.

It is VERY VERY VERY important that your properties in your model class have the set attribute enabled.

This WILL NOT work (parameter still null):

/* Action code */
[HttpPost]
public Weird NOURLAuthenticate([FromBody] Weird form) {
    return form;
}
/* Model class code */
public class Weird {
    public string UserId {get;}
    public string UserPwd {get;}
}

This WILL work:

/* Action code */
[HttpPost]
public Weird NOURLAuthenticate([FromBody] Weird form) {
    return form;
}
/* Model class code */
public class Weird {
    public string UserId {get; set;}
    public string UserPwd {get; set;}
}

SQL Views - no variables?

How often do you need to refresh the view? I have a similar case where the new data comes once a month; then I have to load it, and during the loading processes I have to create new tables. At that moment I alter my view to consider the changes. I used as base the information in this other question:

Create View Dynamically & synonyms

In there, it is proposed to do it 2 ways:

  1. using synonyms.
  2. Using dynamic SQL to create view (this is what helped me achieve my result).

Find index of a value in an array

int keyIndex = words.TakeWhile(w => !w.IsKey).Count();

How can I match a string with a regex in Bash?

I don't have enough rep to comment here, so I'm submitting a new answer to improve on dogbane's answer. The dot . in the regexp

[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched

will actually match any character, not only the literal dot between 'tar.bz2', for example

[[ sed-4.2.2.tar4bz2 =~ tar.bz2$ ]] && echo matched
[[ sed-4.2.2.tar§bz2 =~ tar.bz2$ ]] && echo matched

or anything that doesn't require escaping with '\'. The strict syntax should then be

[[ sed-4.2.2.tar.bz2 =~ tar\.bz2$ ]] && echo matched

or you can go even stricter and also include the previous dot in the regex:

[[ sed-4.2.2.tar.bz2 =~ \.tar\.bz2$ ]] && echo matched

How can I set the focus (and display the keyboard) on my EditText programmatically

I recommend using a LifecycleObserver which is part of the Handling Lifecycles with Lifecycle-Aware Components of Android Jetpack.

I want to open and close the Keyboard when the Fragment/Activity appears. Firstly, define two extension functions for the EditText. You can put them anywhere in your project:

fun EditText.showKeyboard() {
    requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}

fun EditText.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(this.windowToken, 0)
}

Then define a LifecycleObserver which opens and closes the keyboard when the Activity/Fragment reaches onResume() or onPause:

class EditTextKeyboardLifecycleObserver(private val editText: WeakReference<EditText>) :
    LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun openKeyboard() {
        editText.get()?.postDelayed({ editText.get()?.showKeyboard() }, 100)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun closeKeyboard() {
        editText.get()?.hideKeyboard()
    }
}

Then add the following line to any of your Fragments/Activities, you can reuse the LifecycleObserver any times. E.g. for a Fragment:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    // inflate the Fragment layout

    lifecycle.addObserver(EditTextKeyboardLifecycleObserver(WeakReference(myEditText)))

    // do other stuff and return the view

}

*.h or *.hpp for your class definitions

I'm answering this as an reminder, to give point to my comment(s) on "user1949346" answer to this same OP.


So as many already answered: either way is fine. Followed by emphasizes of their own impressions.

Introductory, as also in the previous named comments stated, my opinion is C++ header extensions are proposed to be .h if there is actually no reason against it.

Since the ISO/IEC documents use this notation of header files and no string matching to .hpp even occurs in their language documentations about C++.

But I'm now aiming for an approvable reason WHY either way is ok, and especially why it's not subject of the language it self.

So here we go.

The C++ documentation (I'm actually taking reference from the version N3690) defines that a header has to conform to the following syntax:

2.9 Header names

header-name:
    < h-char-sequence >
    " q-char-sequence "
h-char-sequence:
    h-char
    h-char-sequence h-char
h-char:
    any member of the source character set except new-line and >
q-char-sequence:
    q-char
    q-char-sequence q-char
q-char:
    any member of the source character set except new-line and "

So as we can extract from this part, the header file name may be anything that is valid in the source code, too. Except containing '\n' characters and depending on if it is to be included by <> it is not allowed to contain a >. Or the other way if it is included by ""-include it is not allowed to contain a ".

In other words: if you had a environment supporting filenames like prettyStupidIdea.>, an include like:

#include "prettyStupidIdea.>"

would be valid, but:

#include <prettyStupidIdea.>>

would be invalid. The other way around the same.

And even

#include <<.<>

would be a valid includable header file name.

Even this would conform to C++, it would be a pretty pretty stupid idea, tho.

And that's why .hpp is valid, too.

But it's not an outcome of the committees designing decisions for the language!

So discussing about to use .hpp is same as doing it about .cc, .mm or what ever else I read in other posts on this topic.

I have to admit I have no clue where .hpp came from1, but I would bet an inventor of some parsing tool, IDE or something else concerned with C++ came to this idea to optimize some internal processes or just to invent some (probably even for them necessarily) new naming conventions.

But it is not part of the language.

And whenever one decides to use it this way. May it be because he likes it most or because some applications of the workflow require it, it never2 is a requirement of the language. So whoever says "the pp is because it is used with C++", simply is wrong in regards of the languages definition.

C++ allows anything respecting the previous paragraph. And if there is anything the committee proposed to use, then it is using .h since this is the extension sued in all examples of the ISO document.

Conclusion:

As long you don't see/feel any need of using .h over .hpp or vise versa, you shouldn't bother. Because both would be form a valid header name of same quality in respect to the standard. And therefore anything that REQUIRES you to use .h or .hpp is an additional restriction of the standard which could even be contradicting with other additional restrictions not conform with each other. But as OP doesn't mention any additional language restriction, this is the only correct and approvable answer to the question

"*.h or *.hpp for your class definitions" is:

Both are equally correct and applicable as long as no external restrictions are present.


1From what I know, apparently, it is the boost framework that came up with that .hpp extension.

2Of course I can't say what some future versions will bring with it!

Subtracting two lists in Python

To prove jkp's point that 'anything on one line will probably be helishly complex to understand', I created a one-liner. Please do not mod me down because I understand this is not a solution that you should actually use. It is just for demonstrational purposes.

The idea is to add the values in a one by one, as long as the total times you have added that value does is smaller than the total number of times this value is in a minus the number of times it is in b:

[ value for counter,value in enumerate(a) if a.count(value) >= b.count(value) + a[counter:].count(value) ]

The horror! But perhaps someone can improve on it? Is it even bug free?

Edit: Seeing Devin Jeanpierre comment about using a dictionary datastructure, I came up with this oneliner:

sum([ [value]*count for value,count in {value:a.count(value)-b.count(value) for value in set(a)}.items() ], [])

Better, but still unreadable.

React : difference between <Route exact path="/" /> and <Route path="/" />

Take a look here: https://reacttraining.com/react-router/core/api/Route/exact-bool

exact: bool

When true, will only match if the path matches the location.pathname exactly.

**path**    **location.pathname**   **exact**   **matches?**

/one        /one/two                true        no
/one        /one/two                false       yes

Delete files or folder recursively on Windows CMD

You could also do:

del /s /p *.{your extension here}

The /p will prompt you for each found file, if you're nervous about deleting something you shouldn't.

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

You can achieve it like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

<script>
       window.jQuery || document.write('<script src="/path/to/your/jquery"><\/script>');
</script>

This should be in your page's <head> and any jQuery ready event handlers should be in the <body> to avoid errors (although it's not fool-proof!).

One more reason to not use Google-hosted jQuery is that in some countries, Google's domain name is banned.

How to pad zeroes to a string?

Strings:

>>> n = '4'
>>> print(n.zfill(3))
004

And for numbers:

>>> n = 4
>>> print(f'{n:03}') # Preferred method, python >= 3.6
004
>>> print('%03d' % n)
004
>>> print(format(n, '03')) # python >= 2.6
004
>>> print('{0:03d}'.format(n))  # python >= 2.6 + python 3
004
>>> print('{foo:03d}'.format(foo=n))  # python >= 2.6 + python 3
004
>>> print('{:03d}'.format(n))  # python >= 2.7 + python3
004

String formatting documentation.

Java Minimum and Maximum values in Array

Imho one of the simplest Solutions is: -

//MIN NUMBER
Collections.sort(listOfNumbers);
listOfNumbers.get(0);

//MAX NUMBER
Collections.sort(listOfNumbers);
Collections.reverse(listOfNumbers);
listOfNumbers.get(0);

Can I use complex HTML with Twitter Bootstrap's Tooltip?

This parameter is just about whether you are going to use complex html into the tooltip. Set it to true and then hit the html into the title attribute of the tag.

See this fiddle here - I've set the html attribute to true through the data-html="true" in the <a> tag and then just added in the html ad hoc as an example.

How to style an asp.net menu with CSS

I ran into the issue where the class of 'selected' wasn't being added to my menu item. Turns out that you can't have a NavigateUrl on it for whatever reason.

Once I removed the NavigateUrl it applied the 'selected' css class to the a tag and I was able to apply the background style with:

div.menu ul li a.static.selected
{
    background-color: #bfcbd6 !important;
    color: #465c71 !important;
    text-decoration: none !important;
}

SQL Server query to find all permissions/access for all users in a database

Can't comment on accepted answer so I'll add some comments here:

  • I second Brad on schemas issue. From MS reference sys.objects table contains only schema-scoped objects. So to get info about "higher level" objects (i.e. schemas in our case) you need to use sys.schemas table.
  • For [ObjectType] it's better to use obj.type_desc only for OBJECT_OR_COLUMN permission class. For all other cases use perm.[class_desc]
  • Another type of permission which is not handled so well with this query is IMPERSONATE. To get info about impersonations one should LEFT JOIN with sys.database_principals on perm.major_id = imp.principal_id
  • With my experience it's better to replace sys.login_token with sys.server_principals as it will show also SQL Logins, not only Windows ones
  • One should add 'G' to allowed principal types to allow Windows groups
  • Also, one can exclude users sys and INFORMATION_SCHEMA from resulting table, as these users are used only for service

I'll post first piece of script with all proposed fixes, other parts should be changed as well:

SELECT  
    [UserName] = ulogin.[name],
    [UserType] = CASE princ.[type]
                    WHEN 'S' THEN 'SQL User'
                    WHEN 'U' THEN 'Windows User'
                    WHEN 'G' THEN 'Windows Group'
                 END,  
    [DatabaseUserName] = princ.[name],       
    [Role] = null,      
    [PermissionType] = perm.[permission_name],       
    [PermissionState] = perm.[state_desc],       
    [ObjectType] = CASE perm.[class] 
                        WHEN 1 THEN obj.type_desc               -- Schema-contained objects
                        ELSE perm.[class_desc]                  -- Higher-level objects
                   END,       
    [ObjectName] = CASE perm.[class] 
                        WHEN 1 THEN OBJECT_NAME(perm.major_id)  -- General objects
                        WHEN 3 THEN schem.[name]                -- Schemas
                        WHEN 4 THEN imp.[name]                  -- Impersonations
                   END,
    [ColumnName] = col.[name]
FROM    
    --database user
    sys.database_principals princ  
LEFT JOIN
    --Login accounts
    sys.server_principals ulogin on princ.[sid] = ulogin.[sid]
LEFT JOIN        
    --Permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = princ.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col ON col.[object_id] = perm.major_id 
                    AND col.[column_id] = perm.[minor_id]
LEFT JOIN
    sys.objects obj ON perm.[major_id] = obj.[object_id]
LEFT JOIN
    sys.schemas schem ON schem.[schema_id] = perm.[major_id]
LEFT JOIN
    sys.database_principals imp ON imp.[principal_id] = perm.[major_id]
WHERE 
    princ.[type] IN ('S','U','G') AND
    -- No need for these system accounts
    princ.[name] NOT IN ('sys', 'INFORMATION_SCHEMA')

How can I show/hide a specific alert with twitter bootstrap?

I had this problem today, was in a lot of time crunch, so below idea worked:

  • setTimeout with 1 sec -- call a function that shows the div
  • setTimeout with 10 sec -- call a function that hides the div

Fade is not there, but that bootstrap feeling will be there.

Hope that helps.

How to expand/collapse a diff sections in Vimdiff?

ctrl + w, w as mentioned can be used for navigating from pane to pane.

Now you can select a particular change alone and paste it to the other pane as follows.Here I am giving an eg as if I wanted to change my piece of code from pane 1 to pane 2 and currently my cursor is in pane1

  • Use Shift-v to highlight a line and use up or down keys to select the piece of code you require and continue from step 3 written below to paste your changes in the other pane.

  • Use visual mode and then change it

    1 click 'v' this will take you to visual mode 2 use up or down key to select your required code 3 click on ,Esc' escape key 4 Now use 'yy' to copy or 'dd' to cut the change 5 do 'ctrl + w, w' to navigate to pane2 6 click 'p' to paste your change where you require

How do you properly return multiple values from a Promise?

You can't resolve a promise with multiple properties just like you can't return multiple values from a function. A promise conceptually represents a value over time so while you can represent composite values you can't put multiple values in a promise.

A promise inherently resolves with a single value - this is part of how Q works, how the Promises/A+ spec works and how the abstraction works.

The closest you can get is use Q.spread and return arrays or use ES6 destructuring if it's supported or you're willing to use a transpilation tool like BabelJS.

As for passing context down a promise chain please refer to Bergi's excellent canonical on that.

PHP - check if variable is undefined

JavaScript's 'strict not equal' operator (!==) on comparison with undefined does not result in false on null values.

var createTouch = null;
isTouch = createTouch !== undefined  // true

To achieve an equivalent behaviour in PHP, you can check whether the variable name exists in the keys of the result of get_defined_vars().

// just to simplify output format
const BR = '<br>' . PHP_EOL;

// set a global variable to test independence in local scope
$test = 1;

// test in local scope (what is working in global scope as well)
function test()
{
  // is global variable found?
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test does not exist.

  // is local variable found?
  $test = null;
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test exists.

  // try same non-null variable value as globally defined as well
  $test = 1;
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test exists.

  // repeat test after variable is unset
  unset($test);
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.') . BR;
  // $test does not exist.
}

test();

In most cases, isset($variable) is appropriate. That is aquivalent to array_key_exists('variable', get_defined_vars()) && null !== $variable. If you just use null !== $variable without prechecking for existence, you will mess up your logs with warnings because that is an attempt to read the value of an undefined variable.

However, you can apply an undefined variable to a reference without any warning:

// write our own isset() function
function my_isset(&$var)
{
  // here $var is defined
  // and initialized to null if the given argument was not defined
  return null === $var;
}

// passing an undefined variable by reference does not log any warning
$is_set = my_isset($undefined_variable);   // $is_set is false

isset() and empty() - what to use

Here are the outputs of isset() and empty() for the 4 possibilities: undeclared, null, false and true.

$a=null;
$b=false;
$c=true;

var_dump(array(isset($z1),isset($a),isset($b),isset($c)),true); //$z1 previously undeclared
var_dump(array(empty($z2),empty($a),empty($b),empty($c)),true); //$z2 previously undeclared

//array(4) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(true) [3]=> bool(true) } 
//array(4) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) } 

You'll notice that all the 'isset' results are opposite of the 'empty' results except for case $b=false. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for by isset and false when tested by 'empty'.

So use isset() when you're concerned about the existence of a variable. And use empty when you're testing for true or false. If the actual type of emptiness matters, use is_null and ===0, ===false, ===''.

Print all day-dates between two dates

I came up with this:

from datetime import date, timedelta

sdate = date(2008, 8, 15)   # start date
edate = date(2008, 9, 15)   # end date

delta = edate - sdate       # as timedelta

for i in range(delta.days + 1):
    day = sdate + timedelta(days=i)
    print(day)

The output:

2008-08-15
2008-08-16
...
2008-09-13
2008-09-14
2008-09-15

Your question asks for dates in-between but I believe you meant including the start and end points, so they are included. To remove the end date, delete the "+ 1" at the end of the range function. To remove the start date, insert a 1 argument to the beginning of the range function.

Array initialization in Perl

To produce the output in your comment to your post, this will do it:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @array;
my %uniqs;

$uniqs{$_}++ for @other_array;

foreach (keys %uniqs) { $array[$_]=$uniqs{$_} }

print "array[$_] = $array[$_]\n" for (0..$#array);

Output:

   array[0] = 3
   array[1] = 1
   array[2] = 2
   array[3] = 3
   array[4] = 1

This is different than your stated algorithm of producing a parallel array with zero values, but it is a more Perly way of doing it...

If you must have a parallel array that is the same size as your first array with the elements initialized to 0, this statement will dynamically do it: @array=(0) x scalar(@other_array); but really, you don't need to do that.

The entity type <type> is not part of the model for the current context

if you are trying DB first then be sure that your table has primary key

Difference between Node object and Element object?

Node : http://www.w3schools.com/js/js_htmldom_nodes.asp

The Node object represents a single node in the document tree. A node can be an element node, an attribute node, a text node, or any other of the node types explained in the Node Types chapter.

Element : http://www.w3schools.com/js/js_htmldom_elements.asp

The Element object represents an element in an XML document. Elements may contain attributes, other elements, or text. If an element contains text, the text is represented in a text-node.

duplicate :

Connection timeout for SQL server

Yes, you could append ;Connection Timeout=30 to your connection string and specify the value you wish.

The timeout value set in the Connection Timeout property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).

Moreover, setting the timeout value to 0, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:

A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.

How do I tidy up an HTML file's indentation in VI?

None of the answers worked for me because all my HTML was in a single line.

Basically you need first to break each line with the following command that substitutes >< with the same characters but with a line break in the middle.

:%s/></>\r</g

Then the command

gg=G

will indent the file.

SQL permissions for roles

USE DataBaseName; GO --------- CREATE ROLE --------- CREATE ROLE Doctors ; GO  ---- Assign Role To users -------  CREATE USER [Username] FOR LOGIN [Domain\Username] EXEC sp_addrolemember N'Doctors', N'Username'  ----- GRANT Permission to Users Assinged with this Role----- GRANT ALL ON Table1, Table2, Table3 TO Doctors; GO 

How do I change the default library path for R packages

After a couple of hours of trying to solve the issue in several ways, some of which are described here, for me (on Win 10) the option of creating a Renviron file worked, but a little different from what was written here above. The task is to change the value of the variable R_LIBS_USER. To do this two steps needed:

  1. Create the file named Renviron (without dot) in the folder \Program\etc\ (Programm is the directory where the R installed, for example for me it was c:\Program Files\R\R-4.0.0\etc)
  2. Insert a line in Renviron with new path: R_LIBS_USER=c:/R/Library

It's been working for a few days already.

Dynamic Height Issue for UITableView Cells (Swift)

Swift 5 Enjoy

tablev.rowHeight = 100
tablev.estimatedRowHeight = UITableView.automaticDimension


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = self.tablev.dequeueReusableCell(withIdentifier: "ConferenceRoomsCell") as! ConferenceRoomsCell
    cell.lblRoomName.numberOfLines = 0
    cell.lblRoomName.lineBreakMode = .byWordWrapping
    cell.lblRoomName.text = arrNameOfRooms[indexPath.row]
    cell.lblRoomName.sizeToFit()
    return cell
}

How to do "If Clicked Else .."

 var flag = 0;

 $('#target').click(function() {
    flag = 1;
 });

 if (flag == 1)
 {
  alert("Clicked");
 }
 else
 {
   alert("Not clicked");
 }

Pass variables to Ruby script via command line

You can also try out cliqr. Its pretty new and in active development. But there are stable releases ready to be used. Here is the git repo: https://github.com/anshulverma/cliqr

Look into the example folder to get an idea on how it can be used.

How to check if a file exists from a url

Hi according to our test between 2 different servers the results are as follows:

using curl for checking 10 .png files (each about 5 mb) was on average 5.7 secs. using header check for the same thing took average of 7.8 seconds!

So in our test curl was much faster if you have to check larger files!

our curl function is:

function remote_file_exists($url){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if( $httpCode == 200 ){return true;}
    return false;
}

here is our header check sample:

function UR_exists($url){
   $headers=get_headers($url);
   return stripos($headers[0],"200 OK")?true:false;
}

rsync: difference between --size-only and --ignore-times

The short answer is that --ignore-times does more than its name implies. It ignores both the time and size. In contrast, --size-only does exactly what it says.


The long answer is that rsync has three ways to decide if a file is outdated:

  1. Compare the size of source and destination.
  2. Compare the timestamp of source and destination.
  3. Compare the static checksum of source and destination.

These checks are performed before transferring data. Notably, this means the static checksum is distinct from the stream checksum - the later is computed while transferring data.

By default, rsync uses only 1 and 2. Both 1 and 2 can be acquired together by a single stat, whereas 3 requires reading the entire file (this is independent from reading the file for transfer). Assuming only one modifier is specified, that means the following:

  • By using --size-only, only 1 is performed - timestamps and checksum are ignored. A file is copied unless its size is identical on both ends.

  • By using --ignore-times, neither of 1, 2 or 3 is performed. A file is always copied.

  • By using --checksum, 3 is used in addition to 1, but 2 is not performed. A file is copied unless size and checksum match. The checksum is only computed if size matches.

How to get file's last modified date on Windows command line?

Change % to %% for use in batch file, for %~ta syntax enter call /?

for %a in (MyFile.txt) do set FileDate=%~ta

Sample output:

for %a in (MyFile.txt) do set FileDate=%~ta
set FileDate=05/05/2020 09:47 AM

for %a in (file_not_exist_file.txt) do set FileDate=%~ta
set FileDate=

Is using 'var' to declare variables optional?

Nope, they are not equivalent.

With myObj = 1; you are using a global variable.

The latter declaration create a variable local to the scope you are using.

Try the following code to understand the differences:

external = 5;
function firsttry() {
  var external = 6;
  alert("first Try: " + external);
}

function secondtry() {
  external = 7;
  alert("second Try: " + external);
}

alert(external); // Prints 5
firsttry(); // Prints 6
alert(external); // Prints 5
secondtry(); // Prints 7
alert(external); // Prints 7

The second function alters the value of the global variable "external", but the first function doesn't.

git push vs git push origin <branchname>

First, you need to create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Your Teammates/colleagues can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch 

How do I generate a stream from a string?

We use the extension methods listed below. I think you should make the developer make a decision about the encoding, so there is less magic involved.

public static class StringExtensions {

    public static Stream ToStream(this string s) {
        return s.ToStream(Encoding.UTF8);
    }

    public static Stream ToStream(this string s, Encoding encoding) {
        return new MemoryStream(encoding.GetBytes(s ?? ""));
    }
}

jquery loop on Json data using $.each

Have you converted your data from string to JavaScript object?

You can do it with data = eval('(' + string_data + ')'); or, which is safer, data = JSON.parse(string_data); but later will only works in FF 3.5 or if you include json2.js

jQuery since 1.4.1 also have function for that, $.parseJSON().

But actually, $.getJSON() should give you already parsed json object, so you should just check everything thoroughly, there is little mistake buried somewhere, like you might have forgotten to quote something in json, or one of the brackets is missing.

Best way to store data locally in .NET (C#)

My first inclination is an access database. The .mdb files are stored locally, and can be encrypted if that is deemed necessary. Though XML or JSON would also work for many scenarios. Flat files I would only use for read only, non-search (forward read only) information. I tend to prefer csv format to set width.

How to modify WooCommerce cart, checkout pages (main theme portion)

You can use function: wc_get_page_id( 'cart' ) to get the ID of the page. This function will use the page setup as 'cart' page and not the slug. Meaning it will keep working also when you setup a different url for your 'cart' on the settings page. This works for all kind of Woocommerce special page, like 'checkout', 'shop' etc.

example:

if (wc_get_page_id( 'cart' ) == get_the_ID()) {
  // Do something.
}

How can I include css files using node, express, and ejs?

The custom style sheets that we have are static pages in our local file system. In order for server to serve static files, we have to use,

app.use(express.static("public"));

where,

public is a folder we have to create inside our root directory and it must have other folders like css, images.. etc

The directory structure would look like :

enter image description here

Then in your html file, refer to the style.css as

<link type="text/css" href="css/styles.css" rel="stylesheet">

JavaFX - create custom button with image

You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.

public class ImageButton extends Parent {

    private static final Image NORMAL_IMAGE = ...;
    private static final Image PRESSED_IMAGE = ...;

    private final ImageView iv;

    public ImageButton() {
        this.iv = new ImageView(NORMAL_IMAGE);
        this.getChildren().add(this.iv);

        this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {

            public void handle(MouseEvent evt) {
                iv.setImage(PRESSED_IMAGE);
            }

        });

        // TODO other event handlers like mouse up

    } 

}

What does -> mean in C++?

The -> operator, which is applied exclusively to pointers, is needed to obtain the specified field or method of the object referenced by the pointer. (this applies also to structs just for their fields)

If you have a variable ptr declared as a pointer you can think of it as (*ptr).field.

A side node that I add just to make pedantic people happy: AS ALMOST EVERY OPERATOR you can define a different semantic of the operator by overloading it for your classes.

How to search JSON tree with jQuery

Once you have the JSON loaded into a JavaScript object, it's no longer a jQuery problem but is now a JavaScript problem. In JavaScript you could for instance write a search such as:

var people = myJson["people"];
var persons = people["person"];
for(var i=0; i < persons.length; ++i) {
    var person_i = persons[i];
    if(person_i["name"] == mySearchForName) {
        // found ! do something with 'person_i'.
        break;
    }
}
// not found !

Using subprocess to run Python script on Windows

How about this:

import sys
import subprocess

theproc = subprocess.Popen("myscript.py", shell = True)
theproc.communicate()                   # ^^^^^^^^^^^^

This tells subprocess to use the OS shell to open your script, and works on anything that you can just run in cmd.exe.

Additionally, this will search the PATH for "myscript.py" - which could be desirable.

Where is GACUTIL for .net Framework 4.0 in windows 7?

If you've got VS2010 installed, you ought to find a .NET 4.0 gacutil at

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools

The 7.0A Windows SDK should have been installed alongside VS2010 - 6.0A will have been installed with VS2008, and hence won't have .NET 4.0 support.

Best practices for copying files with Maven

The ant solution above is easiest to configure, but I have had luck using the maven-upload-plugin from Atlassian. I was unable to find good documentation, here is how I use it:

<build>
  <plugin>
    <groupId>com.atlassian.maven.plugins</groupId>
    <artifactId>maven-upload-plugin</artifactId>
    <version>1.1</version>
    <configuration>
       <resourceSrc>
             ${project.build.directory}/${project.build.finalName}.${project.packaging}
       </resourceSrc>
       <resourceDest>${jboss.deployDir}</resourceDest>
       <serverId>${jboss.host}</serverId>
       <url>${jboss.deployUrl}</url>
     </configuration>
  </plugin>
</build>

The variables like "${jboss.host}" referenced above are defined in my ~/.m2/settings.xml and are activated using maven profiles. This solution is not constrained to JBoss, this is just what I named my variables. I have a profile for dev, test, and live. So to upload my ear to a jboss instance in test environment I would execute:

mvn upload:upload -P test

Here is a snipet from settings.xml:

<server>
  <id>localhost</id>
  <username>username</username>
  <password>{Pz+6YRsDJ8dUJD7XE8=} an encrypted password. Supported since maven 2.1</password>
</server>
...
<profiles>
  <profile>
    <id>dev</id>
    <properties>
      <jboss.host>localhost</jboss.host> 
      <jboss.deployDir>/opt/jboss/server/default/deploy/</jboss.deployDir>
      <jboss.deployUrl>scp://root@localhost</jboss.deployUrl>
    </properties>
  </profile>
  <profile>
    <id>test</id>
    <properties>
       <jboss.host>testserver</jboss.host>
       ...

Notes: The Atlassian maven repo that has this plugin is here: https://maven.atlassian.com/public/

I recommend downloading the sources and looking at the documentation inside to see all the features the plugin provides.

`

PHP convert string to hex and hex to string

Using @bill-shirley answer with a little addition

function str_to_hex($string) {
$hexstr = unpack('H*', $string);
return array_shift($hexstr);
}
function hex_to_str($string) {
return hex2bin("$string");
}

Usage:

  $str = "Go placidly amidst the noise";
  $hexstr = str_to_hex($str);// 476f20706c616369646c7920616d6964737420746865206e6f697365
  $strstr = hex_to_str($str);// Go placidly amidst the noise

Add up a column of numbers at the Unix shell

TMTWWTDI: Perl has a file size operator (-s)

perl -lne '$t+=-s;END{print $t}' files.txt

Run Button is Disabled in Android Studio

I'm using Linux where I had a symlink in my home folder pointing to a folder containing the Android Studio projects. Loading a project using the symlink failed, loading a project from the folder where the symlink is pointing to worked!

CURL alternative in Python

Here's a simple example using urllib2 that does a basic authentication against GitHub's API.

import urllib2

u='username'
p='userpass'
url='https://api.github.com/users/username'

# simple wrapper function to encode the username & pass
def encodeUserData(user, password):
    return "Basic " + (user + ":" + password).encode("base64").rstrip()

# create the request object and set some headers
req = urllib2.Request(url)
req.add_header('Accept', 'application/json')
req.add_header("Content-type", "application/x-www-form-urlencoded")
req.add_header('Authorization', encodeUserData(u, p))
# make the request and print the results
res = urllib2.urlopen(req)
print res.read()

Furthermore if you wrap this in a script and run it from a terminal you can pipe the response string to 'mjson.tool' to enable pretty printing.

>> basicAuth.py | python -mjson.tool

One last thing to note, urllib2 only supports GET & POST requests.
If you need to use other HTTP verbs like DELETE, PUT, etc you'll probably want to take a look at PYCURL

Creating a timer in python

import time
def timer():
   now = time.localtime(time.time())
   return now[5]


run = raw_input("Start? > ")
while run == "start":
   minutes = 0
   current_sec = timer()
   #print current_sec
   if current_sec == 59:
      mins = minutes + 1
      print ">>>>>>>>>>>>>>>>>>>>>", mins

I was actually looking for a timer myself and your code seems to work, the probable reason for your minutes not being counted is that when you say that

minutes = 0

and then

mins = minutes + 1

it is the same as saying

mins = 0 + 1

I'm betting that every time you print mins it shows you "1" because of what i just explained, "0+1" will always result in "1".

What you have to do first is place your

minutes = 0

declaration outside of your while loop. After that you can delete the

mins = minutes + 1

line because you don't really need another variable in this case, just replace it with

minutes = minutes + 1

That way minutes will start off with a value of "0", receive the new value of "0+1", receive the new value of "1+1", receive the new value of "2+1", etc.

I realize that a lot of people answered it already but i thought it would help out more, learning wise, if you could see where you made a mistake and try to fix it.Hope it helped. Also, thanks for the timer.

mysql update multiple columns with same now()

If you really need to be sure that now() has the same value you can run two queries (that will answer to your second question too, in that case you are asking to update last_monitor = to last_update but last_update hasn't been updated yet)

you could do something like:

mysql> update table set last_update=now() where id=1;
mysql> update table set last_monitor = last_update where id=1;

anyway I think that mysql is clever enough to ask for now() only once per query.

Get source jar files attached to Eclipse for Maven-managed dependencies

Changing pom for maven-eclipse-plugin to include source/javadoc just apply for new dependencies being added to pom. If we need to apply for existing dependencies, we must run mvn dependency:sources. I checked this.

How to generate auto increment field in select query

DECLARE @id INT 
SET @id = 0 
UPDATE cartemp
SET @id = CarmasterID = @id + 1 
GO

Cannot connect to the Docker daemon on macOS

I had docker up to date, docker said it was running, and the diagnosis was good. I needed to unset some legacy environment variable (thanks https://docs.docker.com/docker-for-mac/troubleshoot/#workarounds-for-common-problems )

unset DOCKER_HOST
unset DOCKER_CERT_PATH
unset DOCKER_TLS_VERIFY

Represent space and tab in XML tag

If you are talking about the issue where multiple and non-space whitespace characters are stripped specifically from attribute values, then yes, encoding them as character references such as &#9; will fix it.

Replace Fragment inside a ViewPager

I have implemented a solution for:

  • Dynamic fragment replacement inside the tab
  • Maintenance of the history per tab
  • Working with orientation changes

The tricks to achieve this are the following:

  • Use the notifyDataSetChanged() method to apply the fragment replacement
  • Use the fragment manager only for back stage and no for fragament replacement
  • Maintain the history using the memento pattern (stack)

The adapter code is the following:

public class TabsAdapter extends FragmentStatePagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener {

/** The sherlock fragment activity. */
private final SherlockFragmentActivity mActivity;

/** The action bar. */
private final ActionBar mActionBar;

/** The pager. */
private final ViewPager mPager;

/** The tabs. */
private List<TabInfo> mTabs = new LinkedList<TabInfo>();

/** The total number of tabs. */
private int TOTAL_TABS;

private Map<Integer, Stack<TabInfo>> history = new HashMap<Integer, Stack<TabInfo>>();

/**
 * Creates a new instance.
 *
 * @param activity the activity
 * @param pager    the pager
 */
public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
    super(activity.getSupportFragmentManager());
    activity.getSupportFragmentManager();
    this.mActivity = activity;
    this.mActionBar = activity.getSupportActionBar();
    this.mPager = pager;
    mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}

/**
 * Adds the tab.
 *
 * @param image         the image
 * @param fragmentClass the class
 * @param args          the arguments
 */
public void addTab(final Drawable image, final Class fragmentClass, final Bundle args) {
    final TabInfo tabInfo = new TabInfo(fragmentClass, args);
    final ActionBar.Tab tab = mActionBar.newTab();
    tab.setTabListener(this);
    tab.setTag(tabInfo);
    tab.setIcon(image);

    mTabs.add(tabInfo);
    mActionBar.addTab(tab);

    notifyDataSetChanged();
}

@Override
public Fragment getItem(final int position) {
    final TabInfo tabInfo = mTabs.get(position);
    return Fragment.instantiate(mActivity, tabInfo.fragmentClass.getName(), tabInfo.args);
}

@Override
public int getItemPosition(final Object object) {
    /* Get the current position. */
    int position = mActionBar.getSelectedTab().getPosition();

    /* The default value. */
    int pos = POSITION_NONE;
    if (history.get(position).isEmpty()) {
        return POSITION_NONE;
    }

    /* Checks if the object exists in current history. */
    for (Stack<TabInfo> stack : history.values()) {
        TabInfo c = stack.peek();
        if (c.fragmentClass.getName().equals(object.getClass().getName())) {
            pos = POSITION_UNCHANGED;
            break;
        }
    }
    return pos;
}

@Override
public int getCount() {
    return mTabs.size();
}

@Override
public void onPageScrollStateChanged(int arg0) {
}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}

@Override
public void onPageSelected(int position) {
    mActionBar.setSelectedNavigationItem(position);
}

@Override
public void onTabSelected(final ActionBar.Tab tab, final FragmentTransaction ft) {
    TabInfo tabInfo = (TabInfo) tab.getTag();
    for (int i = 0; i < mTabs.size(); i++) {
        if (mTabs.get(i).equals(tabInfo)) {
            mPager.setCurrentItem(i);
        }
    }
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}

public void replace(final int position, final Class fragmentClass, final Bundle args) {
    /* Save the fragment to the history. */
    mActivity.getSupportFragmentManager().beginTransaction().addToBackStack(null).commit();

    /* Update the tabs. */
    updateTabs(new TabInfo(fragmentClass, args), position);

    /* Updates the history. */
    history.get(position).push(new TabInfo(mTabs.get(position).fragmentClass, mTabs.get(position).args));

    notifyDataSetChanged();
}

/**
 * Updates the tabs.
 *
 * @param tabInfo
 *          the new tab info
 * @param position
 *          the position
 */
private void updateTabs(final TabInfo tabInfo, final int position) {
    mTabs.remove(position);
    mTabs.add(position, tabInfo);
    mActionBar.getTabAt(position).setTag(tabInfo);
}

/**
 * Creates the history using the current state.
 */
public void createHistory() {
    int position = 0;
    TOTAL_TABS = mTabs.size();
    for (TabInfo mTab : mTabs) {
        if (history.get(position) == null) {
            history.put(position, new Stack<TabInfo>());
        }
        history.get(position).push(new TabInfo(mTab.fragmentClass, mTab.args));
        position++;
    }
}

/**
 * Called on back
 */
public void back() {
    int position = mActionBar.getSelectedTab().getPosition();
    if (!historyIsEmpty(position)) {
        /* In case there is not any other item in the history, then finalize the activity. */
        if (isLastItemInHistory(position)) {
            mActivity.finish();
        }
        final TabInfo currentTabInfo = getPrevious(position);
        mTabs.clear();
        for (int i = 0; i < TOTAL_TABS; i++) {
            if (i == position) {
                mTabs.add(new TabInfo(currentTabInfo.fragmentClass, currentTabInfo.args));
            } else {
                TabInfo otherTabInfo = history.get(i).peek();
                mTabs.add(new TabInfo(otherTabInfo.fragmentClass, otherTabInfo.args));
            }
        }
    }
    mActionBar.selectTab(mActionBar.getTabAt(position));
    notifyDataSetChanged();
}

/**
 * Returns if the history is empty.
 *
 * @param position
 *          the position
 * @return  the flag if empty
 */
private boolean historyIsEmpty(final int position) {
    return history == null || history.isEmpty() || history.get(position).isEmpty();
}

private boolean isLastItemInHistory(final int position) {
    return history.get(position).size() == 1;
}

/**
 * Returns the previous state by the position provided.
 *
 * @param position
 *          the position
 * @return  the tab info
 */
private TabInfo getPrevious(final int position) {
    TabInfo currentTabInfo = history.get(position).pop();
    if (!history.get(position).isEmpty()) {
        currentTabInfo = history.get(position).peek();
    }
    return currentTabInfo;
}

/** The tab info class */
private static class TabInfo {

    /** The fragment class. */
    public Class fragmentClass;

    /** The args.*/
    public Bundle args;

    /**
     * Creates a new instance.
     *
     * @param fragmentClass
     *          the fragment class
     * @param args
     *          the args
     */
    public TabInfo(Class fragmentClass, Bundle args) {
        this.fragmentClass = fragmentClass;
        this.args = args;
    }

    @Override
    public boolean equals(final Object o) {
        return this.fragmentClass.getName().equals(o.getClass().getName());
    }

    @Override
    public int hashCode() {
        return fragmentClass.getName() != null ? fragmentClass.getName().hashCode() : 0;
    }

    @Override
    public String toString() {
        return "TabInfo{" +
                "fragmentClass=" + fragmentClass +
                '}';
    }
}

The very first time you add all tabs, we need to call the method createHistory(), to create the initial history

public void createHistory() {
    int position = 0;
    TOTAL_TABS = mTabs.size();
    for (TabInfo mTab : mTabs) {
        if (history.get(position) == null) {
            history.put(position, new Stack<TabInfo>());
        }
        history.get(position).push(new TabInfo(mTab.fragmentClass, mTab.args));
        position++;
    }
}

Every time you want to replace a fragment to a specific tab you call: replace(final int position, final Class fragmentClass, final Bundle args)

/* Save the fragment to the history. */
    mActivity.getSupportFragmentManager().beginTransaction().addToBackStack(null).commit();

    /* Update the tabs. */
    updateTabs(new TabInfo(fragmentClass, args), position);

    /* Updates the history. */
    history.get(position).push(new TabInfo(mTabs.get(position).fragmentClass, mTabs.get(position).args));

    notifyDataSetChanged();

On back pressed you need to call the back() method:

public void back() {
    int position = mActionBar.getSelectedTab().getPosition();
    if (!historyIsEmpty(position)) {
        /* In case there is not any other item in the history, then finalize the activity. */
        if (isLastItemInHistory(position)) {
            mActivity.finish();
        }
        final TabInfo currentTabInfo = getPrevious(position);
        mTabs.clear();
        for (int i = 0; i < TOTAL_TABS; i++) {
            if (i == position) {
                mTabs.add(new TabInfo(currentTabInfo.fragmentClass, currentTabInfo.args));
            } else {
                TabInfo otherTabInfo = history.get(i).peek();
                mTabs.add(new TabInfo(otherTabInfo.fragmentClass, otherTabInfo.args));
            }
        }
    }
    mActionBar.selectTab(mActionBar.getTabAt(position));
    notifyDataSetChanged();
}

The solution works with sherlock action bar and with swipe gesture.

Handle Guzzle exception and get HTTP body

Guzzle 3.x

Per the docs, you can catch the appropriate exception type (ClientErrorResponseException for 4xx errors) and call its getResponse() method to get the response object, then call getBody() on that:

use Guzzle\Http\Exception\ClientErrorResponseException;

...

try {
    $response = $request->send();
} catch (ClientErrorResponseException $exception) {
    $responseBody = $exception->getResponse()->getBody(true);
}

Passing true to the getBody function indicates that you want to get the response body as a string. Otherwise you will get it as instance of class Guzzle\Http\EntityBody.

Transpose list of lists

Here is a solution for transposing a list of lists that is not necessarily square:

maxCol = len(l[0])
for row in l:
    rowLength = len(row)
    if rowLength > maxCol:
        maxCol = rowLength
lTrans = []
for colIndex in range(maxCol):
    lTrans.append([])
    for row in l:
        if colIndex < len(row):
            lTrans[colIndex].append(row[colIndex])

Transfer data between databases with PostgreSQL

I just had to do this exact thing so I figured I'd post the recipe here. This assumes that both databases are on the same server.

First, copy the table from the old db to the new db (because apparently you can't move data between databases). At the commandline:

pg_dump -U postgres -t <old_table> <old_database> | psql -U postgres -d <new_database>

# Just adding extra space here so scrollbar doesn't hide the command

Next, grant permissions of the copied table to the user of the new database. Log into psql:

psql -U postgres -d <new_database>

ALTER TABLE <old_table> OWNER TO <new_user>;

\q

Finally, copy data from the old table to the new table. Log in as the new user and then:

INSERT INTO <new_table> (field1, field2, field3) 
SELECT field1, field2, field3 from <old_table>;

Done!

How to figure out the SMTP server host?

To automate the answer of @Jordan S. Jones at WIN/DOS command-line,

Put this in a batch file named: getmns.bat (get mail name server):

@echo off
if @%1==@ goto USAGE
echo set type=MX>mnscmd.txt
echo %1>>mnscmd.txt
echo exit>>mnscmd.txt
nslookup<mnscmd.txt>mnsresult.txt
type mnsresult.txt
del mnsresult.txt
goto END
:USAGE
echo usage:
echo %0 domainname.ext
:END
echo.

For example:

getmns google.com

output:

google.com      MX preference = 20, mail exchanger = alt1.aspmx.l.google.com
google.com      MX preference = 10, mail exchanger = aspmx.l.google.com
google.com      MX preference = 50, mail exchanger = alt4.aspmx.l.google.com
google.com      MX preference = 40, mail exchanger = alt3.aspmx.l.google.com
google.com      MX preference = 30, mail exchanger = alt2.aspmx.l.google.com

alt4.aspmx.l.google.com internet address = 74.125.25.27
alt3.aspmx.l.google.com internet address = 173.194.72.27
aspmx.l.google.com      internet address = 173.194.65.27
alt1.aspmx.l.google.com internet address = 74.125.200.27
alt2.aspmx.l.google.com internet address = 64.233.187.27

For example to pipe the result again into a file do:

getmns google.com > google.mns.txt

:-D

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

Official way to ask jQuery wait for all images to load before executing something

With jQuery i come with this...

$(function() {
    var $img = $('img'),
        totalImg = $img.length;

    var waitImgDone = function() {
        totalImg--;
        if (!totalImg) alert("Images loaded!");
    };

    $('img').each(function() {
        $(this)
            .load(waitImgDone)
            .error(waitImgDone);
    });
});

Demo : http://jsfiddle.net/molokoloco/NWjDb/

Is it possible to make a Tree View with Angular?

You can use angular-recursion-injector for that: https://github.com/knyga/angular-recursion-injector

Allows you to do unlimited depth nesting with conditioning. Does recompilation only if needed and compiles only right elements. No magic in code.

<div class="node">
  <span>{{name}}</span>

  <node--recursion recursion-if="subNode" ng-model="subNode"></node--recursion>
</div>

One of the things that allows it to work faster and simpler then the other solutions is "--recursion" suffix.

In Rails, how do you render JSON using a view?

This is potentially a better option and faster than ERB: https://github.com/dewski/json_builder

What does Statement.setFetchSize(nSize) method really do in SQL Server JDBC driver?

I had the exact same problem in a project. The issue is that even though the fetch size might be small enough, the JDBCTemplate reads all the result of your query and maps it out in a huge list which might blow your memory. I ended up extending NamedParameterJdbcTemplate to create a function which returns a Stream of Object. That Stream is based on the ResultSet normally returned by JDBC but will pull data from the ResultSet only as the Stream requires it. This will work if you don't keep a reference of all the Object this Stream spits. I did inspire myself a lot on the implementation of org.springframework.jdbc.core.JdbcTemplate#execute(org.springframework.jdbc.core.ConnectionCallback). The only real difference has to do with what to do with the ResultSet. I ended up writing this function to wrap up the ResultSet:

private <T> Stream<T> wrapIntoStream(ResultSet rs, RowMapper<T> mapper) {
    CustomSpliterator<T> spliterator = new CustomSpliterator<T>(rs, mapper, Long.MAX_VALUE, NON-NULL | IMMUTABLE | ORDERED);
    Stream<T> stream = StreamSupport.stream(spliterator, false);
    return stream;
}
private static class CustomSpliterator<T> extends Spliterators.AbstractSpliterator<T> {
    // won't put code for constructor or properties here
    // the idea is to pull for the ResultSet and set into the Stream
    @Override
    public boolean tryAdvance(Consumer<? super T> action) {
        try {
            // you can add some logic to close the stream/Resultset automatically
            if(rs.next()) {
                T mapped = mapper.mapRow(rs, rowNumber++);
                action.accept(mapped);
                return true;
            } else {
                return false;
            }
        } catch (SQLException) {
            // do something with this Exception
        }
    }
}

you can add some logic to make that Stream "auto closable", otherwise don't forget to close it when you are done.

How can I get a Dialog style activity window to fill the screen?

In your manifest file where our activity is defined

<activity
        android:name=".YourPopUpActivity"
        android:theme="@android:style/Theme.Holo.Dialog" >
    </activity>

without action bar

<activity android:name=".YourPopUpActivity"
            android:theme="@android:style/Theme.Holo.Dialog.NoActionBar"/>

What does \0 stand for?

To the C language, '\0' means exactly the same thing as the integer constant 0 (same value zero, same type int).

To someone reading the code, writing '\0' suggests that you're planning to use this particular zero as a character.

How can I determine the type of an HTML element in JavaScript?

nodeName is the attribute you are looking for. For example:

var elt = document.getElementById('foo');
console.log(elt.nodeName);

Note that nodeName returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div> element you could do it as follows:

elt.nodeName == "DIV"

While this would not give you the expected results:

elt.nodeName == "<div>"

In Tensorflow, get the names of all the Tensors in a graph

There is a way to do it slightly faster than in Yaroslav's answer by using get_operations. Here is a quick example:

import tensorflow as tf

a = tf.constant(1.3, name='const_a')
b = tf.Variable(3.1, name='variable_b')
c = tf.add(a, b, name='addition')
d = tf.multiply(c, a, name='multiply')

for op in tf.get_default_graph().get_operations():
    print(str(op.name))