Programs & Examples On #Qt4

Questions specifically relating to the deprecated version 4.x.x of the Qt C++ GUI library. If your question applies to the current major version of Qt, use the tag [qt].

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

The Qt documentations has an Image Viewer example which demonstrates handling resizing images inside a QLabel. The basic idea is to use QScrollArea as a container for the QLabel and if needed use label.setScaledContents(bool) and scrollarea.setWidgetResizable(bool) to fill available space and/or ensure QLabel inside is resizable. Additionally, to resize QLabel while honoring aspect ratio use:

label.setPixmap(pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::FastTransformation));

The width and height can be set based on scrollarea.width() and scrollarea.height(). In this way there is no need to subclass QLabel.

QLabel: set color of text and background

The best way to set any feature regarding the colors of any widget is to use QPalette.

And the easiest way to find what you are looking for is to open Qt Designer and set the palette of a QLabel and check the generated code.

Console output in a Qt GUI app?

First of all you can try flushing the buffer

std::cout << "Hello, world!"<<std::endl;

For more Qt based logging you can try using qDebug.

How to make a Qt Widget grow with the window size?

I found it was impossible to assign a layout to the centralwidget until I had added at least one child beneath it. Then I could highlight the tiny icon with the red 'disabled' mark and then click on a layout in the Designer toolbar at top.

How to add minutes to current time in swift

In case you want unix timestamp

        let now : Date = Date()
        let currentCalendar : NSCalendar = Calendar.current as NSCalendar

        let nowPlusAddTime : Date = currentCalendar.date(byAdding: .second, value: accessTime, to: now, options: .matchNextTime)!

        let unixTime = nowPlusAddTime.timeIntervalSince1970

Select Tag Helper in ASP.NET Core MVC

You can use below code for multiple select:

<select asp-for="EmployeeId"  multiple="multiple" asp-items="@ViewBag.Employees">
    <option>Please select</option>
</select>

You can also use:

<select id="EmployeeId" name="EmployeeId"  multiple="multiple" asp-items="@ViewBag.Employees">
    <option>Please select</option>
</select>

OnclientClick and OnClick is not working at the same time?

OnClientClick seems to be very picky when used with OnClick.

I tried unsuccessfully with the following use cases:

OnClientClick="return ValidateSearch();" 
OnClientClick="if(ValidateSearch()) return true;"
OnClientClick="ValidateSearch();"

But they did not work. The following worked:

<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" 
  OnClick="keywordSearch_Click" 
  OnClientClick="if (!ValidateSearch()) { return false;};" />

Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

String compare in Perl with "eq" vs "=="

First, eq is for comparing strings; == is for comparing numbers.

Even if the "if" condition is satisfied, it doesn't evaluate the "then" block.

I think your problem is that your variables don't contain what you think they do. I think your $str1 or $str2 contains something like "taste\n" or so. Check them by printing before your if: print "str1='$str1'\n";.

The trailing newline can be removed with the chomp($str1); function.

Instant run in Android Studio 2.0 (how to turn off)

Update August 2019

In Android Studio 3.5 Instant Run was replaced with Apply Changes. And it works in different way: APK is not modified on the fly anymore but instead runtime instrumentation is used to redefine classes on the fly (more info). So since Android Studio 3.5 instant run settings are replaced with Deployment (Settings -> Build, Execution, Deployment -> Deployment):enter image description here

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

You don't need Xvfb

It is failing to start due to a mismatch between the chrome version and the chromedriver version. Downloading and installing the same versions or latest versions would solve the issue.

How do I clone a generic List in Java?

To clone a generic interface like java.util.List you will just need to cast it. here you are an example:

List list = new ArrayList();
List list2 = ((List) ( (ArrayList) list).clone());

It is a bit tricky, but it works, if you are limited to return a List interface, so anyone after you can implement your list whenever he wants.

I know this answer is close to the final answer, but my answer answers how to do all of that while you are working with List -the generic parent- not ArrayList

creating Hashmap from a JSON String

Don't do this yourself, I suggest.
Use a library, e.g. the Gson library from Google.

https://code.google.com/p/google-gson/

Convert Uri to String and String to Uri

You can use Drawable instead of Uri.

   ImageView iv=(ImageView)findViewById(R.id.imageView1);
   String pathName = "/external/images/media/470939"; 
   Drawable image = Drawable.createFromPath(pathName);
   iv.setImageDrawable(image);

This would work.

How do you add an image?

Just to clarify the problem here - the error is in the following bit of code:

<xsl:attribute name="src">
    <xsl:copy-of select="/root/Image/node()"/>
</xsl:attribute>

The instruction xsl:copy-of takes a node or node-set and makes a copy of it - outputting a node or node-set. However an attribute cannot contain a node, only a textual value, so xsl:value-of would be a possible solution (as this returns the textual value of a node or nodeset).

A MUCH shorter solution (and perhaps more elegant) would be the following:

<img width="100" height="100" src="{/root/Image/node()}" class="CalloutRightPhoto"/>

The use of the {} in the attribute is called an Attribute Value Template, and can contain any XPATH expression.

Note, the same XPath can be used here as you have used in the xsl_copy-of as it knows to take the textual value when used in a Attribute Value Template.

Python - How to cut a string in Python?

string = 'http://www.domain.com/?s=some&two=20'
cut_string = string.split('&')
new_string = cut_string[0]
print(new_string)

How do I create dynamic properties in C#?

You might use a dictionary, say

Dictionary<string,object> properties;

I think in most cases where something similar is done, it's done like this.
In any case, you would not gain anything from creating a "real" property with set and get accessors, since it would be created only at run-time and you would not be using it in your code...

Here is an example, showing a possible implementation of filtering and sorting (no error checking):

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1 {

    class ObjectWithProperties {
        Dictionary<string, object> properties = new Dictionary<string,object>();

        public object this[string name] {
            get { 
                if (properties.ContainsKey(name)){
                    return properties[name];
                }
                return null;
            }
            set {
                properties[name] = value;
            }
        }

    }

    class Comparer<T> : IComparer<ObjectWithProperties> where T : IComparable {

        string m_attributeName;

        public Comparer(string attributeName){
            m_attributeName = attributeName;
        }

        public int Compare(ObjectWithProperties x, ObjectWithProperties y) {
            return ((T)x[m_attributeName]).CompareTo((T)y[m_attributeName]);
        }

    }

    class Program {

        static void Main(string[] args) {

            // create some objects and fill a list
            var obj1 = new ObjectWithProperties();
            obj1["test"] = 100;
            var obj2 = new ObjectWithProperties();
            obj2["test"] = 200;
            var obj3 = new ObjectWithProperties();
            obj3["test"] = 150;
            var objects = new List<ObjectWithProperties>(new ObjectWithProperties[]{ obj1, obj2, obj3 });

            // filtering:
            Console.WriteLine("Filtering:");
            var filtered = from obj in objects
                         where (int)obj["test"] >= 150
                         select obj;
            foreach (var obj in filtered){
                Console.WriteLine(obj["test"]);
            }

            // sorting:
            Console.WriteLine("Sorting:");
            Comparer<int> c = new Comparer<int>("test");
            objects.Sort(c);
            foreach (var obj in objects) {
                Console.WriteLine(obj["test"]);
            }
        }

    }
}

Can a shell script set environment variables of the calling shell?

This works — it isn't what I'd use, but it 'works'. Let's create a script teredo to set the environment variable TEREDO_WORMS:

#!/bin/ksh
export TEREDO_WORMS=ukelele
exec $SHELL -i

It will be interpreted by the Korn shell, exports the environment variable, and then replaces itself with a new interactive shell.

Before running this script, we have SHELL set in the environment to the C shell, and the environment variable TEREDO_WORMS is not set:

% env | grep SHELL
SHELL=/bin/csh
% env | grep TEREDO
%

When the script is run, you are in a new shell, another interactive C shell, but the environment variable is set:

% teredo
% env | grep TEREDO
TEREDO_WORMS=ukelele
%

When you exit from this shell, the original shell takes over:

% exit
% env | grep TEREDO
%

The environment variable is not set in the original shell's environment. If you use exec teredo to run the command, then the original interactive shell is replaced by the Korn shell that sets the environment, and then that in turn is replaced by a new interactive C shell:

% exec teredo
% env | grep TEREDO
TEREDO_WORMS=ukelele
%

If you type exit (or Control-D), then your shell exits, probably logging you out of that window, or taking you back to the previous level of shell from where the experiments started.

The same mechanism works for Bash or Korn shell. You may find that the prompt after the exit commands appears in funny places.


Note the discussion in the comments. This is not a solution I would recommend, but it does achieve the stated purpose of a single script to set the environment that works with all shells (that accept the -i option to make an interactive shell). You could also add "$@" after the option to relay any other arguments, which might then make the shell usable as a general 'set environment and execute command' tool. You might want to omit the -i if there are other arguments, leading to:

#!/bin/ksh
export TEREDO_WORMS=ukelele
exec $SHELL "${@-'-i'}"

The "${@-'-i'}" bit means 'if the argument list contains at least one argument, use the original argument list; otherwise, substitute -i for the non-existent arguments'.

Convert a string to a double - is this possible?

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.

$s = '1234.13';
$double = bcadd($s,'0',2);

PHP: bcadd

what are the .map files used for in Bootstrap 3.x?

These are source maps. Provide these alongside compressed source files; developer tools such as those in Firefox and Chrome will use them to allow debugging as if the code was not compressed.

Search a text file and print related lines in Python?

with open('file.txt', 'r') as searchfile:
    for line in searchfile:
        if 'searchphrase' in line:
            print line

With apologies to senderle who I blatantly copied.

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

  1. try to go to Windows services and stop the MySQL service
  2. go to your wamp server and click on "restart all services".
  3. Refrsch your browser

How to declare a type as nullable in TypeScript?

Just add a question mark ? to the optional field.

interface Employee{
   id: number;
   name: string;
   salary?: number;
}

localhost refused to connect Error in visual studio

If found it was because I had been messing about with netsh http add commands to get IIS Express visible remotely.

The symptoms were:

  • the site would fail to connect in a browser
  • the site would fail to start (right click IIS Express in the Taskbar and it was missing)
  • if I ran Visual Studio as admin it would start in IIS Express and be visible in the browser

The solution was to list all bound sites:

netsh http show urlacl

then delete the one I had recently added:

netsh http delete urlacl url=http://*:54321/


In addition I had removed localhost from the hidden solution folder file .vs\config\application.config for the site:

<bindings>
    <binding protocol="http" bindingInformation="*:54321:" />
</bindings>

so had to put that back:

<bindings>
    <binding protocol="http" bindingInformation="*:54321:localhost" />
</bindings>

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

You will have to make an explicit call on the lazy collection in order to initialize it (common practice is to call .size() for this purpose). In Hibernate there is a dedicated method for this (Hibernate.initialize()), but JPA has no equivalent of that. Of course you will have to make sure that the invocation is done, when the session is still available, so annotate your controller method with @Transactional. An alternative is to create an intermediate Service layer between the Controller and the Repository that could expose methods which initialize lazy collections.

Update:

Please note that the above solution is easy, but results in two distinct queries to the database (one for the user, another one for its roles). If you want to achieve better performace add the following method to your Spring Data JPA repository interface:

public interface PersonRepository extends JpaRepository<Person, Long> {

    @Query("SELECT p FROM Person p JOIN FETCH p.roles WHERE p.id = (:id)")
    public Person findByIdAndFetchRolesEagerly(@Param("id") Long id);

}

This method will use JPQL's fetch join clause to eagerly load the roles association in a single round-trip to the database, and will therefore mitigate the performance penalty incurred by the two distinct queries in the above solution.

Copy a file in a sane, safe and efficient way

For those who like boost:

boost::filesystem::path mySourcePath("foo.bar");
boost::filesystem::path myTargetPath("bar.foo");

// Variant 1: Overwrite existing
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::overwrite_if_exists);

// Variant 2: Fail if exists
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::fail_if_exists);

Note that boost::filesystem::path is also available as wpath for Unicode. And that you could also use

using namespace boost::filesystem

if you do not like those long type names

Is there any "font smoothing" in Google Chrome?

Chrome doesn't render the fonts like Firefox or any other browser does. This is generally a problem in Chrome running on Windows only. If you want to make the fonts smooth, use the -webkit-font-smoothing property on yer h4 tags like this.

h4 {
    -webkit-font-smoothing: antialiased;
}

You can also use subpixel-antialiased, this will give you different type of smoothing (making the text a little blurry/shadowed). However, you will need a nightly version to see the effects. You can learn more about font smoothing here.

What do I use on linux to make a python program executable

Just put this in the first line of your script :

#!/usr/bin/env python

Make the file executable with

chmod +x myfile.py

Execute with

./myfile.py

using jquery $.ajax to call a PHP function

I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php

After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.

For ease of use reference the function in a simple manner:

    var P = $.fn.php;

Then initialize the plugin:

P('init', 
{
    // The path to our function request handler is absolutely required
    'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',

    // Synchronous requests are required for method chaining functionality
    'async': false,

    // List any user defined functions in the manner prescribed here
            // There must be user defined functions with these same names in your PHP
    'userFunctions': {

        languageFunctions: 'someFunc1 someFunc2'
    }
});             

And now some usage scenarios:

// Suspend callback mode so we don't work with the DOM
P.callback(false);

// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25

// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]

Demonstrating PHP function chaining:

var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );

Demonstrating sending a JSON block of PHP pseudo-code:

var data1 = 
        P.block({
    $str: "Let's use PHP's file_get_contents()!",
    $opts: 
    [
        {
            http: {
                method: "GET",
                header: "Accept-language: en\r\n" +
                        "Cookie: foo=bar\r\n"
            }
        }
    ],
    $context: 
    {
        stream_context_create: ['$opts']
    },
    $contents: 
    {
        file_get_contents: ['http://www.github.com/', false, '$context']
    },
    $html: 
    {
        htmlentities: ['$contents']
    }
}).data();
    console.log( data1 );

The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.

Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?

In Python 2.x this is not guaranteed as it is possible for True and False to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.

In Python 3.x True and False are keywords and will always be equal to 1 and 0.

Under normal circumstances in Python 2, and always in Python 3:

False object is of type bool which is a subclass of int:

object
   |
 int
   |
 bool

It is the only reason why in your example, ['zero', 'one'][False] does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define a __index__ method (thanks mark-dickinson).

Edit:

It is true of the current python version, and of that of Python 3. The docs for python 2 and the docs for Python 3 both say:

There are two types of integers: [...] Integers (int) [...] Booleans (bool)

and in the boolean subsection:

Booleans: These represent the truth values False and True [...] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

There is also, for Python 2:

In numeric contexts (for example when used as the argument to an arithmetic operator), they [False and True] behave like the integers 0 and 1, respectively.

So booleans are explicitly considered as integers in Python 2 and 3.

So you're safe until Python 4 comes along. ;-)

SQL query, if value is null then return 1

You can use COALESCE:

SELECT  orderhed.ordernum, 
    orderhed.orderdate, 
    currrate.currencycode,  
    coalesce(currrate.currentrate, 1) as currentrate
FROM orderhed 
LEFT OUTER JOIN currrate 
    ON orderhed.company = currrate.company 
    AND orderhed.orderdate = currrate.effectivedate

Or even IsNull():

SELECT  orderhed.ordernum, 
    orderhed.orderdate, 
    currrate.currencycode,  
    IsNull(currrate.currentrate, 1) as currentrate
FROM orderhed 
LEFT OUTER JOIN currrate 
    ON orderhed.company = currrate.company 
    AND orderhed.orderdate = currrate.effectivedate

Here is an article to help decide between COALESCE and IsNull:

http://www.mssqltips.com/sqlservertip/2689/deciding-between-coalesce-and-isnull-in-sql-server/

Read a file one line at a time in node.js?

I have a little module which does this well and is used by quite a few other projects npm readline Note thay in node v10 there is a native readline module so I republished my module as linebyline https://www.npmjs.com/package/linebyline

if you dont want to use the module the function is very simple:

var fs = require('fs'),
EventEmitter = require('events').EventEmitter,
util = require('util'),
newlines = [
  13, // \r
  10  // \n
];
var readLine = module.exports = function(file, opts) {
if (!(this instanceof readLine)) return new readLine(file);

EventEmitter.call(this);
opts = opts || {};
var self = this,
  line = [],
  lineCount = 0,
  emit = function(line, count) {
    self.emit('line', new Buffer(line).toString(), count);
  };
  this.input = fs.createReadStream(file);
  this.input.on('open', function(fd) {
    self.emit('open', fd);
  })
  .on('data', function(data) {
   for (var i = 0; i < data.length; i++) {
    if (0 <= newlines.indexOf(data[i])) { // Newline char was found.
      lineCount++;
      if (line.length) emit(line, lineCount);
      line = []; // Empty buffer.
     } else {
      line.push(data[i]); // Buffer new line data.
     }
   }
 }).on('error', function(err) {
   self.emit('error', err);
 }).on('end', function() {
  // Emit last line if anything left over since EOF won't trigger it.
  if (line.length){
     lineCount++;
     emit(line, lineCount);
  }
  self.emit('end');
 }).on('close', function() {
   self.emit('close');
 });
};
util.inherits(readLine, EventEmitter);

How do I install Python packages on Windows?

As mentioned by Blauhirn after 2.7 pip is preinstalled. If it is not working for you it might need to be added to path.

However if you run Windows 10 you no longer have to open a terminal to install a module. The same goes for opening Python as well.

You can type directly into the search menu pip install mechanize, select command and it will install:

enter image description here

If anything goes wrong however it may close before you can read the error but still it's a useful shortcut.

Git Pull is Not Possible, Unmerged Files

Assuming you want to throw away any changes you have, first check the output of git status. For any file that says "unmerged" next to it, run git add <unmerged file>. Then follow up with git reset --hard. That will git rid of any local changes except for untracked files.

Upgrade Node.js to the latest version on Mac OS

Because this seems to be at the top of Google when searching for how to upgrade nodejs on mac I will offer my tip for anyone coming along in the future despite its age.

Upgrading via NPM
You can use the method described by @Mathias above or choose the following simpler method via the terminal.

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

After which you may opt to confirm the upgrade

node -v

Your nodejs should have upgraded to the latest version. If you wish to upgrade to a specific one say v0.8.19 then instead of

sudo n stable

use

sudo n 0.8.19

EDIT Avoid using sudo unless you need to. Refer to comment by Steve in the comments

Playing a MP3 file in a WinForm application

You can do it using old DirectShow functionality.

This answer teaches you how to create QuartzTypeLib.dll:

  1. Run tlbimp tool (in your case path will be different):

  2. Run TlbImp.exe %windir%\system32\quartz.dll /out:QuartzTypeLib.dll

Alternatively, this project contains the library interop.QuartzTypeLib.dll, which is basically the same thing as steps 1. and 2. The following steps teach how to use this library:

  1. Add generated QuartzTypeLib.dll as a COM-reference to your project (click right mouse button on the project name in "Solution Explorer", then select "Add" menu item and then "Reference")

  2. In your Project, expand the "References", find the QuartzTypeLib reference. Right click it and select properties, and change "Embed Interop Types" to false. (Otherwise you won't be able to use the FilgraphManager class in your project (and probably a couple of other ones)).

  3. In Project Settings, in the Build tab, I had to disable the Prefer 32-bit flag, Otherwise I would get this Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040266

  4. Use this class to play your favorite MP3 file:

    using QuartzTypeLib;
    
    public sealed class DirectShowPlayer
    {
        private FilgraphManager FilterGraph;
    
        public void Play(string path)
        {
            FilgraphManager = new FilgraphManager();
            FilterGraph.RenderFile(path);
            FilterGraph.Run();
        }
    
        public void Stop()
        {
            FilterGraph?.Stop();
        }
    }
    

PS: TlbImp.exe can be found here: "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin", or in "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools"

What is pluginManagement in Maven's pom.xml?

pluginManagement: is an element that is seen along side plugins. Plugin Management contains plugin elements in much the same way, except that rather than configuring plugin information for this particular project build, it is intended to configure project builds that inherit from this one. However, this only configures plugins that are actually referenced within the plugins element in the children. The children have every right to override pluginManagement definitions.

From http://maven.apache.org/pom.html#Plugin%5FManagement

Copied from :

Maven2 - problem with pluginManagement and parent-child relationship

Format a JavaScript string using placeholders and an object of substitutions?

I have written a code that lets you format string easily.

Use this function.

function format() {
    if (arguments.length === 0) {
        throw "No arguments";
    }
    const string = arguments[0];
    const lst = string.split("{}");
    if (lst.length !== arguments.length) {
        throw "Placeholder format mismatched";
    }
    let string2 = "";
    let off = 1;
    for (let i = 0; i < lst.length; i++) {
        if (off < arguments.length) {
            string2 += lst[i] + arguments[off++]
        } else {
            string2 += lst[i]
        }
    }
    return string2;
}

Example

format('My Name is {} and my age is {}', 'Mike', 26);

Output

My Name is Mike and my age is 26

Calculate correlation for more than two variables?

You might want to look at Quick-R, which has a lot of nice little tutorials on how you can do basic statistics in R. For example on correlations:

http://www.statmethods.net/stats/correlations.html

Anaconda vs. miniconda

Anaconda is a very large installation ~ 2 GB and is most useful for those users who are not familiar with installing modules or packages with other package managers.

Anaconda seems to be promoting itself as the official package manager of Jupyter. It's not. Anaconda bundles Jupyter, R, python, and many packages with its installation.

Anaconda is not necessary for installing Jupyter Lab or the R kernel. There is plenty of information available elsewhere for installing Jupyter Lab or Notebooks. There is also plenty of information elsewhere for installing R studio. The following shows how to install the R kernel directly from R Studio:

To install the R kernel, without Anaconda, start R Studio. In the R terminal window enter these three commands:

install.packages("devtools")
devtools::install_github("IRkernel/IRkernel")
IRkernel::installspec()

Done. Next time Jupyter is opened, the R kernel will be available.

Bash loop ping successful

You probably shouldn't rely on textual output of a command to decide this, especially when the ping command gives you a perfectly good return value:

The ping utility returns an exit status of zero if at least one response was heard from the specified host; a status of two if the transmission was successful but no responses were received; or another value from <sysexits.h> if an error occurred.

In other words, use something like:

((count = 100))                            # Maximum number to try.
while [[ $count -ne 0 ]] ; do
    ping -c 1 8.8.8.8                      # Try once.
    rc=$?
    if [[ $rc -eq 0 ]] ; then
        ((count = 1))                      # If okay, flag to exit loop.
    fi
    ((count = count - 1))                  # So we don't go forever.
done

if [[ $rc -eq 0 ]] ; then                  # Make final determination.
    echo `say The internet is back up.`
else
    echo `say Timeout.`
fi

SELECT INTO a table variable in T-SQL

The purpose of SELECT INTO is (per the docs, my emphasis)

To create a new table from values in another table

But you already have a target table! So what you want is

The INSERT statement adds one or more new rows to a table

You can specify the data values in the following ways:

...

By using a SELECT subquery to specify the data values for one or more rows, such as:

  INSERT INTO MyTable 
 (PriKey, Description)
        SELECT ForeignKey, Description
        FROM SomeView

And in this syntax, it's allowed for MyTable to be a table variable.

Start an activity from a fragment

If you are using getActivity() then you have to make sure that the calling activity is added already. If activity has not been added in such case so you may get null when you call getActivity()

in such cases getContext() is safe

then the code for starting the activity will be slightly changed like,

Intent intent = new Intent(getContext(), mFragmentFavorite.class);
startActivity(intent);

Activity, Service and Application extends ContextWrapper class so you can use this or getContext() or getApplicationContext() in the place of first argument.

How to change package name in android studio?

Another good method is: First create a new package with the desired name by right clicking on the java folder -> new -> package.

Then, select and drag all your classes to the new package. Android Studio will refactor the package name everywhere.

Finally, delete the old package.

or Look into this post

mongodb/mongoose findMany - find all documents with IDs listed in array

Combining Daniel's and snnsnn's answers:

_x000D_
_x000D_
let ids = ['id1','id2','id3']
let data = await MyModel.find(
  {'_id': { $in: ids}}
);
_x000D_
_x000D_
_x000D_

Simple and clean code. It works and tested against:

"mongodb": "^3.6.0", "mongoose": "^5.10.0",

How do you input command line arguments in IntelliJ IDEA?

maytham-???i???, you can use this code to simulate input of file:

System.setIn(new FileInputStream("FILE_NAME"));

Or send file name as parameter and then put it into FileInputStream:

System.setIn(new FileInputStream(args[0]));

identifier "string" undefined?

You must use std namespace. If this code in main.cpp you should write

using namespace std;

If this declaration is in header, then you shouldn't include namespace and just write

std::string level;

What’s the best way to get an HTTP response code from a URL?

The urllib2.HTTPError exception does not contain a getcode() method. Use the code attribute instead.

to remove first and last element in array

You used Fruits.shift() method to first element remove . Fruits.pop() method used for last element remove one by one if you used button click. Fruits.slice( start position, delete element)You also used slice method for remove element in middle start.

Can linux cat command be used for writing text to file?

I use the following code to write raw text to files, to update my CPU-settings. Hope this helps out! Script:

#!/bin/sh

cat > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor <<EOF
performance
EOF

cat > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor <<EOF
performance
EOF

This writes the text "performance" to the two files mentioned in the script above. This example overwrite old data in files.

This code is saved as a file (cpu_update.sh) and to make it executable run:

chmod +x cpu_update.sh

After that, you can run the script with:

./cpu_update.sh

IF you do not want to overwrite the old data in the file, switch out

cat > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor <<EOF

with

cat >> /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor <<EOF

This will append your text to the end of the file without removing what other data already is in the file.

How to import existing *.sql files in PostgreSQL 8.4?

Always preferred using a connection service file (lookup/google 'psql connection service file')

Then simply:

psql service={yourservicename} < {myfile.sql}

Where yourservicename is a section name from the service file.

Creating multiple objects with different names in a loop to store in an array list

ArrayList<Customer> custArr = new ArrayList<Customer>();
while(youWantToContinue) {
    //get a customerName
    //get an amount
    custArr.add(new Customer(customerName, amount);
}

For this to work... you'll have to fix your constructor...


Assuming your Customer class has variables called name and sale, your constructor should look like this:

public Customer(String customerName, double amount) {
    name = customerName;
    sale = amount;
}

Change your Store class to something more like this:

public class Store {

    private ArrayList<Customer> custArr;

    public new Store() {
        custArr = new ArrayList<Customer>();
    }

    public void addSale(String customerName, double amount) {
        custArr.add(new Customer(customerName, amount));
    }

    public Customer getSaleAtIndex(int index) {
        return custArr.get(index);
    }

    //or if you want the entire ArrayList:
    public ArrayList getCustArr() {
        return custArr;
    }
}

Pass a javascript variable value into input type hidden value

add some id for an input

var multi = product(2,3);
document.getElementById('id').value=multi;

Twig: in_array or similar possible within if statement?

Try this

{% if var in ['foo', 'bar', 'beer'] %}
    ...
{% endif %}

Is Eclipse the best IDE for Java?

In my opinion if you got the resources to use, then go with eclipse. NetBeans which is awesome like eclipse is another best option, these are the only 2 I've ever used (loved, needed, wanted)

Eclipse is hands down the most popular, and for good reason!

Hope this helps.

Dynamic variable names in Bash

Beyond associative arrays, there are several ways of achieving dynamic variables in Bash. Note that all these techniques present risks, which are discussed at the end of this answer.

In the following examples I will assume that i=37 and that you want to alias the variable named var_37 whose initial value is lolilol.

Method 1. Using a “pointer” variable

You can simply store the name of the variable in an indirection variable, not unlike a C pointer. Bash then has a syntax for reading the aliased variable: ${!name} expands to the value of the variable whose name is the value of the variable name. You can think of it as a two-stage expansion: ${!name} expands to $var_37, which expands to lolilol.

name="var_$i"
echo "$name"         # outputs “var_37”
echo "${!name}"      # outputs “lolilol”
echo "${!name%lol}"  # outputs “loli”
# etc.

Unfortunately, there is no counterpart syntax for modifying the aliased variable. Instead, you can achieve assignment with one of the following tricks.

1a. Assigning with eval

eval is evil, but is also the simplest and most portable way of achieving our goal. You have to carefully escape the right-hand side of the assignment, as it will be evaluated twice. An easy and systematic way of doing this is to evaluate the right-hand side beforehand (or to use printf %q).

And you should check manually that the left-hand side is a valid variable name, or a name with index (what if it was evil_code # ?). By contrast, all other methods below enforce it automatically.

# check that name is a valid variable name:
# note: this code does not support variable_name[index]
shopt -s globasciiranges
[[ "$name" == [a-zA-Z_]*([a-zA-Z_0-9]) ]] || exit

value='babibab'
eval "$name"='$value'  # carefully escape the right-hand side!
echo "$var_37"  # outputs “babibab”

Downsides:

  • does not check the validity of the variable name.
  • eval is evil.
  • eval is evil.
  • eval is evil.

1b. Assigning with read

The read builtin lets you assign values to a variable of which you give the name, a fact which can be exploited in conjunction with here-strings:

IFS= read -r -d '' "$name" <<< 'babibab'
echo "$var_37"  # outputs “babibab\n”

The IFS part and the option -r make sure that the value is assigned as-is, while the option -d '' allows to assign multi-line values. Because of this last option, the command returns with an non-zero exit code.

Note that, since we are using a here-string, a newline character is appended to the value.

Downsides:

  • somewhat obscure;
  • returns with a non-zero exit code;
  • appends a newline to the value.

1c. Assigning with printf

Since Bash 3.1 (released 2005), the printf builtin can also assign its result to a variable whose name is given. By contrast with the previous solutions, it just works, no extra effort is needed to escape things, to prevent splitting and so on.

printf -v "$name" '%s' 'babibab'
echo "$var_37"  # outputs “babibab”

Downsides:

  • Less portable (but, well).

Method 2. Using a “reference” variable

Since Bash 4.3 (released 2014), the declare builtin has an option -n for creating a variable which is a “name reference” to another variable, much like C++ references. Just as in Method 1, the reference stores the name of the aliased variable, but each time the reference is accessed (either for reading or assigning), Bash automatically resolves the indirection.

In addition, Bash has a special and very confusing syntax for getting the value of the reference itself, judge by yourself: ${!ref}.

declare -n ref="var_$i"
echo "${!ref}"  # outputs “var_37”
echo "$ref"     # outputs “lolilol”
ref='babibab'
echo "$var_37"  # outputs “babibab”

This does not avoid the pitfalls explained below, but at least it makes the syntax straightforward.

Downsides:

  • Not portable.

Risks

All these aliasing techniques present several risks. The first one is executing arbitrary code each time you resolve the indirection (either for reading or for assigning). Indeed, instead of a scalar variable name, like var_37, you may as well alias an array subscript, like arr[42]. But Bash evaluates the contents of the square brackets each time it is needed, so aliasing arr[$(do_evil)] will have unexpected effects… As a consequence, only use these techniques when you control the provenance of the alias.

function guillemots() {
  declare -n var="$1"
  var="«${var}»"
}

arr=( aaa bbb ccc )
guillemots 'arr[1]'  # modifies the second cell of the array, as expected
guillemots 'arr[$(date>>date.out)1]'  # writes twice into date.out
            # (once when expanding var, once when assigning to it)

The second risk is creating a cyclic alias. As Bash variables are identified by their name and not by their scope, you may inadvertently create an alias to itself (while thinking it would alias a variable from an enclosing scope). This may happen in particular when using common variable names (like var). As a consequence, only use these techniques when you control the name of the aliased variable.

function guillemots() {
  # var is intended to be local to the function,
  # aliasing a variable which comes from outside
  declare -n var="$1"
  var="«${var}»"
}

var='lolilol'
guillemots var  # Bash warnings: “var: circular name reference”
echo "$var"     # outputs anything!

Source:

Swift UIView background color opacity

The question is old, but it seems that there are people who have the same concerns.

What do you think of the opinion that 'the alpha property of UIColor and the opacity property of Interface Builder are applied differently in code'?


The two views created in Interface Builder were initially different colors, but had to be the same color when the conditions changed. So, I had to set the background color of one view in code, and set a different value to make the background color of both views the same.

As an actual example, the background color of Interface Builder was 0x121212 and the Opacity value was 80%(in Amani Elsaed's image :: Red: 18, Green: 18, Blue: 18, Hex Color #: [121212], Opacity: 80), In the code, I set the other view a background color of 0x121212 with an alpha value of 0.8.

self.myFuncView.backgroundColor = UIColor(red: 18, green: 18, blue: 18, alpha: 0.8)

extension is

extension UIColor {
    convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat = 1.0) {
        self.init(red: CGFloat(red) / 255.0,
                  green: CGFloat(green) / 255.0,
                  blue: CGFloat(blue) / 255.0,
                  alpha: alpha)
    }
}

However, the actual view was

  • 'View with background color specified in Interface Builder': R 0.09 G 0.09 B 0.09 alpha 0.8.
  • 'View with background color by code': R 0.07 G 0.07 B 0.07 alpha 0.8

Calculating it,

  • 0x12 = 18(decimal)
  • 18/255 = 0.07058...
  • 255 * 0.09 = 22.95
  • 23(decimal) = 0x17

So, I was able to match the colors similarly by setting the UIColor values ??to 17, 17, 17 and alpha 0.8.

self.myFuncView.backgroundColor = UIColor(red: 17, green: 17, blue: 17, alpha: 0.8)

Or can anyone tell me what I'm missing?

ipad safari: disable scrolling, and bounce effect?

Code to To remove ipad safari: disable scrolling, and bounce effect

   document.addEventListener("touchmove", function (e) {
        e.preventDefault();
    }, { passive: false });

If you have canvas tag inside document, sometime it will affect the usability of object inside Canvas(example: movement of object); so add below code to fix it.

    document.getElementById("canvasId").addEventListener("touchmove", function (e) {
        e.stopPropagation();
    }, { passive: false });

Page Redirect after X seconds wait using JavaScript

You need to pass a function to setTimeout

$(window).load(function () {
    window.setTimeout(function () {
        window.location.href = "https://www.google.co.in";
    }, 5000)
});

Getting attributes of a class

two function:

def get_class_attr(Cls) -> []:
    import re
    return [a for a, v in Cls.__dict__.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]

def get_class_attr_val(cls):
    attr = get_class_attr(type(cls))
    attr_dict = {}
    for a in attr:
        attr_dict[a] = getattr(cls, a)
    return attr_dict

use:

>>> class MyClass:
    a = "12"
    b = "34"
    def myfunc(self):
        return self.a

>>> m = MyClass()
>>> get_class_attr_val(m)
{'a': '12', 'b': '34'}

Print list without brackets in a single row

For array of integer type, we need to change it to string type first and than use join function to get clean output without brackets.

    arr = [1, 2, 3, 4, 5]    
    print(', '.join(map(str, arr)))

OUTPUT - 1, 2, 3, 4, 5

For array of string type, we need to use join function directly to get clean output without brackets.

    arr = ["Ram", "Mohan", "Shyam", "Dilip", "Sohan"]
    print(', '.join(arr)

OUTPUT - Ram, Mohan, Shyam, Dilip, Sohan

In Go's http package, how do I get the query string on a POST request?

A QueryString is, by definition, in the URL. You can access the URL of the request using req.URL (doc). The URL object has a Query() method (doc) that returns a Values type, which is simply a map[string][]string of the QueryString parameters.

If what you're looking for is the POST data as submitted by an HTML form, then this is (usually) a key-value pair in the request body. You're correct in your answer that you can call ParseForm() and then use req.Form field to get the map of key-value pairs, but you can also call FormValue(key) to get the value of a specific key. This calls ParseForm() if required, and gets values regardless of how they were sent (i.e. in query string or in the request body).

Prevent browser caching of AJAX call result

JQuery's $.get() will cache the results. Instead of

$.get("myurl", myCallback)

you should use $.ajax, which will allow you to turn caching off:

$.ajax({url: "myurl", success: myCallback, cache: false});

android: data binding error: cannot find symbol class

In my case, there was a package with the same name as a missing import in the generated databinding class.. It seems like the compiler got confused.

Creating layout constraints programmatically

Hi I have been using this page a lot for constraints and "how to". It took me forever to get to the point of realizing I needed:

myView.translatesAutoresizingMaskIntoConstraints = NO;

to get this example to work. Thank you Userxxx, Rob M. and especially larsacus for the explanation and code here, it has been invaluable.

Here is the code in full to get the examples above to run:

UIView *myView = [[UIView alloc] init];
myView.backgroundColor = [UIColor redColor];
myView.translatesAutoresizingMaskIntoConstraints = NO;  //This part hung me up 
[self.view addSubview:myView];
//needed to make smaller for iPhone 4 dev here, so >=200 instead of 748
[self.view addConstraints:[NSLayoutConstraint
                           constraintsWithVisualFormat:@"V:|-[myView(>=200)]-|"
                           options:NSLayoutFormatDirectionLeadingToTrailing
                           metrics:nil
                           views:NSDictionaryOfVariableBindings(myView)]];

[self.view addConstraints:[NSLayoutConstraint
                           constraintsWithVisualFormat:@"H:[myView(==200)]-|"
                           options:NSLayoutFormatDirectionLeadingToTrailing
                           metrics:nil
                           views:NSDictionaryOfVariableBindings(myView)]];

JavaScript: remove event listener

   canvas.addEventListener('click', function(event) {
      click++;
      if(click == 50) {
          this.removeEventListener('click',arguments.callee,false);
      }

Should do it.

How to make PDF file downloadable in HTML link?

Try this:

<a href="pdf_server_with_path.php?file=pdffilename&path=http://myurl.com/mypath/">Download my eBook</a>

The code inside pdf_server_with_path.php is:

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".pdf";
$path = $_GET["path"];
$fullfile = $path.$file;

header("Content-Disposition: attachment; filename=" . Urlencode($file));   
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . Filesize($fullfile));
flush(); // this doesn't really matter.
$fp = fopen($fullfile, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
} 
fclose($fp);

Sprintf equivalent in Java

Both solutions workto simulate printf, but in a different way. For instance, to convert a value to a hex string, you have the 2 following solutions:

  • with format(), closest to sprintf():

    final static String HexChars = "0123456789abcdef";
    
    public static String getHexQuad(long v) {
        String ret;
        if(v > 0xffff) ret = getHexQuad(v >> 16); else ret = "";
        ret += String.format("%c%c%c%c",
            HexChars.charAt((int) ((v >> 12) & 0x0f)),
            HexChars.charAt((int) ((v >>  8) & 0x0f)),
            HexChars.charAt((int) ((v >>  4) & 0x0f)),
            HexChars.charAt((int) ( v        & 0x0f)));
        return ret;
    }
    
  • with replace(char oldchar , char newchar), somewhat faster but pretty limited:

        ...
        ret += "ABCD".
            replace('A', HexChars.charAt((int) ((v >> 12) & 0x0f))).
            replace('B', HexChars.charAt((int) ((v >>  8) & 0x0f))).
            replace('C', HexChars.charAt((int) ((v >>  4) & 0x0f))).
            replace('D', HexChars.charAt((int) ( v        & 0x0f)));
        ...
    
  • There is a third solution consisting of just adding the char to ret one by one (char are numbers that add to each other!) such as in:

    ...
    ret += HexChars.charAt((int) ((v >> 12) & 0x0f)));
    ret += HexChars.charAt((int) ((v >>  8) & 0x0f)));
    ...
    

...but that'd be really ugly.

Serialize an object to XML

To serialize an object, do:

 using (StreamWriter myWriter = new StreamWriter(path, false))
 {
     XmlSerializer mySerializer = new XmlSerializer(typeof(your_object_type));
     mySerializer.Serialize(myWriter, objectToSerialize);
 }

Also remember that for XmlSerializer to work, you need a parameterless constructor.

What does the error "arguments imply differing number of rows: x, y" mean?

Your data.frame mat is rectangular (n_rows!= n_cols).

Therefore, you cannot make a data.frame out of the column- and rownames, because each column in a data.frame must be the same length.

Maybe this suffices your needs:

require(reshape2)
mat$id <- rownames(mat) 
melt(mat)

Pass path with spaces as parameter to bat file

I think the OP's problem was that he wants to do BOTH of the following:

  • Pass a parameter which may contain spaces
  • Test whether the parameter is missing

As several posters have mentioned, to pass a parameter containing spaces, you must surround the actual parameter value with double quotes.

To test whether a parameter is missing, the method I always learned was:

if "%1" == ""

However, if the actual parameter is quoted (as it must be if the value contains spaces), this becomes

if ""actual parameter value"" == ""

which causes the "unexpected" error. If you instead use

if %1 == ""

then the error no longer occurs for quoted values. But in that case, the test no longer works when the value is missing -- it becomes

if  == ""

To fix this, use any other characters (except ones with special meaning to DOS) instead of quotes in the test:

if [%1] == []
if .%1. == ..
if abc%1xyz == abcxyz

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

In Netbeans 7.1 can select columns (Rectangular Selection) with Ctrl + shift + R . There is also a button Toggle Rectangular Selection Button in the code editor available.

This is how rectangular selections look like: Screenshot Rectangular Selection

Best way to iterate through a Perl array

The best way to decide questions like this to benchmark them:

use strict;
use warnings;
use Benchmark qw(:all);

our @input_array = (0..1000);

my $a = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    foreach my $element (@array) {
       die unless $index == $element;
       $index++;
    }
};

my $b = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    while (defined(my $element = shift @array)) {
       die unless $index == $element;
       $index++;
    }
};

my $c = sub {
    my @array = @{[ @input_array ]};
    my $index = 0;
    while (scalar(@array) !=0) {
       my $element = shift(@array);
       die unless $index == $element;
       $index++;
    }
};

my $d = sub {
    my @array = @{[ @input_array ]};
    foreach my $index (0.. $#array) {
       my $element = $array[$index];
       die unless $index == $element;
    }
};

my $e = sub {
    my @array = @{[ @input_array ]};
    for (my $index = 0; $index <= $#array; $index++) {
       my $element = $array[$index];
       die unless $index == $element;
    }
};

my $f = sub {
    my @array = @{[ @input_array ]};
    while (my ($index, $element) = each @array) {
       die unless $index == $element;
    }
};

my $count;
timethese($count, {
   '1' => $a,
   '2' => $b,
   '3' => $c,
   '4' => $d,
   '5' => $e,
   '6' => $f,
});

And running this on perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linux-gnu-thread-multi

I get:

Benchmark: running 1, 2, 3, 4, 5, 6 for at least 3 CPU seconds...
         1:  3 wallclock secs ( 3.16 usr +  0.00 sys =  3.16 CPU) @ 12560.13/s (n=39690)
         2:  3 wallclock secs ( 3.18 usr +  0.00 sys =  3.18 CPU) @ 7828.30/s (n=24894)
         3:  3 wallclock secs ( 3.23 usr +  0.00 sys =  3.23 CPU) @ 6763.47/s (n=21846)
         4:  4 wallclock secs ( 3.15 usr +  0.00 sys =  3.15 CPU) @ 9596.83/s (n=30230)
         5:  4 wallclock secs ( 3.20 usr +  0.00 sys =  3.20 CPU) @ 6826.88/s (n=21846)
         6:  3 wallclock secs ( 3.12 usr +  0.00 sys =  3.12 CPU) @ 5653.53/s (n=17639)

So the 'foreach (@Array)' is about twice as fast as the others. All the others are very similar.

@ikegami also points out that there are quite a few differences in these implimentations other than speed.

Setting unique Constraint with fluent API?

Here is an extension method for setting unique indexes more fluently:

public static class MappingExtensions
{
    public static PrimitivePropertyConfiguration IsUnique(this PrimitivePropertyConfiguration configuration)
    {
        return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute { IsUnique = true }));
    }
}

Usage:

modelBuilder 
    .Entity<Person>() 
    .Property(t => t.Name)
    .IsUnique();

Will generate migration such as:

public partial class Add_unique_index : DbMigration
{
    public override void Up()
    {
        CreateIndex("dbo.Person", "Name", unique: true);
    }

    public override void Down()
    {
        DropIndex("dbo.Person", new[] { "Name" });
    }
}

Src: Creating Unique Index with Entity Framework 6.1 fluent API

Is this very likely to create a memory leak in Tomcat?

This problem appears when we are using any third party solution, without using the handlers for the cleanup activitiy. For me this was happening for EhCache. We were using EhCache in our project for caching. And often we used to see following error in the logs

 SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.

And we often noticed tomcat failing for OutOfMemory error during development where we used to do backend changes and deploy the application multiple times for reflecting our changes.

This is the fix we did

<listener>
  <listener-class>
     net.sf.ehcache.constructs.web.ShutdownListener
  </listener-class>
</listener>

So point I am trying to make is check the documentation of the third party libraries which you are using. They should be providing some mechanisms to clean up the threads during shutdown. Which you need to use in your application. No need to re-invent the wheel unless its not provided by them. The worst case is to provide your own implementation.

Reference for EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html

Raise error in a Bash script

There are a couple more ways with which you can approach this problem. Assuming one of your requirement is to run a shell script/function containing a few shell commands and check if the script ran successfully and throw errors in case of failures.

The shell commands in generally rely on exit-codes returned to let the shell know if it was successful or failed due to some unexpected events.

So what you want to do falls upon these two categories

  • exit on error
  • exit and clean-up on error

Depending on which one you want to do, there are shell options available to use. For the first case, the shell provides an option with set -e and for the second you could do a trap on EXIT

Should I use exit in my script/function?

Using exit generally enhances readability In certain routines, once you know the answer, you want to exit to the calling routine immediately. If the routine is defined in such a way that it doesn’t require any further cleanup once it detects an error, not exiting immediately means that you have to write more code.

So in cases if you need to do clean-up actions on script to make the termination of the script clean, it is preferred to not to use exit.

Should I use set -e for error on exit?

No!

set -e was an attempt to add "automatic error detection" to the shell. Its goal was to cause the shell to abort any time an error occurred, but it comes with a lot of potential pitfalls for example,

  • The commands that are part of an if test are immune. In the example, if you expect it to break on the test check on the non-existing directory, it wouldn't, it goes through to the else condition

    set -e
    f() { test -d nosuchdir && echo no dir; }
    f
    echo survived
    
  • Commands in a pipeline other than the last one, are immune. In the example below, because the most recently executed (rightmost) command's exit code is considered ( cat) and it was successful. This could be avoided by setting by the set -o pipefail option but its still a caveat.

    set -e
    somecommand that fails | cat -
    echo survived 
    

Recommended for use - trap on exit

The verdict is if you want to be able to handle an error instead of blindly exiting, instead of using set -e, use a trap on the ERR pseudo signal.

The ERR trap is not to run code when the shell itself exits with a non-zero error code, but when any command run by that shell that is not part of a condition (like in if cmd, or cmd ||) exits with a non-zero exit status.

The general practice is we define an trap handler to provide additional debug information on which line and what cause the exit. Remember the exit code of the last command that caused the ERR signal would still be available at this point.

cleanup() {
    exitcode=$?
    printf 'error condition hit\n' 1>&2
    printf 'exit code returned: %s\n' "$exitcode"
    printf 'the command executing at the time of the error was: %s\n' "$BASH_COMMAND"
    printf 'command present on line: %d' "${BASH_LINENO[0]}"
    # Some more clean up code can be added here before exiting
    exit $exitcode
}

and we just use this handler as below on top of the script that is failing

trap cleanup ERR

Putting this together on a simple script that contained false on line 15, the information you would be getting as

error condition hit
exit code returned: 1
the command executing at the time of the error was: false
command present on line: 15

The trap also provides options irrespective of the error to just run the cleanup on shell completion (e.g. your shell script exits), on signal EXIT. You could also trap on multiple signals at the same time. The list of supported signals to trap on can be found on the trap.1p - Linux manual page

Another thing to notice would be to understand that none of the provided methods work if you are dealing with sub-shells are involved in which case, you might need to add your own error handling.

  • On a sub-shell with set -e wouldn't work. The false is restricted to the sub-shell and never gets propagated to the parent shell. To do the error handling here, add your own logic to do (false) || false

    set -e
    (false)
    echo survived
    
  • The same happens with trap also. The logic below wouldn't work for the reasons mentioned above.

    trap 'echo error' ERR
    (false)
    

Change the size of a JTextField inside a JBorderLayout

With a BorderLayout you need to use setPreferredSize instead of setSize

How to call a parent class function from derived class function?

Given a parent class named Parent and a child class named Child, you can do something like this:

class Parent {
public:
    virtual void print(int x);
};

class Child : public Parent {
    void print(int x) override;
};

void Parent::print(int x) {
    // some default behavior
}

void Child::print(int x) {
    // use Parent's print method; implicitly passes 'this' to Parent::print
    Parent::print(x);
}

Note that Parent is the class's actual name and not a keyword.

Open Url in default web browser

You should use Linking.

Example from the docs:

class OpenURLButton extends React.Component {
  static propTypes = { url: React.PropTypes.string };
  handleClick = () => {
    Linking.canOpenURL(this.props.url).then(supported => {
      if (supported) {
        Linking.openURL(this.props.url);
      } else {
        console.log("Don't know how to open URI: " + this.props.url);
      }
    });
  };
  render() {
    return (
      <TouchableOpacity onPress={this.handleClick}>
        {" "}
        <View style={styles.button}>
          {" "}<Text style={styles.text}>Open {this.props.url}</Text>{" "}
        </View>
        {" "}
      </TouchableOpacity>
    );
  }
}

Here's an example you can try on Expo Snack:

import React, { Component } from 'react';
import { View, StyleSheet, Button, Linking } from 'react-native';
import { Constants } from 'expo';

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
       <Button title="Click me" onPress={ ()=>{ Linking.openURL('https://google.com')}} />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
});

submitting a GET form with query string params and hidden params disappear

Isn't that what hidden parameters are for to start with...?

<form action="http://www.example.com" method="GET">
  <input type="hidden" name="a" value="1" /> 
  <input type="hidden" name="b" value="2" /> 
  <input type="hidden" name="c" value="3" /> 
  <input type="submit" /> 
</form>

I wouldn't count on any browser retaining any existing query string in the action URL.

As the specifications (RFC1866, page 46; HTML 4.x section 17.13.3) state:

If the method is "get" and the action is an HTTP URI, the user agent takes the value of action, appends a `?' to it, then appends the form data set, encoded using the "application/x-www-form-urlencoded" content type.

Maybe one could percent-encode the action-URL to embed the question mark and the parameters, and then cross one's fingers to hope all browsers would leave that URL as it (and validate that the server understands it too). But I'd never rely on that.

By the way: it's not different for non-hidden form fields. For POST the action URL could hold a query string though.

Are static methods inherited in Java?

All the public and protected members can be inherited from any class while the default or package members can also be inherited from the class within the same package as that of the superclass. It does not depend whether it is static or non static member.

But it is also true that static member function do not take part in dynamic binding. If the signature of that static method is same in both parent and child class then concept of Shadowing applies, not polymorphism.

In android app Toolbar.setTitle method has no effect – application name is shown as title

This can be done by setting the android:label attribute of your activity in the AndroidManifest.xml file:

<activity android:name="my activity"
 android:label="The Title I'd like to display" />

And then add this line to the onCreate():

getSupportActionBar().setDisplayShowTitleEnabled(true);

CSS grid wrapping

You may be looking for auto-fill:

grid-template-columns: repeat(auto-fill, 186px);

Demo: http://codepen.io/alanbuchanan/pen/wJRMox

To use up the available space more efficiently, you could use minmax, and pass in auto as the second argument:

grid-template-columns: repeat(auto-fill, minmax(186px, auto));

Demo: http://codepen.io/alanbuchanan/pen/jBXWLR

If you don't want the empty columns, you could use auto-fit instead of auto-fill.

Alert handling in Selenium WebDriver (selenium 2) with Java

try 
    {
        //Handle the alert pop-up using seithTO alert statement
        Alert alert = driver.switchTo().alert();

        //Print alert is present
        System.out.println("Alert is present");

        //get the message which is present on pop-up
        String message = alert.getText();

        //print the pop-up message
        System.out.println(message);

        alert.sendKeys("");
        //Click on OK button on pop-up
        alert.accept();
    } 
    catch (NoAlertPresentException e) 
    {
        //if alert is not present print message
        System.out.println("alert is not present");
    }

How to format Joda-Time DateTime to only mm/dd/yyyy?

I am adding this here even though the other answers are completely acceptable. JodaTime has parsers pre built in DateTimeFormat:

dateTime.toString(DateTimeFormat.longDate());

This is most of the options printed out with their format:

shortDate:         11/3/16
shortDateTime:     11/3/16 4:25 AM
mediumDate:        Nov 3, 2016
mediumDateTime:    Nov 3, 2016 4:25:35 AM
longDate:          November 3, 2016
longDateTime:      November 3, 2016 4:25:35 AM MDT
fullDate:          Thursday, November 3, 2016
fullDateTime:      Thursday, November 3, 2016 4:25:35 AM Mountain Daylight Time

Repeat command automatically in Linux

while true; do
    sleep 5
    ls -l
done

eclipse stuck when building workspace

I have this problem whe I have too much maven projects open at once. What I tend to do is:

  • Restart eclipse (sometimes I need to kill eclipse)
  • Disable automatic build immediatly (project > uncheck Build automatically)
  • Right click the project(s) I want to have rebuild
  • Close unrelated projects
  • Re-enable automatic build

This enables a functioning rebuild in 99% off the cases in my workspace.

Difference between File.separator and slash in paths

The pathname for a file or directory is specified using the naming conventions of the host system. However, the File class defines platform-dependent constants that can be used to handle file and directory names in a platform-independent way.

Files.seperator defines the character or string that separates the directory and the file com- ponents in a pathname. This separator is '/', '\' or ':' for Unix, Windows, and Macintosh, respectively.

Why must wait() always be in synchronized block

@Rollerball is right. The wait() is called, so that the thread can wait for some condition to occur when this wait() call happens, the thread is forced to give up its lock.
To give up something, you need to own it first. Thread needs to own the lock first. Hence the need to call it inside a synchronized method/block.

Yes, I do agree with all the above answers regarding the potential damages/inconsistencies if you did not check the condition within synchronized method/block. However as @shrini1000 has pointed out, just calling wait() within synchronized block will not avert this inconsistency from happening.

Here is a nice read..

Best C# API to create PDF

My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)

Getting MAC Address

Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily:

from uuid import getnode as get_mac
mac = get_mac()

The return value is the mac address as 48 bit integer.

Detecting TCP Client Disconnect

In python you can do a try-except statement like this:

try:
  conn.send("{you can send anything to check connection}")
except BrokenPipeError:
  print("Client has Disconnected")

This works because when the client/server closes the program, python returns broken pip error to the server or client depending on who it was that disconnected.

Can't connect to MySQL server error 111

If all the previous answers didn't give any solution, you should check your user privileges.

If you could login as root to mysql then you should add this:

CREATE USER 'root'@'192.168.1.100' IDENTIFIED BY  '***';
GRANT ALL PRIVILEGES ON * . * TO  'root'@'192.168.1.100' IDENTIFIED BY  '***' WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;

Then try to connect again using mysql -ubeer -pbeer -h192.168.1.100. It should work.

Call a function from another file?

You should have the file at the same location as that of the Python files you are trying to import. Also 'from file import function' is enough.

How to check string length with JavaScript

I'm not sure what you mean by having tried it onblur, but to get the length of any string, use its .length property, so in the case of a textbox or textarea:

document.getElementById("textarea").value.length

Changing that ID, of course, to whatever the actual ID is.

Solution to "subquery returns more than 1 row" error

= can be used when the subquery returns only 1 value.

When subquery returns more than 1 value, you will have to use IN:

select * 
from table
where id IN (multiple row query);

For example:

SELECT *
FROM Students
WHERE Marks = (SELECT MAX(Marks) FROM Students)   --Subquery returns only 1 value

SELECT *
FROM Students
WHERE Marks IN 
      (SELECT Marks 
       FROM Students 
       ORDER BY Marks DESC
       LIMIT 10)                       --Subquery returns 10 values

SSL Connection / Connection Reset with IISExpress

I was getting ERR_CONNECTION_RESET because my Visual Studio 2013/IIS Express configured app port number was NOT in the range :44300-:44398. (I don't recall having to dismiss any warnings to get out of that range.) Changing the port number to something in this range is all I had to do to make it work.

I noticed this after reviewing the netsh http show sslcert > sslcert.txt output and something clicking with stuff I read recently about the port numbers.

Playing sound notifications using Javascript?

First things first, i'd not like that as a user.

The best way to do is probably using a small flash applet that plays your sound in the background.

Also answered here: Cross-platform, cross-browser way to play sound from Javascript?

SQL query to group by day

If you're using MySQL:

SELECT
    DATE(created) AS saledate,
    SUM(amount)
FROM
    Sales
GROUP BY
    saledate

If you're using MS SQL 2008:

SELECT
    CAST(created AS date) AS saledate,
    SUM(amount)
FROM
    Sales
GROUP BY
    CAST(created AS date)

Select value if condition in SQL Server

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

Left Outer Join using + sign in Oracle 11g

I saw some contradictions in the answers above, I just tried the following on Oracle 12c and the following is correct :

LEFT OUTER JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT *
FROM A, B
WHERE B.column(+) = A.column

How to click on hidden element in Selenium WebDriver?

Use an XPath of the link by using Selenium IDE to click the element:

driver.findelement(By.xpath("//a[contains(@title, \"Plastic Spiral Bind\")]")).click();

Extract a substring according to a pattern

Here are a few ways:

1) sub

sub(".*:", "", string)
## [1] "E001" "E002" "E003"

2) strsplit

sapply(strsplit(string, ":"), "[", 2)
## [1] "E001" "E002" "E003"

3) read.table

read.table(text = string, sep = ":", as.is = TRUE)$V2
## [1] "E001" "E002" "E003"

4) substring

This assumes second portion always starts at 4th character (which is the case in the example in the question):

substring(string, 4)
## [1] "E001" "E002" "E003"

4a) substring/regex

If the colon were not always in a known position we could modify (4) by searching for it:

substring(string, regexpr(":", string) + 1)

5) strapplyc

strapplyc returns the parenthesized portion:

library(gsubfn)
strapplyc(string, ":(.*)", simplify = TRUE)
## [1] "E001" "E002" "E003"

6) read.dcf

This one only works if the substrings prior to the colon are unique (which they are in the example in the question). Also it requires that the separator be colon (which it is in the question). If a different separator were used then we could use sub to replace it with a colon first. For example, if the separator were _ then string <- sub("_", ":", string)

c(read.dcf(textConnection(string)))
## [1] "E001" "E002" "E003"

7) separate

7a) Using tidyr::separate we create a data frame with two columns, one for the part before the colon and one for after, and then extract the latter.

library(dplyr)
library(tidyr)
library(purrr)

DF <- data.frame(string)
DF %>% 
  separate(string, into = c("pre", "post")) %>% 
  pull("post")
## [1] "E001" "E002" "E003"

7b) Alternately separate can be used to just create the post column and then unlist and unname the resulting data frame:

library(dplyr)
library(tidyr)

DF %>% 
  separate(string, into = c(NA, "post")) %>% 
  unlist %>%
  unname
## [1] "E001" "E002" "E003"

8) trimws We can use trimws to trim word characters off the left and then use it again to trim the colon.

trimws(trimws(string, "left", "\\w"), "left", ":")
## [1] "E001" "E002" "E003"

Note

The input string is assumed to be:

string <- c("G1:E001", "G2:E002", "G3:E003")

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

For non-preemptive system,

waitingTime = startTime - arrivalTime

turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime

startTime = Time at which the process started executing

finishTime = Time at which the process finished executing

You can keep track of the current time elapsed in the system(timeElapsed). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime, when finishes, record its finishTime (both same as timeElapsed). That way you can calculate what you need.

Windows Bat file optional argument parsing

If you want to use optional arguments, but not named arguments, then this approach worked for me. I think this is much easier code to follow.

REM Get argument values.  If not specified, use default values.
IF "%1"=="" ( SET "DatabaseServer=localhost" ) ELSE ( SET "DatabaseServer=%1" )
IF "%2"=="" ( SET "DatabaseName=MyDatabase" ) ELSE ( SET "DatabaseName=%2" )

REM Do work
ECHO Database Server = %DatabaseServer%
ECHO Database Name   = %DatabaseName%

mysql count group by having

One way would be to use a nested query:

SELECT count(*)
FROM (
   SELECT COUNT(Genre) AS count
   FROM movies
   GROUP BY ID
   HAVING (count = 4)
) AS x

The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.

How to nicely format floating numbers to string without unnecessary decimal 0's

In short:

If you want to get rid of trailing zeros and locale problems, then you should use:

double myValue = 0.00000021d;

DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); //340 = DecimalFormat.DOUBLE_FRACTION_DIGITS

System.out.println(df.format(myValue)); //output: 0.00000021

Explanation:

Why other answers did not suit me:

  • Double.toString() or System.out.println or FloatingDecimal.toJavaFormatString uses scientific notations if double is less than 10^-3 or greater than or equal to 10^7

     double myValue = 0.00000021d;
     String.format("%s", myvalue); //output: 2.1E-7
    
  • by using %f, the default decimal precision is 6, otherwise you can hardcode it, but it results in extra zeros added if you have fewer decimals. Example:

     double myValue = 0.00000021d;
     String.format("%.12f", myvalue); // Output: 0.000000210000
    
  • by using setMaximumFractionDigits(0); or %.0f you remove any decimal precision, which is fine for integers/longs but not for double

     double myValue = 0.00000021d;
     System.out.println(String.format("%.0f", myvalue)); // Output: 0
     DecimalFormat df = new DecimalFormat("0");
     System.out.println(df.format(myValue)); // Output: 0
    
  • by using DecimalFormat, you are local dependent. In the French locale, the decimal separator is a comma, not a point:

     double myValue = 0.00000021d;
     DecimalFormat df = new DecimalFormat("0");
     df.setMaximumFractionDigits(340);
     System.out.println(df.format(myvalue)); // Output: 0,00000021
    

    Using the ENGLISH locale makes sure you get a point for decimal separator, wherever your program will run.

Why using 340 then for setMaximumFractionDigits?

Two reasons:

  • setMaximumFractionDigits accepts an integer, but its implementation has a maximum digits allowed of DecimalFormat.DOUBLE_FRACTION_DIGITS which equals 340
  • Double.MIN_VALUE = 4.9E-324 so with 340 digits you are sure not to round your double and lose precision

How do I find the value of $CATALINA_HOME?

Tomcat can tell you in several ways. Here's the easiest:

 $ /path/to/catalina.sh version
Using CATALINA_BASE:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_HOME:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.29/temp
Using JRE_HOME:        /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
Using CLASSPATH:       /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.29
Server built:   Jul 3 2012 11:31:52
Server number:  7.0.29.0
OS Name:        Mac OS X
OS Version:     10.7.4
Architecture:   x86_64
JVM Version:    1.6.0_33-b03-424-11M3720
JVM Vendor:     Apple Inc.

If you don't know where catalina.sh is (or it never gets called), you can usually find it via ps:

$ ps aux | grep catalina
chris            930   0.0  3.1  2987336 258328 s000  S    Wed01PM   2:29.43 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.library.path=/usr/local/apache-tomcat-7.0.29/lib -Djava.endorsed.dirs=/usr/local/apache-tomcat-7.0.29/endorsed -classpath /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar -Dcatalina.base=/Users/chris/blah/blah -Dcatalina.home=/usr/local/apache-tomcat-7.0.29 -Djava.io.tmpdir=/Users/chris/blah/blah/temp org.apache.catalina.startup.Bootstrap start

From the ps output, you can see both catalina.home and catalina.base. catalina.home is where the Tomcat base files are installed, and catalina.base is where the running configuration of Tomcat exists. These are often set to the same value unless you have configured your Tomcat for multiple (configuration) instances to be launched from a single Tomcat base install.

You can also interrogate the JVM directly if you can't find it in a ps listing:

$ jinfo -sysprops 930 | grep catalina
Attaching to process ID 930, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 20.8-b03-424
catalina.base = /Users/chris/blah/blah
[...]
catalina.home = /usr/local/apache-tomcat-7.0.29

If you can't manage that, you can always try to write a JSP that dumps the values of the two system properties catalina.home and catalina.base.

How do I bind a WPF DataGrid to a variable number of columns?

I managed to make it possible to dynamically add a column using just a line of code like this:

MyItemsCollection.AddPropertyDescriptor(
    new DynamicPropertyDescriptor<User, int>("Age", x => x.Age));

Regarding to the question, this is not a XAML-based solution (since as mentioned there is no reasonable way to do it), neither it is a solution which would operate directly with DataGrid.Columns. It actually operates with DataGrid bound ItemsSource, which implements ITypedList and as such provides custom methods for PropertyDescriptor retrieval. In one place in code you can define "data rows" and "data columns" for your grid.

If you would have:

IList<string> ColumnNames { get; set; }
//dict.key is column name, dict.value is value
Dictionary<string, string> Rows { get; set; }

you could use for example:

var descriptors= new List<PropertyDescriptor>();
//retrieve column name from preprepared list or retrieve from one of the items in dictionary
foreach(var columnName in ColumnNames)
    descriptors.Add(new DynamicPropertyDescriptor<Dictionary, string>(ColumnName, x => x[columnName]))
MyItemsCollection = new DynamicDataGridSource(Rows, descriptors) 

and your grid using binding to MyItemsCollection would be populated with corresponding columns. Those columns can be modified (new added or existing removed) at runtime dynamically and grid will automatically refresh it's columns collection.

DynamicPropertyDescriptor mentioned above is just an upgrade to regular PropertyDescriptor and provides strongly-typed columns definition with some additional options. DynamicDataGridSource would otherwise work just fine event with basic PropertyDescriptor.

How to set web.config file to show full error message

not sure if it'll work in your scenario, but try adding the following to your web.config under <system.web>:

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

works in my instance.

also see:

CustomErrors mode="Off"

Javascript Drag and drop for touch devices

Old thread I know.......

Problem with the answer of @ryuutatsuo is that it blocks also any input or other element that has to react on 'clicks' (for example inputs), so i wrote this solution. This solution made it possible to use any existing drag and drop library that is based upon mousedown, mousemove and mouseup events on any touch device (or cumputer). This is also a cross-browser solution.

I have tested in on several devices and it works fast (in combination with the drag and drop feature of ThreeDubMedia (see also http://threedubmedia.com/code/event/drag)). It is a jQuery solution so you can use it only with jQuery libs. I have used jQuery 1.5.1 for it because some newer functions don't work properly with IE9 and above (not tested with newer versions of jQuery).

Before you add any drag or drop operation to an event you have to call this function first:

simulateTouchEvents(<object>);

You can also block all components/children for input or to speed up event handling by using the following syntax:

simulateTouchEvents(<object>, true); // ignore events on childs

Here is the code i wrote. I used some nice tricks to speed up evaluating things (see code).

function simulateTouchEvents(oo,bIgnoreChilds)
{
 if( !$(oo)[0] )
  { return false; }

 if( !window.__touchTypes )
 {
   window.__touchTypes  = {touchstart:'mousedown',touchmove:'mousemove',touchend:'mouseup'};
   window.__touchInputs = {INPUT:1,TEXTAREA:1,SELECT:1,OPTION:1,'input':1,'textarea':1,'select':1,'option':1};
 }

$(oo).bind('touchstart touchmove touchend', function(ev)
{
    var bSame = (ev.target == this);
    if( bIgnoreChilds && !bSame )
     { return; }

    var b = (!bSame && ev.target.__ajqmeclk), // Get if object is already tested or input type
        e = ev.originalEvent;
    if( b === true || !e.touches || e.touches.length > 1 || !window.__touchTypes[e.type]  )
     { return; } //allow multi-touch gestures to work

    var oEv = ( !bSame && typeof b != 'boolean')?$(ev.target).data('events'):false,
        b = (!bSame)?(ev.target.__ajqmeclk = oEv?(oEv['click'] || oEv['mousedown'] || oEv['mouseup'] || oEv['mousemove']):false ):false;

    if( b || window.__touchInputs[ev.target.tagName] )
     { return; } //allow default clicks to work (and on inputs)

    // https://developer.mozilla.org/en/DOM/event.initMouseEvent for API
    var touch = e.changedTouches[0], newEvent = document.createEvent("MouseEvent");
    newEvent.initMouseEvent(window.__touchTypes[e.type], true, true, window, 1,
            touch.screenX, touch.screenY,
            touch.clientX, touch.clientY, false,
            false, false, false, 0, null);

    touch.target.dispatchEvent(newEvent);
    e.preventDefault();
    ev.stopImmediatePropagation();
    ev.stopPropagation();
    ev.preventDefault();
});
 return true;
}; 

What it does: At first, it translates single touch events into mouse events. It checks if an event is caused by an element on/in the element that must be dragged around. If it is an input element like input, textarea etc, it skips the translation, or if a standard mouse event is attached to it it will also skip a translation.

Result: Every element on a draggable element is still working.

Happy coding, greetz, Erwin Haantjes

How to find out line-endings in a text file?

In vi...

:set list to see line-endings.

:set nolist to go back to normal.

While I don't think you can see \n or \r\n in vi, you can see which type of file it is (UNIX, DOS, etc.) to infer which line endings it has...

:set ff

Alternatively, from bash you can use od -t c <filename> or just od -c <filename> to display the returns.

Action Bar's onClick listener for the Home button

you should to delete your the Override onOptionsItemSelected and replate your onCreateOptionsMenu with this code

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_action_bar_finish_order_stop, menu);
        menu.getItem(0).setOnMenuItemClickListener(new FinishOrderStopListener(this, getApplication(), selectedChild));
        return true;

    }

Subset a dataframe by multiple factor levels

You can use %in%

  data[data$Code %in% selected,]
  Code Value
1    A     1
2    B     2
7    A     3
8    A     4

How to get input from user at runtime

you can try this too And it will work:

DECLARE
  a NUMBER;
  b NUMBER;
BEGIN
  a :=: a; --this will take input from user
  b :=: b;
  DBMS_OUTPUT.PUT_LINE('a = '|| a);
  DBMS_OUTPUT.PUT_LINE('b = '|| b);
END;

Get Application Name/ Label via ADB Shell or Terminal

If you know the app id of the package (like org.mozilla.firefox), it is easy. First to get the path of actual package file of the appId,

$  adb shell pm list packages -f com.google.android.apps.inbox
package:/data/app/com.google.android.apps.inbox-1/base.apk=com.google.android.apps.inbox

Now you can do some grep|sed magic to extract the path : /data/app/com.google.android.apps.inbox-1/base.apk

After that aapt tool comes in handy :

$  adb shell aapt dump badging /data/app/com.google.android.apps.inbox-1/base.apk
...
application-label:'Inbox'
application-label-hi:'Inbox'
application-label-ru:'Inbox'
...

Again some grep magic to get the Label.

PHP/MySQL Insert null values

I think you need quotes around your {$row['null_field']}, so '{$row['null_field']}'

If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',) which is a syntax error.

If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..

iOS 7 - Failing to instantiate default view controller

If you have been committing your code to source control regularly, this may save you the hassle of creating a new Storyboard and possibly introducing more problems...

I was able to solve this by comparing the Git source code of the version that worked against the broken one. The diff showed that the first line should contain the Id of the initial view controller, in my case, initialViewController="Q7U-eo-vxw". I searched through the source code to be sure that the id existed. All I had to do was put it back and everything worked again!

<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="5056" systemVersion="13E28" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" initialViewController="Q7U-eo-vxw">
    <dependencies>
        <deployment defaultVersion="1296" identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="3733"/>
    </dependencies>
    <scenes>

Here are some steps that can help you troubleshoot:

  1. Right click the failing Storyboard and use Source Control > Commit... to preserve your changes since the last commit.
  2. Try right clicking your failing Storyboard and use "Open As > Source Code" to view the XML of the storyboard.
  3. In the document element, look for the attribute named "initialViewController". If it is missing, don't worry, we'll fix that. If it is there, double click the id that is assigned to it, command-c to copy it, command-f command-v to search for it deeper in the document. This is the identifier of the controller that should provide the initial view. If it is not defined in the document then that is a problem - you should remove it from the document tag, in my case initialViewController="Q7U-eo-vxw".
  4. Go to Xcode menu item called View and choose Version Editor > Show Comparison View
  5. This shows your local version on the left and the historical version on the right. Click on the date beneath the historical version to get a list of the commits for this story board. Choose one that you know worked and compare the document element. What is the id of the *initialViewController? Is it different? If so, try editing it back in by hand and running. xcode historical compare tool in action

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I've faced this error, That was because the value you want to filter in the _id field is not in an ID format, one "if" should solve your error.

const mongoose = require('mongoose');

console.log(mongoose.Types.ObjectId.isValid('53cb6b9b4f4ddef1ad47f943'));
// true
console.log(mongoose.Types.ObjectId.isValid('whatever'));
// false

To solve it, always validate if the criteria value for search is a valid ObjectId

const criteria = {};
criteria.$or = [];

if(params.q) {
  if(mongoose.Types.ObjectId.isValid(params.id)) {
    criteria.$or.push({ _id: params.q })
  }
  criteria.$or.push({ name: { $regex: params.q, $options: 'i' }})
  criteria.$or.push({ email: { $regex: params.q, $options: 'i' }})
  criteria.$or.push({ password: { $regex: params.q, $options: 'i' }})
}

return UserModule.find(criteria).exec(() => {
  // do stuff
})

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

Yes, __attribute__((packed)) is potentially unsafe on some systems. The symptom probably won't show up on an x86, which just makes the problem more insidious; testing on x86 systems won't reveal the problem. (On the x86, misaligned accesses are handled in hardware; if you dereference an int* pointer that points to an odd address, it will be a little slower than if it were properly aligned, but you'll get the correct result.)

On some other systems, such as SPARC, attempting to access a misaligned int object causes a bus error, crashing the program.

There have also been systems where a misaligned access quietly ignores the low-order bits of the address, causing it to access the wrong chunk of memory.

Consider the following program:

#include <stdio.h>
#include <stddef.h>
int main(void)
{
    struct foo {
        char c;
        int x;
    } __attribute__((packed));
    struct foo arr[2] = { { 'a', 10 }, {'b', 20 } };
    int *p0 = &arr[0].x;
    int *p1 = &arr[1].x;
    printf("sizeof(struct foo)      = %d\n", (int)sizeof(struct foo));
    printf("offsetof(struct foo, c) = %d\n", (int)offsetof(struct foo, c));
    printf("offsetof(struct foo, x) = %d\n", (int)offsetof(struct foo, x));
    printf("arr[0].x = %d\n", arr[0].x);
    printf("arr[1].x = %d\n", arr[1].x);
    printf("p0 = %p\n", (void*)p0);
    printf("p1 = %p\n", (void*)p1);
    printf("*p0 = %d\n", *p0);
    printf("*p1 = %d\n", *p1);
    return 0;
}

On x86 Ubuntu with gcc 4.5.2, it produces the following output:

sizeof(struct foo)      = 5
offsetof(struct foo, c) = 0
offsetof(struct foo, x) = 1
arr[0].x = 10
arr[1].x = 20
p0 = 0xbffc104f
p1 = 0xbffc1054
*p0 = 10
*p1 = 20

On SPARC Solaris 9 with gcc 4.5.1, it produces the following:

sizeof(struct foo)      = 5
offsetof(struct foo, c) = 0
offsetof(struct foo, x) = 1
arr[0].x = 10
arr[1].x = 20
p0 = ffbff317
p1 = ffbff31c
Bus error

In both cases, the program is compiled with no extra options, just gcc packed.c -o packed.

(A program that uses a single struct rather than array doesn't reliably exhibit the problem, since the compiler can allocate the struct on an odd address so the x member is properly aligned. With an array of two struct foo objects, at least one or the other will have a misaligned x member.)

(In this case, p0 points to a misaligned address, because it points to a packed int member following a char member. p1 happens to be correctly aligned, since it points to the same member in the second element of the array, so there are two char objects preceding it -- and on SPARC Solaris the array arr appears to be allocated at an address that is even, but not a multiple of 4.)

When referring to the member x of a struct foo by name, the compiler knows that x is potentially misaligned, and will generate additional code to access it correctly.

Once the address of arr[0].x or arr[1].x has been stored in a pointer object, neither the compiler nor the running program knows that it points to a misaligned int object. It just assumes that it's properly aligned, resulting (on some systems) in a bus error or similar other failure.

Fixing this in gcc would, I believe, be impractical. A general solution would require, for each attempt to dereference a pointer to any type with non-trivial alignment requirements either (a) proving at compile time that the pointer doesn't point to a misaligned member of a packed struct, or (b) generating bulkier and slower code that can handle either aligned or misaligned objects.

I've submitted a gcc bug report. As I said, I don't believe it's practical to fix it, but the documentation should mention it (it currently doesn't).

UPDATE: As of 2018-12-20, this bug is marked as FIXED. The patch will appear in gcc 9 with the addition of a new -Waddress-of-packed-member option, enabled by default.

When address of packed member of struct or union is taken, it may result in an unaligned pointer value. This patch adds -Waddress-of-packed-member to check alignment at pointer assignment and warn unaligned address as well as unaligned pointer

I've just built that version of gcc from source. For the above program, it produces these diagnostics:

c.c: In function ‘main’:
c.c:10:15: warning: taking address of packed member of ‘struct foo’ may result in an unaligned pointer value [-Waddress-of-packed-member]
   10 |     int *p0 = &arr[0].x;
      |               ^~~~~~~~~
c.c:11:15: warning: taking address of packed member of ‘struct foo’ may result in an unaligned pointer value [-Waddress-of-packed-member]
   11 |     int *p1 = &arr[1].x;
      |               ^~~~~~~~~

Eclipse does not highlight matching variables

Eclipse Toolbar > Windows > Preferences > General (Right side) > Editors (Right side) > Text Editors (Right side) > Annotations (Right side)

For Occurrences and Write Occurrences, make sure you DO have the 'Text as highlighted' option checked for all of them. See screenshot below:

enter image description here

enter image description here

enter image description here

Can't start hostednetwork

The hosted network won't start if there are other active wifi adapters.

Disable the others whilst you're starting the hosted network.

Font size relative to the user's screen resolution?

You can use em, %, px. But in combination with media-queries See this Link to learn about media-queries. Also, CSS3 have some new values for sizing things relative to the current viewport size: vw, vh, and vmin. See link about that.

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

You need to have the file /root/test/devenv/openstack-rhel/pom.xml

This file need to have the followings elements:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.openstack</groupId>
    <artifactId>openstack-rhel-rpms</artifactId>
    <version>2012.1-SNAPSHOT</version>
    <packaging>pom</packaging>
</project>

Ansible: Set variable to file content

You can use fetch module to copy files from remote hosts to local, and lookup module to read the content of fetched files.

Add table row in jQuery

I have tried the most upvoted one, but it did not work for me, but below works well.

$('#mytable tr').last().after('<tr><td></td></tr>');

Which will work even there is a tobdy there.

Displaying the build date

Add below to pre-build event command line:

echo %date% %time% > "$(ProjectDir)\Resources\BuildDate.txt"

Add this file as resource, now you have 'BuildDate' string in your resources.

After inserting the file into the Resource (as public text file), I accessed it via

string strCompTime = Properties.Resources.BuildDate;

To create resources, see How to create and use resources in .NET.

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

Minimal example

And just to make what Mizux said as a minimal example:

main_c.c

#include <stdio.h>

int main(void) {
    puts("hello");
}

main_cpp.cpp

#include <iostream>

int main(void) {
    std::cout << "hello" << std::endl;
}

Then, without any Makefile:

make CFLAGS='-g -O3' \
     CXXFLAGS='-ggdb3 -O0' \
     CPPFLAGS='-DX=1 -DY=2' \
     CCFLAGS='--asdf' \
     main_c \
     main_cpp

runs:

cc -g -O3 -DX=1 -DY=2   main_c.c   -o main_c
g++ -ggdb3 -O0 -DX=1 -DY=2   main_cpp.cpp   -o main_cpp

So we understand that:

  • make had implicit rules to make main_c and main_cpp from main_c.c and main_cpp.cpp
  • CFLAGS and CPPFLAGS were used as part of the implicit rule for .c compilation
  • CXXFLAGS and CPPFLAGS were used as part of the implicit rule for .cpp compilation
  • CCFLAGS is not used

Those variables are only used in make's implicit rules automatically: if compilation had used our own explicit rules, then we would have to explicitly use those variables as in:

main_c: main_c.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $<

main_cpp: main_c.c
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $@ $<

to achieve a similar affect to the implicit rules.

We could also name those variables however we want: but since Make already treats them magically in the implicit rules, those make good name choices.

Tested in Ubuntu 16.04, GNU Make 4.1.

Reading string from input with space character?

Try this:

scanf("%[^\n]s",name);

\n just sets the delimiter for the scanned string.

How to get a list of all files in Cloud Storage in a Firebase app?

#In Python

import firebase_admin
from firebase_admin import credentials
from firebase_admin import storage
import datetime
import urllib.request


def image_download(url, name_img) :
    urllib.request.urlretrieve(url, name_img)

cred = credentials.Certificate("credentials.json")

# Initialize the app with a service account, granting admin privileges
app = firebase_admin.initialize_app(cred, {
    'storageBucket': 'YOURSTORAGEBUCKETNAME.appspot.com',
})
url_img = "gs://YOURSTORAGEBUCKETNAME.appspot.com/"
bucket_1 = storage.bucket(app=app)
image_urls = []

for blob in bucket_1.list_blobs():
    name = str(blob.name)
    #print(name)
    blob_img = bucket_1.blob(name)
    X_url = blob_img.generate_signed_url(datetime.timedelta(seconds = 300), method='GET')
    #print(X_url)
    image_urls.append(X_url)


PATH = ['Where you want to save the image']
for path in PATH:
    i = 1
    for url  in image_urls:
        name_img = str(path + "image"+str(i)+".jpg")
        image_download(url, name_img)
        i+=1

nodejs - How to read and output jpg image?

Two things to keep in mind Content-Type and the Encoding

1) What if the file is css

if (/.(css)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'text/css'}); 
  res.write(data, 'utf8');
} 

2) What if the file is jpg/png

if (/.(jpg)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'image/jpg'});
  res.end(data,'Base64');
}

Above one is just a sample code to explain the answer and not the exact code pattern.

You don't have write permissions for the /var/lib/gems/2.3.0 directory

(January 2019) To install Ruby using the Rbenv script, follow these steps:

1. First, update the packages index and install the packages required for the ruby-build tool to build Ruby from source:

sudo apt-get remove ruby
sudo apt update
sudo apt install git curl libssl-dev libreadline-dev zlib1g-dev autoconf bison build-essential libyaml-dev libreadline-dev libncurses5-dev libffi-dev libgdbm-dev

2. Next, run the following curl command to install both rbenv and ruby-build:

curl -sL https://github.com/rbenv/rbenv-installer/raw/master/bin/rbenv-installer | bash -

3. Add $HOME/.rbenv/bin to the system PATH.

If you are using Bash, run:

echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
source ~/.bashrc

If you are using Zsh run:

echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(rbenv init -)"' >> ~/.zshrc
source ~/.zshrc

4. Install the latest stable version of Ruby and set it as a default version with:

rbenv install 2.5.1
rbenv global 2.5.1

To list all available Ruby versions you can use: rbenv install -l

5. Verify that Ruby was properly installed by printing out the version number:

ruby -v

# Output
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]

SOURCE: How To Install Ruby on Ubuntu 18.04

EDIT: Install rubygems:

sudo apt-get install rubygems

Detect changed input text box

WORKING:

$("#ContentPlaceHolder1_txtNombre").keyup(function () {
    var txt = $(this).val();
        $('.column').each(function () {
            $(this).show();
            if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) == -1) {
                $(this).hide();
            }
        });
    //}
});

Split String by delimiter position using oracle SQL

Therefore, I would like to separate the string by the furthest delimiter.

I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.

SQL> WITH DATA AS
  2    ( SELECT 'F/P/O' str FROM dual
  3    )
  4  SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
  5         SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
  6  FROM DATA
  7  /

PART1 PART2
----- -----
F/P   O

As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.

You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.

find difference between two text files with one item per line

if you are expecting them in a certain order, you can just use diff

diff file1 file2 | grep ">"

Ansible - Use default if a variable is not defined

If you are assigning default value for boolean fact then ensure that no quotes is used inside default().

- name: create bool default
  set_fact:
    name: "{{ my_bool | default(true) }}"

For other variables used the same method given in verified answer.

- name: Create user
  user:
    name: "{{ my_variable | default('default_value') }}"

Scatter plots in Pandas/Pyplot: How to plot by category

With plt.scatter, I can only think of one: to use a proxy artist:

df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three'))
df['key1'] = (4,4,4,6,6,6,8,8,8,8)
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
x=ax1.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)

ccm=x.get_cmap()
circles=[Line2D(range(1), range(1), color='w', marker='o', markersize=10, markerfacecolor=item) for item in ccm((array([4,6,8])-4.0)/4)]
leg = plt.legend(circles, ['4','6','8'], loc = "center left", bbox_to_anchor = (1, 0.5), numpoints = 1)

And the result is:

enter image description here

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

Bootstrap 3 Glyphicons CDN

With the recent release of bootstrap 3, and the glyphicons being merged back to the main Bootstrap repo, Bootstrap CDN is now serving the complete Bootstrap 3.0 css including Glyphicons. The Bootstrap css reference is all you need to include: Glyphicons and its dependencies are on relative paths on the CDN site and are referenced in bootstrap.min.css.

In html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

In css:

 @import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css");

Here is a working demo.

Note that you have to use .glyphicon classes instead of .icon:

Example:

<span class="glyphicon glyphicon-heart"></span>

Also note that you would still need to include bootstrap.min.js for usage of Bootstrap JavaScript components, see Bootstrap CDN for url.


If you want to use the Glyphicons separately, you can do that by directly referencing the Glyphicons css on Bootstrap CDN.

In html:

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

In css:

@import url("//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css");

Since the css file already includes all the needed Glyphicons dependencies (which are in a relative path on the Bootstrap CDN site), adding the css file is all there is to do to start using Glyphicons.

Here is a working demo of the Glyphicons without Bootstrap.

How does Go update third-party packages?

Since the question mentioned third-party libraries and not all packages then you probably want to fall back to using wildcards.

A use case being: I just want to update all my packages that are obtained from the Github VCS, then you would just say:

go get -u github.com/... // ('...' being the wildcard). 

This would go ahead and only update your github packages in the current $GOPATH

Same applies for within a VCS too, say you want to only upgrade all the packages from ogranizaiton A's repo's since as they have released a hotfix you depend on:

go get -u github.com/orgA/...

JQuery Ajax Post results in 500 Internal Server Error

You can look up HTTP status codes here (or here), this error is telling you:

"The server encountered an unexpected condition which prevented it from fulfilling the request."

You need to debug your server.

How to check for a JSON response using RSpec?

A lot of the above answers are a bit out of date, so this is a quick summary for a more recent version of RSpec (3.8+). This solution raises no warnings from rubocop-rspec and is inline with rspec best practices:

A successful JSON response is identified by two things:

  1. The content type of the response is application/json
  2. The body of the response can be parsed without errors

Assuming that the response object is the anonymous subject of the test, both of the above conditions can be validate using Rspec's built in matchers:

context 'when response is received' do
  subject { response }

  # check for a successful JSON response
  it { is_expected.to have_attributes(content_type: include('application/json')) }
  it { is_expected.to have_attributes(body: satisfy { |v| JSON.parse(v) }) }

  # validates OP's condition
  it { is_expected.to satisfy { |v| JSON.parse(v.body).key?('success') }
  it { is_expected.to satisfy { |v| JSON.parse(v.body)['success'] == true }
end

If you're prepared to name your subject then the above tests can be simplified further:

context 'when response is received' do
  subject(:response) { response }

  it 'responds with a valid content type' do
    expect(response.content_type).to include('application/json')
  end

  it 'responds with a valid json object' do
    expect { JSON.parse(response.body) }.not_to raise_error
  end

  it 'validates OPs condition' do
    expect(JSON.parse(response.body, symoblize_names: true))
      .to include(success: true)
  end
end

CSS /JS to prevent dragging of ghost image?

You can set the draggable attribute to false in either the markup or JavaScript code.

_x000D_
_x000D_
// As a jQuery method: $('#myImage').attr('draggable', false);_x000D_
document.getElementById('myImage').setAttribute('draggable', false);
_x000D_
<img id="myImage" src="http://placehold.it/150x150">
_x000D_
_x000D_
_x000D_

Flexbox: center horizontally and vertically

You can make use of

display: flex;
align-items: center;
justify-content: center;

on your parent component

enter image description here

How to get the separate digits of an int number?

Here is my answer, I did it for myself and I hope it's simple enough for those who don't want to use the String approach or need a more math-y solution:

public static void reverseNumber2(int number) {

    int residual=0;
    residual=number%10;
    System.out.println(residual);

    while (residual!=number)  {
          number=(number-residual)/10;
          residual=number%10;
          System.out.println(residual);
    }
}

So I just get the units, print them out, substract them from the number, then divide that number by 10 - which is always without any floating stuff, since units are gone, repeat.

Swing/Java: How to use the getText and setText string properly

You are setting the label text before the button is clicked to "txt". Instead when the button is clicked call setText() on the label and pass it the text from the text field.

Example:

label1.setText(nameField.getText()); 

Prevent redirect after form is submitted

Probably you will have to do just an Ajax request to your page. And doing return false there is doing not what you think it is doing.

Image.open() cannot identify image file - Python?

In my case the image file had just been written to and needed to be flushed before opening, like so:

img_file.flush() 
img = Image.open(img_file.name))

delete map[key] in go?

Use make (chan int) instead of nil. The first value has to be the same type that your map holds.

package main

import "fmt"

func main() {

    var sessions = map[string] chan int{}
    sessions["somekey"] = make(chan int)

    fmt.Printf ("%d\n", len(sessions)) // 1

    // Remove somekey's value from sessions
    delete(sessions, "somekey")

    fmt.Printf ("%d\n", len(sessions)) // 0
}

UPDATE: Corrected my answer.

Python: Find index of minimum item in list of floats

I think it's worth putting a few timings up here for some perspective.

All timings done on OS-X 10.5.8 with python2.7

John Clement's answer:

python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop    

David Wolever's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop

OP's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop

Note that I'm purposefully putting the smallest item last in the list to make .index as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.

Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This happens when you index a row/column with a number that is larger than the dimensions of your dataframe. For instance, getting the eleventh column when you have only three.

import pandas as pd

df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
                   'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
                   'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})

You have 5 rows and three columns:

    Name      City      Car
0   Mark    Lisbon    Tesla
1  Laura  Montreal     Audi
2   Adam    Lisbon  Porsche
3  Roger    Berlin     Ford
4   Anna   Glasgow    Honda

Let's try to index the eleventh column (it doesn't exist):

df.iloc[:, 10] # there is obviously no 11th column

IndexError: single positional indexer is out-of-bounds

If you are a beginner with Python, remember that df.iloc[:, 10] would refer to the eleventh column.

How to avoid a System.Runtime.InteropServices.COMException?

Probably you are trying to access the excel with the index 0, please note that Excel rows/columns start from 1.

Android Gradle Apache HttpClient does not exist?

In my case, I updated one of my libraries in my android project.

I'm using Reservoir as my cache storage solution: https://github.com/anupcowkur/Reservoir

I went from:

compile 'com.anupcowkur:reservoir:2.1'

To:

compile 'com.anupcowkur:reservoir:3.1.0'

The library author must have removed the commons-io library from the repo so my app no longer worked.

I had to manually include the commons-io by adding this onto gradle:

compile 'commons-io:commons-io:2.5'

https://mvnrepository.com/artifact/commons-io/commons-io/2.5

Eclipse Bug: Unhandled event loop exception No more handles

I found now 2 ways to work with eclipse without getting “SWTError: No more handles” on my Dell ProBook 6550b Windows 7 64 bit but none of them is really satisfying: I can start windows in “secure mode” or I can downgrade to “eclipse-jee-indigo-SR2-win32-x86_64”. I will now try to kill one process after the other until kepler starts working respective until I arrive in secure mode.

... and then a few hours later ...

Finally (for now) I could solve the issue (at least on my laptop: Dell ProBook 6550b Windows 7 64). I “just” had to kill the processes: “DPAgent.exe*32” (DigitalPersona Local Agent) & “DPAgent.exe” (DigitalPersona 64-bit Helper Process) which were luckily running under my user (and not SYSTEM which might have made it impossible to kill depending on your rights). Nevertheless I don't understand how these processes can interfere with SWT handles in eclipse ....

More information on this issue can as well be found here: https://bugs.eclipse.org/bugs/show_bug.cgi?id=402983

How to download PDF automatically using js?

/* Helper function */
function download_file(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
    var save = document.createElement('a');
    save.href = fileURL;
    save.target = '_blank';
    var filename = fileURL.substring(fileURL.lastIndexOf('/')+1);
    save.download = fileName || filename;
       if ( navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) && navigator.userAgent.search("Chrome") < 0) {
            document.location = save.href; 
// window event not working here
        }else{
            var evt = new MouseEvent('click', {
                'view': window,
                'bubbles': true,
                'cancelable': false
            });
            save.dispatchEvent(evt);
            (window.URL || window.webkitURL).revokeObjectURL(save.href);
        }   
}

// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand)     {
    var _window = window.open(fileURL, '_blank');
    _window.document.close();
    _window.document.execCommand('SaveAs', true, fileName || fileURL)
    _window.close();
}
}

How to use?

download_file(fileURL, fileName); //call function

Source: convertplug.com/plus/docs/download-pdf-file-forcefully-instead-opening-browser-using-js/

Initializing select with AngularJS and ng-repeat

If you are using md-select and ng-repeat ing md-option from angular material then you can add ng-model-options="{trackBy: '$value.id'}" to the md-select tag ash shown in this pen

Code:

_x000D_
_x000D_
<md-select ng-model="user" style="min-width: 200px;" ng-model-options="{trackBy: '$value.id'}">_x000D_
  <md-select-label>{{ user ? user.name : 'Assign to user' }}</md-select-label>_x000D_
  <md-option ng-value="user" ng-repeat="user in users">{{user.name}}</md-option>_x000D_
</md-select>
_x000D_
_x000D_
_x000D_

Get the item doubleclick event of listview

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <EventSetter Event="MouseDoubleClick" Handler="listViewItem_MouseDoubleClick" />
    </Style>
</ListView.ItemContainerStyle>

The only difficulty then is if you are interested in the underlying object the listviewitem maps to e.g.

private void listViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    ListViewItem item = sender as ListViewItem;
    object obj = item.Content;
}

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

How to stop a JavaScript for loop?

To stop a for loop early in JavaScript, you use break:

var remSize = [], 
    szString,
    remData,
    remIndex,
    i;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {      
     // I'm looking for the index i, when the condition is true
     if (remSize[i].size === remData.size) {
          remIndex = i;
          break;       // <=== breaks out of the loop early
     }
}

If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array#findIndex (to find the entry's index) or Array#find (to find the entry itself), both of which can be shimmed/polyfilled:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = remSize.findIndex(function(entry) {
     return entry.size === remData.size;
});

Array#find:

var remSize = [], 
    szString,
    remData,
    remEntry;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remEntry = remSize.find(function(entry) {
     return entry.size === remData.size;
});

Array#findIndex stops the first time the callback returns a truthy value, returning the index for that call to the callback; it returns -1 if the callback never returns a truthy value. Array#find also stops when it finds what you're looking for, but it returns the entry, not its index (or undefined if the callback never returns a truthy value).

If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some function on arrays, which calls a callback until the callback returns a truthy value:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
    if (entry.size === remData.size) {
        remIndex = index;
        return true; // <== Equivalent of break for `Array#some`
    }
});

If you're using jQuery, you can use jQuery.each to loop through an array; that would look like this:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
    if (entry.size === remData.size) {
        remIndex = index;
        return false; // <== Equivalent of break for jQuery.each
    }
});

jQuery check if an input is type checkbox?

A non-jQuery solution is much like a jQuery solution:

document.querySelector('#myinput').getAttribute('type') === 'checkbox'

Insert data into hive table

If table is without partition then code will be,

Insert into table table_name select col_a,col_b,col_c from another_table(source table)

--here any condition can be applied such as limit, group by, order by etc...

If table is with partitions then code will be,

set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;

insert into table table_name partition(partition_col1, paritition_col2) select col_a,col_b,col_c,partition_col1,partition_col2 from another_table(source table)

--here any condition can be applied such as limit, group by, order by etc...

using batch echo with special characters

Here's one more approach by using SET and FOR /F

@echo off

set "var=<?xml version="1.0" encoding="utf-8" ?>"

for /f "tokens=1* delims==" %%a in ('set var') do echo %%b

and you can beautify it like:

@echo off
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "print{[=for /f "tokens=1* delims==" %%a in ('set " & set "]}=') do echo %%b"
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


set "xml_line.1=<?xml version="1.0" encoding="utf-8" ?>"
set "xml_line.2=<root>"
set "xml_line.3=</root>"

%print{[% xml_line %]}%

How do I set up IntelliJ IDEA for Android applications?

You just need to install Android development kit from http://developer.android.com/sdk/installing/studio.html#Updating

and also Download and install Java JDK (Choose the Java platform)

define the environment variable in windows System setting https://confluence.atlassian.com/display/DOC/Setting+the+JAVA_HOME+Variable+in+Windows

Voila ! You are Donezo !

Heap space out of memory

Are you keeping references to variables that you no longer need (e.g. data from the previous simulations)? If so, you have a memory leak. You just need to find where that is happening and make sure that you remove the references to the variables when they are no longer needed (this would automatically happen if they go out of scope).

If you actually need all that data from previous simulations in memory, you need to increase the heap size or change your algorithm.

Sorting by date & time in descending order?

putting the UNIX_TIMESTAMP will do the trick.

SELECT id, NAME, form_id, UNIX_TIMESTAMP(updated_at) AS DATE
    FROM wp_frm_items
    WHERE user_id = 11 && form_id=9
    ORDER BY DATE DESC

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

The fundamental misunderstanding here is in thinking that range is a generator. It's not. In fact, it's not any kind of iterator.

You can tell this pretty easily:

>>> a = range(5)
>>> print(list(a))
[0, 1, 2, 3, 4]
>>> print(list(a))
[0, 1, 2, 3, 4]

If it were a generator, iterating it once would exhaust it:

>>> b = my_crappy_range(5)
>>> print(list(b))
[0, 1, 2, 3, 4]
>>> print(list(b))
[]

What range actually is, is a sequence, just like a list. You can even test this:

>>> import collections.abc
>>> isinstance(a, collections.abc.Sequence)
True

This means it has to follow all the rules of being a sequence:

>>> a[3]         # indexable
3
>>> len(a)       # sized
5
>>> 3 in a       # membership
True
>>> reversed(a)  # reversible
<range_iterator at 0x101cd2360>
>>> a.index(3)   # implements 'index'
3
>>> a.count(3)   # implements 'count'
1

The difference between a range and a list is that a range is a lazy or dynamic sequence; it doesn't remember all of its values, it just remembers its start, stop, and step, and creates the values on demand on __getitem__.

(As a side note, if you print(iter(a)), you'll notice that range uses the same listiterator type as list. How does that work? A listiterator doesn't use anything special about list except for the fact that it provides a C implementation of __getitem__, so it works fine for range too.)


Now, there's nothing that says that Sequence.__contains__ has to be constant time—in fact, for obvious examples of sequences like list, it isn't. But there's nothing that says it can't be. And it's easier to implement range.__contains__ to just check it mathematically ((val - start) % step, but with some extra complexity to deal with negative steps) than to actually generate and test all the values, so why shouldn't it do it the better way?

But there doesn't seem to be anything in the language that guarantees this will happen. As Ashwini Chaudhari points out, if you give it a non-integral value, instead of converting to integer and doing the mathematical test, it will fall back to iterating all the values and comparing them one by one. And just because CPython 3.2+ and PyPy 3.x versions happen to contain this optimization, and it's an obvious good idea and easy to do, there's no reason that IronPython or NewKickAssPython 3.x couldn't leave it out. (And in fact CPython 3.0-3.1 didn't include it.)


If range actually were a generator, like my_crappy_range, then it wouldn't make sense to test __contains__ this way, or at least the way it makes sense wouldn't be obvious. If you'd already iterated the first 3 values, is 1 still in the generator? Should testing for 1 cause it to iterate and consume all the values up to 1 (or up to the first value >= 1)?

How do I get the max ID with Linq to Entity?

Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();

Why is this error, 'Sequence contains no elements', happening?

Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:

.Where(y => y.ResponseId.Equals(item.ResponseId))

so you can't call

.First()

on it. Maybe try

.FirstOrDefault()

if it solves the issue.

Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.

React Native fixed footer

Simple stuff here:

Incase you don't need a ScrollView for this approach you can go with the below code to achieve Something like this :

Something like this

<View style={{flex: 1, backgroundColor:'grey'}}>
    <View style={{flex: 1, backgroundColor: 'red'}} />
    <View style={{height: 100, backgroundColor: 'green'}} />
</View>

Regular expression to match exact number of characters?

Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:

^([A-Z]{3})$

The {3} indicates that the [A-Z] must appear exactly 3 times.

Inserting the same value multiple times when formatting a string

>>> s1 ='arbit'
>>> s2 = 'hello world '.join( [s]*3 )
>>> print s2
arbit hello world arbit hello world arbit

How to return a value from pthread threads in C?

Question : What is the best practice of returning/storing variables of multiple threads? A global hash table?

This totally depends on what you want to return and how you would use it? If you want to return only status of the thread (say whether the thread completed what it intended to do) then just use pthread_exit or use a return statement to return the value from the thread function.

But, if you want some more information which will be used for further processing then you can use global data structure. But, in that case you need to handle concurrency issues by using appropriate synchronization primitives. Or you can allocate some dynamic memory (preferrably for the structure in which you want to store the data) and send it via pthread_exit and once the thread joins, you update it in another global structure. In this way only the one main thread will update the global structure and concurrency issues are resolved. But, you need to make sure to free all the memory allocated by different threads.

Jupyter/IPython Notebooks: Shortcut for "run all"?

Easiest solution:

Esc, Ctrl-A, Shift-Enter.

pyplot scatter plot marker size

I also attempted to use 'scatter' initially for this purpose. After quite a bit of wasted time - I settled on the following solution.

import matplotlib.pyplot as plt
input_list = [{'x':100,'y':200,'radius':50, 'color':(0.1,0.2,0.3)}]    
output_list = []   
for point in input_list:
    output_list.append(plt.Circle((point['x'], point['y']), point['radius'], color=point['color'], fill=False))
ax = plt.gca(aspect='equal')
ax.cla()
ax.set_xlim((0, 1000))
ax.set_ylim((0, 1000))
for circle in output_list:    
   ax.add_artist(circle)

enter image description here

This is based on an answer to this question

How can I remove the extension of a filename in a shell script?

You should be using the command substitution syntax $(command) when you want to execute a command in script/command.

So your line would be

name=$(echo "$filename" | cut -f 1 -d '.')

Code explanation:

  1. echo get the value of the variable $filename and send it to standard output
  2. We then grab the output and pipe it to the cut command
  3. The cut will use the . as delimiter (also known as separator) for cutting the string into segments and by -f we select which segment we want to have in output
  4. Then the $() command substitution will get the output and return its value
  5. The returned value will be assigned to the variable named name

Note that this gives the portion of the variable up to the first period .:

$ filename=hello.world
$ echo "$filename" | cut -f 1 -d '.'
hello
$ filename=hello.hello.hello
$ echo "$filename" | cut -f 1 -d '.'
hello
$ filename=hello
$ echo "$filename" | cut -f 1 -d '.'
hello

How to calculate an age based on a birthday?

Another clever way from that ancient thread:

int age = (
    Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
    Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;

Vertically align text next to an image?

Because you have to set the line-height to the height of the div for this to work

Correct way to read a text file into a buffer in C?

Have you considered mmap()? You can read from the file directly as if it were already in memory.

http://beej.us/guide/bgipc/output/html/multipage/mmap.html

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

docker: "build" requires 1 argument. See 'docker build --help'

In case anyone is running into this problem when trying to tag -t the image and also build it from a file that is NOT named Dockerfile (i.e. not using simply the . path), you can do it like this:

docker build -t my_image -f my_dockerfile .

Notice that docker expects a directory as the parameter and the filename as an option.

Change visibility of ASP.NET label with JavaScript

Continuing with what Dave Ward said:

  • You can't set the Visible property to false because the control will not be rendered.
  • You should use the Style property to set it's display to none.

Page/Control design

<asp:Label runat="server" ID="Label1" Style="display: none;" />

<asp:Button runat="server" ID="Button1" />

Code behind

Somewhere in the load section:

Label label1 = (Label)FindControl("Label1");
((Label)FindControl("Button1")).OnClientClick = "ToggleVisibility('" + label1.ClientID + "')";

Javascript file

function ToggleVisibility(elementID)
{
    var element = document.getElementByID(elementID);

    if (element.style.display = 'none')
    {
        element.style.display = 'inherit';
    }
    else
    {
        element.style.display = 'none';
    }
}

Of course, if you don't want to toggle but just to show the button/label then adjust the javascript method accordingly.

The important point here is that you need to send the information about the ClientID of the control that you want to manipulate on the client side to the javascript file either setting global variables or through a function parameter as in my example.

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

Get data type of field in select statement in ORACLE

I usually create a view and use the DESC command:

CREATE VIEW tmp_view AS 
SELECT 
      a.name
    , a.surname
    , b.ordernum 
FROM customer a
  JOIN orders b
    ON a.id = b.id

Then, the DESC command will show the type of each field.

DESC tmp_view

Anchor links in Angularjs?

There are a few ways to do this it seems.

Option 1: Native Angular

Angular provides an $anchorScroll service, but the documentation is severely lacking and I've not been able to get it to work.

Check out http://www.benlesh.com/2013/02/angular-js-scrolling-to-element-by-id.html for some insight into $anchorScroll.

Option 2: Custom Directive / Native JavaScript

Another way I tested out was creating a custom directive and using el.scrollIntoView(). This works pretty decently by basically doing the following in your directive link function:

var el = document.getElementById(attrs.href);
el.scrollIntoView();

However, it seems a bit overblown to do both of these when the browser natively supports this, right?

Option 3: Angular Override / Native Browser

If you take a look at http://docs.angularjs.org/guide/dev_guide.services.$location and its HTML Link Rewriting section, you'll see that links are not rewritten in the following:

Links that contain target element

Example: <a href="/ext/link?a=b" target="_self">link</a>

So, all you have to do is add the target attribute to your links, like so:

<a href="#anchorLinkID" target="_self">Go to inpage section</a>

Angular defaults to the browser and since its an anchor link and not a different base url, the browser scrolls to the correct location, as desired.

I went with option 3 because its best to rely on native browser functionality here, and saves us time and effort.

Gotta note that after a successful scroll and hash change, Angular does follow up and rewrite the hash to its custom style. However, the browser has already completed its business and you are good to go.

Is it not possible to stringify an Error using JSON.stringify?

JSON.stringify(err, Object.getOwnPropertyNames(err))

seems to work

[from a comment by /u/ub3rgeek on /r/javascript] and felixfbecker's comment below

Setting focus to iframe contents

I discovered that FF triggers the focus event for iframe.contentWindow but not for iframe.contentWindow.document. Chrome for example can handle both cases. so, I just needed to bind my event handlers to iframe.contentWindow in order to get things working. Maybe this helps somebody ...

CSS: background-color only inside the margin

If your margin is set on the body, then setting the background color of the html tag should color the margin area

html { background-color: black; }
body { margin:50px; background-color: white; }

http://jsfiddle.net/m3zzb/

Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color

UINavigationBar custom back button without title

Create a UILabel with the title you want for your root view controller and assign it to the view controller's navigationItem.titleView.

Now set the title to an empty string and the next view controller you push will have a back button without text.

self.navigationItem.titleView = titleLabel; //Assuming you've created titleLabel above
self.title = @"";

How do I use Docker environment variable in ENTRYPOINT array?

I tried to resolve with the suggested answer and still ran into some issues...

This was a solution to my problem:

ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}

# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh

# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]

Specifically targeting your problem:

RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]

Excel: last character/string match in a string

Just came up with this solution, no VBA needed;

Find the last occurance of "_" in my example;

=IFERROR(FIND(CHAR(1);SUBSTITUTE(A1;"_";CHAR(1);LEN(A1)-LEN(SUBSTITUTE(A1;"_";"")));0)

Explained inside out;

SUBSTITUTE(A1;"_";"") => replace "_" by spaces
LEN( *above* ) => count the chars
LEN(A1)- *above*  => indicates amount of chars replaced (= occurrences of "_")
SUBSTITUTE(A1;"_";CHAR(1); *above* ) => replace the Nth occurence of "_" by CHAR(1) (Nth = amount of chars replaced = the last one)
FIND(CHAR(1); *above* ) => Find the CHAR(1), being the last (replaced) occurance of "_" in our case
IFERROR( *above* ;"0") => in case no chars were found, return "0"

Hope this was helpful.

How to switch a user per task or set of tasks?

A solution is to use the include statement with remote_user var (describe there : http://docs.ansible.com/playbooks_roles.html) but it has to be done at playbook instead of task level.

Is it necessary to use # for creating temp tables in SQL server?

Yes. You need to prefix the table name with "#" (hash) to create temporary tables.

If you do NOT need the table later, go ahead & create it. Temporary Tables are very much like normal tables. However, it gets created in tempdb. Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.

"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.

Refer the below link for the Basics of Temporary Tables: http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005

If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.

They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.

DECLARE @ItemBack1 TABLE
(
 column1 int,
 column2 int,
 someInt int,
 someVarChar nvarchar(50)
);

INSERT INTO @ItemBack1
SELECT column1, 
       column2, 
       someInt, 
       someVarChar 
  FROM table2
 WHERE table2.ID = 7;

More Info on Table Variables: http://odetocode.com/articles/365.aspx

How to comment/uncomment in HTML code

My view templates are generally .php files. This is what I would be using for now.

<?php // Some comment here ?>

The solution is quite similar to what @Robert suggested, works for me. Is not very clean I guess.

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

How to get First and Last record from a sql query?

How to get the First and Last Record of DB in c#.

SELECT TOP 1 * 
  FROM ViewAttendenceReport 
 WHERE EmployeeId = 4 
   AND AttendenceDate >='1/18/2020 00:00:00' 
   AND AttendenceDate <='1/18/2020 23:59:59'
 ORDER BY Intime ASC
 UNION
SELECT TOP 1 * 
  FROM ViewAttendenceReport 
 WHERE EmployeeId = 4 
   AND AttendenceDate >='1/18/2020 00:00:00' 
   AND AttendenceDate <='1/18/2020 23:59:59' 
 ORDER BY OutTime DESC; 

Converting unix timestamp string to readable date

You can use easy_date to make it easy:

import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")

Wait for a process to finish

There's no builtin. Use kill -0 in a loop for a workable solution:

anywait(){

    for pid in "$@"; do
        while kill -0 "$pid"; do
            sleep 0.5
        done
    done
}

Or as a simpler oneliner for easy one time usage:

while kill -0 PIDS 2> /dev/null; do sleep 1; done;

As noted by several commentators, if you want to wait for processes that you do not have the privilege to send signals to, you have find some other way to detect if the process is running to replace the kill -0 $pid call. On Linux, test -d "/proc/$pid" works, on other systems you might have to use pgrep (if available) or something like ps | grep "^$pid ".

Can I create links with 'target="_blank"' in Markdown?

For completed alex answered (Dec 13 '10)

A more smart injection target could be done with this code :

/*
 * For all links in the current page...
 */
$(document.links).filter(function() {
    /*
     * ...keep them without `target` already setted...
     */
    return !this.target;
}).filter(function() {
    /*
     * ...and keep them are not on current domain...
     */
    return this.hostname !== window.location.hostname ||
        /*
         * ...or are not a web file (.pdf, .jpg, .png, .js, .mp4, etc.).
         */
        /\.(?!html?|php3?|aspx?)([a-z]{0,3}|[a-zt]{0,4})$/.test(this.pathname);
/*
 * For all link kept, add the `target="_blank"` attribute. 
 */
}).attr('target', '_blank');

You could change the regexp exceptions with adding more extension in (?!html?|php3?|aspx?) group construct (understand this regexp here: https://regex101.com/r/sE6gT9/3).

and for a without jQuery version, check code below:

var links = document.links;
for (var i = 0; i < links.length; i++) {
    if (!links[i].target) {
        if (
            links[i].hostname !== window.location.hostname || 
            /\.(?!html?)([a-z]{0,3}|[a-zt]{0,4})$/.test(links[i].pathname)
        ) {
            links[i].target = '_blank';
        } 
    }
}

How to get first/top row of the table in Sqlite via Sql Query

LIMIT 1 is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order clause in an outer query).

implement addClass and removeClass functionality in angular2

Try to use it via [ngClass] property:

<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
         (click)="toggle(!isOn)">
         Click me!
     </div>`,

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

In my case, while setting up a Github action I just forgot to add the env variables to the yml file:

jobs:
  build:
    env:
     VAR1: 1
     VAR2: 5