Programs & Examples On #Rad controls

RadControls is a suite of UI controls (buttons, grids, menus, charts, windows, input controls, etc.) created by Telerik. There are version of the suite for ASP.Net WebForm, Silverlight, WPF, WinForms, Windows Phone and Android.

UIImage: Resize, then Crop

- (UIImage*)imageScale:(CGFloat)scaleFactor cropForSize:(CGSize)targetSize
{
    targetSize = !targetSize.width?self.size:targetSize;
    UIGraphicsBeginImageContext(targetSize); // this will crop

    CGRect thumbnailRect = CGRectZero;

    thumbnailRect.size.width  = targetSize.width*scaleFactor;
    thumbnailRect.size.height = targetSize.height*scaleFactor;
    CGFloat xOffset = (targetSize.width- thumbnailRect.size.width)/2;
    CGFloat yOffset = (targetSize.height- thumbnailRect.size.height)/2;
    thumbnailRect.origin = CGPointMake(xOffset,yOffset);

    [self drawInRect:thumbnailRect];

    UIImage *newImage  = UIGraphicsGetImageFromCurrentImageContext();

    if(newImage == nil)
    {
        NSLog(@"could not scale image");
    }

    UIGraphicsEndImageContext();

    return newImage;
}

Below the example of work: Left image - (origin image) ; Right image with scale x2

enter image description here

If you want to scale image but retain its frame(proportions), call method this way:

[yourImage imageScale:2.0f cropForSize:CGSizeZero];

Multiple select in Visual Studio?

Now the plugin is Multi Line tricks. The end and start buttons broke the selection.

How to cache data in a MVC application

public sealed class CacheManager
{
    private static volatile CacheManager instance;
    private static object syncRoot = new Object();
    private ObjectCache cache = null;
    private CacheItemPolicy defaultCacheItemPolicy = null;

    private CacheEntryRemovedCallback callback = null;
    private bool allowCache = true;

    private CacheManager()
    {
        cache = MemoryCache.Default;
        callback = new CacheEntryRemovedCallback(this.CachedItemRemovedCallback);

        defaultCacheItemPolicy = new CacheItemPolicy();
        defaultCacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddHours(1.0);
        defaultCacheItemPolicy.RemovedCallback = callback;
        allowCache = StringUtils.Str2Bool(ConfigurationManager.AppSettings["AllowCache"]); ;
    }
    public static CacheManager Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        instance = new CacheManager();
                    }
                }
            }

            return instance;
        }
    }

    public IEnumerable GetCache(String Key)
    {
        if (Key == null || !allowCache)
        {
            return null;
        }

        try
        {
            String Key_ = Key;
            if (cache.Contains(Key_))
            {
                return (IEnumerable)cache.Get(Key_);
            }
            else
            {
                return null;
            }
        }
        catch (Exception)
        {
            return null;
        }
    }

    public void ClearCache(string key)
    {
        AddCache(key, null);
    }

    public bool AddCache(String Key, IEnumerable data, CacheItemPolicy cacheItemPolicy = null)
    {
        if (!allowCache) return true;
        try
        {
            if (Key == null)
            {
                return false;
            }

            if (cacheItemPolicy == null)
            {
                cacheItemPolicy = defaultCacheItemPolicy;
            }

            String Key_ = Key;

            lock (Key_)
            {
                return cache.Add(Key_, data, cacheItemPolicy);
            }
        }
        catch (Exception)
        {
            return false;
        }
    }

    private void CachedItemRemovedCallback(CacheEntryRemovedArguments arguments)
    {
        String strLog = String.Concat("Reason: ", arguments.RemovedReason.ToString(), " | Key-Name: ", arguments.CacheItem.Key, " | Value-Object: ", arguments.CacheItem.Value.ToString());
        LogManager.Instance.Info(strLog);
    }
}

how get yesterday and tomorrow datetime in c#

Use DateTime.AddDays() (MSDN Documentation DateTime.AddDays Method).

DateTime tomorrow = DateTime.Now.AddDays(1);
DateTime yesterday = DateTime.Now.AddDays(-1);

Amazon S3 - HTTPS/SSL - Is it possible?

payton109’s answer is correct if you’re in the default US-EAST-1 region. If your bucket is in a different region, use a slightly different URL:

https://s3-<region>.amazonaws.com/your.domain.com/some/asset

Where <region> is the bucket location name. For example, if your bucket is in the us-west-2 (Oregon) region, you can do this:

https://s3-us-west-2.amazonaws.com/your.domain.com/some/asset

Loop through childNodes

Try this [reverse order traversal]:

var childs = document.getElementById('parent').childNodes;
var len = childs.length;
if(len --) do {
    console.log('node: ', childs[len]);
} while(len --);

OR [in order traversal]

var childs = document.getElementById('parent').childNodes;
var len = childs.length, i = -1;
if(++i < len) do {
    console.log('node: ', childs[i]);
} while(++i < len);

What is the syntax for Typescript arrow functions with generics?

I to use this type of declaration:

const identity: { <T>(arg: T): T } = (arg) => arg;

It allows defining additional props to your function if you ever need to and in some cases, it helps keeping the function body cleaner from the generic definition.

If you don't need the additional props (namespace sort of thing), it can be simplified to:

const identity: <T>(arg: T) => T = (arg) => arg;

How do I run Selenium in Xvfb?

You can use PyVirtualDisplay (a Python wrapper for Xvfb) to run headless WebDriver tests.

#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(800, 600))
display.start()

# now Firefox will run in a virtual display. 
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()

display.stop()

more info


You can also use xvfbwrapper, which is a similar module (but has no external dependencies):

from xvfbwrapper import Xvfb

vdisplay = Xvfb()
vdisplay.start()

# launch stuff inside virtual display here

vdisplay.stop()

or better yet, use it as a context manager:

from xvfbwrapper import Xvfb

with Xvfb() as xvfb:
    # launch stuff inside virtual display here.
    # It starts/stops in this code block.

Adding default parameter value with type hint in Python

Your second way is correct.

def foo(opts: dict = {}):
    pass

print(foo.__annotations__)

this outputs

{'opts': <class 'dict'>}

It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.

I strongly advise against using mutable keyword arguments. More information here.

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

To stop that Html5 popup/balloon in Web-kit browser use following CSS

::-webkit-validation-bubble-message { display: none; }

Converting string to double in C#

Add a class as Public and use it very easily like convertToInt32()

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

  /// <summary>
  /// Summary description for Common
  /// </summary>
  public static class Common
  {
     public static double ConvertToDouble(string Value) {
        if (Value == null) {
           return 0;
        }
        else {
           double OutVal;
           double.TryParse(Value, out OutVal);

           if (double.IsNaN(OutVal) || double.IsInfinity(OutVal)) {
              return 0;
           }
           return OutVal;
        }
     }
  }

Then Call The Function

double DirectExpense =  Common.ConvertToDouble(dr["DrAmount"].ToString());

How to destroy an object?

I would go with unset because it might give the garbage collector a better hint so that the memory can be available again sooner. Be careful that any things the object points to either have other references or get unset first or you really will have to wait on the garbage collector since there would then be no handles to them.

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

As @hanmari mentioned in his comment. when inserting into a postgres tables, the on conflict (..) do nothing is the best code to use for not inserting duplicate data.:

query = "INSERT INTO db_table_name(column_name)
         VALUES(%s) ON CONFLICT (column_name) DO NOTHING;"

The ON CONFLICT line of code will allow the insert statement to still insert rows of data. The query and values code is an example of inserted date from a Excel into a postgres db table. I have constraints added to a postgres table I use to make sure the ID field is unique. Instead of running a delete on rows of data that is the same, I add a line of sql code that renumbers the ID column starting at 1. Example:

q = 'ALTER id_column serial RESTART WITH 1'

If my data has an ID field, I do not use this as the primary ID/serial ID, I create a ID column and I set it to serial. I hope this information is helpful to everyone. *I have no college degree in software development/coding. Everything I know in coding, I study on my own.

Finding Variable Type in JavaScript

For builtin JS types you can use:

function getTypeName(val) {
    return {}.toString.call(val).slice(8, -1);
}

Here we use 'toString' method from 'Object' class which works different than the same method of another types.

Examples:

// Primitives
getTypeName(42);        // "Number"
getTypeName("hi");      // "String"
getTypeName(true);      // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null);      // "Null"
getTypeName(undefined); // "Undefined"

// Non-primitives
getTypeName({});            // "Object"
getTypeName([]);            // "Array"
getTypeName(new Date);      // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/);           // "RegExp"
getTypeName(new Error);     // "Error"

If you need a class name you can use:

instance.constructor.name

Examples:

({}).constructor.name       // "Object"
[].constructor.name         // "Array"
(new Date).constructor.name // "Date"

function MyClass() {}
let my = new MyClass();
my.constructor.name         // "MyClass"

But this feature was added in ES2015.

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

Your @Entity class has a String type for its @Id field, so it can't generate ids for you.

If you change it to an auto increment in the DB and a Long in java, and add the @GeneratedValue annotation:

@Id
@Column(name="U_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long U_id;

it will handle incrementing id generation for you.

Find all elements on a page whose element ID contains a certain text using jQuery

This selects all DIVs with an ID containing 'foo' and that are visible

$("div:visible[id*='foo']");

Why does this "Slow network detected..." log appear in Chrome?

Updating to the latest version of Chrome (63.0.3239.84) via Help -> About fixed it for me.

(actually, I did had to switch to Offline and back to Online in the Network tab of developers tools to make the last errors go away.)

C++ - Decimal to binary converting

Non recursive solution:

#include <iostream>
#include<string>


std::string toBinary(int n)
{
    std::string r;
    while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
    return r;
}
int main()
{
    std::string i= toBinary(10);
    std::cout<<i;
}

Recursive solution:

#include <iostream>
#include<string>

std::string r="";
std::string toBinary(int n)
{
    r=(n%2==0 ?"0":"1")+r;
    if (n / 2 != 0) {
        toBinary(n / 2);
    }
    return r;
}
int main()
{
    std::string i=toBinary(10);
    std::cout<<i;
}

Change button background color using swift language

If you want to set backgroundColor of button programmatically then this code will surly help you

Swift 3 and Swift 4

self.yourButton.backgroundColor = UIColor.red

Swift 2.3 or lower

self.yourButton.backgroundColor = UIColor.redColor()

Using RGB

self.yourButton.backgroundColor = UIColor(red: 102/255, green: 250/255, blue: 51/255, alpha: 0.5)

or you can use float values

button.backgroundColor = UIColor(red: 0.4, green: 1.0, blue: 0.2, alpha: 0.5)

When do we need curly braces around shell variables?

In this particular example, it makes no difference. However, the {} in ${} are useful if you want to expand the variable foo in the string

"${foo}bar"

since "$foobar" would instead expand the variable identified by foobar.

Curly braces are also unconditionally required when:

  • expanding array elements, as in ${array[42]}
  • using parameter expansion operations, as in ${filename%.*} (remove extension)
  • expanding positional parameters beyond 9: "$8 $9 ${10} ${11}"

Doing this everywhere, instead of just in potentially ambiguous cases, can be considered good programming practice. This is both for consistency and to avoid surprises like $foo_$bar.jpg, where it's not visually obvious that the underscore becomes part of the variable name.

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

ImportError: No module named sqlalchemy

I just experienced the same problem. Apparently, there is a new distribution method, the extension code is no longer stored under flaskext.

Source: Flask CHANGELOG This worked for me:

from flask_sqlalchemy import SQLAlchemy

show all tables in DB2 using the LIST command

select * from syscat.tables where type = 'T'

you may want to restrict the query to your tabschema

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

I had the same issue when updating an older project. Here's what I did to resolve it:

  • Converted all projects to .NET 4.5.
  • Uninstalled the NuGet package for Entity Framework 5.
  • Reinstalled the NuGet package for Entity Framework 5.
  • Cleaned the solution.
  • Rebuilt the solution.

The projects that used Entity Framework 5 and .NET 4 were installing the Entity Framework dll version 4.4. Once I switched the .NET version to 4.5 on the project, the dll version would be 5.

My problem came from older projects being on .NET 4 and a newer project running .NET 4.5 so there were 2 dll versions of EF in my solution.

Hope this helps someone...

Catch an exception thrown by an async void method

The exception can be caught in the async function.

public async void Foo()
{
    try
    {
        var x = await DoSomethingAsync();
        /* Handle the result, but sometimes an exception might be thrown
           For example, DoSomethingAsync get's data from the network
           and the data is invalid... a ProtocolException might be thrown */
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught here */
    }
}

public void DoFoo()
{
    Foo();
}

Chosen Jquery Plugin - getting selected values

If anyone wants to get only the selected value on click to an option, he can do the follow:

$('.chosen-select').on('change', function(evt, params) {
    var selectedValue = params.selected;
    console.log(selectedValue);
});

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

there an easy way to fix this error

just replace the files on the folder : C:\xampp\mysql\data\mysql

with the files on : C:\xampp\mysql\backup\mysql

Apply formula to the entire column

This is for those who want to overwrite the column cells quickly (without cutting and copying). This is the same as double-clicking the cell box but unlike double-clicking, it still works after the first try.

  1. Select the column cell you would like to copy downwards
  2. Press Ctrl+Shift+ to select the cells below
  3. Press Ctrl+Enter to copy the contents of the first cell into the cells below

BONUS:

The shortcut for going to the bottom-most content (to double-check the copy) is Ctrl+. To go back up you can use Ctrl+ but if your top rows are frozen you'll also have to press Enter a few times.

Add a new line to the end of a JtextArea

Instead of using JTextArea.setText(String text), use JTextArea.append(String text).

Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty.

This will add text on to the end of your JTextArea.

Another option would be to use getText() to get the text from the JTextArea, then manipulate the String (add or remove or change the String), then use setText(String text) to set the text of the JTextArea to be the new String.

Comparing Class Types in Java

Check Class.java source code for equals()

public boolean equals(Object obj) {
  return this == obj;
}

Setting default values for columns in JPA

Actually it is possible in JPA, although a little bit of a hack using the columnDefinition property of the @Column annotation, for example:

@Column(name="Price", columnDefinition="Decimal(10,2) default '100.00'")

ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

This error happens when the resource is busy. Check if you have any referential constraints in the query. Or even the tables that you have mentioned in the query may be busy. They might be engaged with some other job which will be definitely listed in the following query results:

SELECT * FROM V$SESSION WHERE STATUS = 'ACTIVE'

Find the SID,

SELECT * FROM V$OPEN_CURSOR WHERE SID = --the id

How to programmatically disable page scrolling with jQuery

I think the best and clean solution is:

window.addEventListener('scroll',() => {
    var x = window.scrollX;
    var y = window.scrollY;
    window.scrollTo(x,y);
});

And with jQuery:

$(window).on('scroll',() => {
    var x = window.scrollX;
    var y = window.scrollY;
    window.scrollTo(x,y)
})

Those event listener should block scrolling. Just remove them to re enable scrolling

Average of multiple columns

Select Req_ID, sum(R1+R2+R3+R4+R5)/5 as Average
from Request
Group by Req_ID;

Launch Minecraft from command line - username and password as prefix

For anyone meaning to do this more reliably for different Minecraft versions, I have a Python script (adapted from parts of minecraft-launcher-lib) that does the job very nicely

Besides setting some basic variables near the top after the functions, it calls a get_classpath that goes through for example ~/.minecraft/versions/1.16.5/1.16.5.json, and loops over the libraries array, checking to see if each object (within the array), is supposed to be added to the classpath (cp variable). whether this library is added to the java classpath is governed by the should_use_library function, deterministic based on the computer's architecture and operating system. finally, some jarfiles that are platform specific have extra things prepended to them (ex. natives-linux in org/lwjgl/lwjgl/3.2.1/lwjgl-3.2.1-natives-linux.jar). this extra prepended string is handled by get_natives_string and is empty if it doesn't apply to the current library

tested on Linux, distribution Arch Linux

#!/usr/bin/env python
import json
import os
import platform
from pathlib import Path
import subprocess


"""Debug output
"""
def debug(str):
    if os.getenv('DEBUG') != None:
        print(str)

"""
[Gets the natives_string toprepend to the jar if it exists. If there is nothing native specific, returns and empty string]
"""
def get_natives_string(lib):
    arch = ""
    if platform.architecture()[0] == "64bit":
        arch = "64"
    elif platform.architecture()[0] == "32bit":
        arch = "32"
    else:
        raise Exception("Architecture not supported")

    nativesFile=""
    if not "natives" in lib:
        return nativesFile

    # i've never seen ${arch}, but leave it in just in case
    if "windows" in lib["natives"] and platform.system() == 'Windows':
        nativesFile = lib["natives"]["windows"].replace("${arch}", arch)
    elif "osx" in lib["natives"] and platform.system() == 'Darwin':
        nativesFile = lib["natives"]["osx"].replace("${arch}", arch)
    elif "linux" in lib["natives"] and platform.system() == "Linux":
        nativesFile = lib["natives"]["linux"].replace("${arch}", arch)
    else:
        raise Exception("Platform not supported")

    return nativesFile


"""[Parses "rule" subpropery of library object, testing to see if should be included]
"""
def should_use_library(lib):
    def rule_says_yes(rule):
        useLib = None

        if rule["action"] == "allow":
            useLib = False
        elif rule["action"] == "disallow":
            useLib = True

        if "os" in rule:
            for key, value in rule["os"].items():
                os = platform.system()
                if key == "name":
                    if value == "windows" and os != 'Windows':
                        return useLib
                    elif value == "osx" and os != 'Darwin':
                        return useLib
                    elif value == "linux" and os != 'Linux':
                        return useLib
                elif key == "arch":
                    if value == "x86" and platform.architecture()[0] != "32bit":
                        return useLib

        return not useLib

    if not "rules" in lib:
        return True

    shouldUseLibrary = False
    for i in lib["rules"]:
        if rule_says_yes(i):
            return True

    return shouldUseLibrary

"""
[Get string of all libraries to add to java classpath]
"""
def get_classpath(lib, mcDir):
    cp = []

    for i in lib["libraries"]:
        if not should_use_library(i):
            continue

        libDomain, libName, libVersion = i["name"].split(":")
        jarPath = os.path.join(mcDir, "libraries", *
                               libDomain.split('.'), libName, libVersion)

        native = get_natives_string(i)
        jarFile = libName + "-" + libVersion + ".jar"
        if native != "":
            jarFile = libName + "-" + libVersion + "-" + native + ".jar"

        cp.append(os.path.join(jarPath, jarFile))

    cp.append(os.path.join(mcDir, "versions", lib["id"], f'{lib["id"]}.jar'))

    return os.pathsep.join(cp)

version = '1.16.5'
username = '{username}'
uuid = '{uuid}'
accessToken = '{token}'

mcDir = os.path.join(os.getenv('HOME'), '.minecraft')
nativesDir = os.path.join(os.getenv('HOME'), 'versions', version, 'natives')
clientJson = json.loads(
    Path(os.path.join(mcDir, 'versions', version, f'{version}.json')).read_text())
classPath = get_classpath(clientJson, mcDir)
mainClass = clientJson['mainClass']
versionType = clientJson['type']
assetIndex = clientJson['assetIndex']['id']

debug(classPath)
debug(mainClass)
debug(versionType)
debug(assetIndex)

subprocess.call([
    '/usr/bin/java',
    f'-Djava.library.path={nativesDir}',
    '-Dminecraft.launcher.brand=custom-launcher',
    '-Dminecraft.launcher.version=2.1',
    '-cp',
    classPath,
    'net.minecraft.client.main.Main',
    '--username',
    username,
    '--version',
    version,
    '--gameDir',
    mcDir,
    '--assetsDir',
    os.path.join(mcDir, 'assets'),
    '--assetIndex',
    assetIndex,
    '--uuid',
    uuid,
    '--accessToken',
    accessToken,
    '--userType',
    'mojang',
    '--versionType',
    'release'
])

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

The problem is in the Eclipse Maven support, the related question is here.

Under Eclipse, the java.home variable is set to the JRE that was used to start Eclipse, not the build JRE. The default system JRE from C:\Program Files doesn't include the JDK so tools.jar is not being found.

To fix the issue you need to start Eclipse using the JRE from the JDK by adding something like this to eclipse.ini (before -vmargs!):

-vm
C:/<your_path_to_jdk170>/jre/bin/server/jvm.dll

Then refresh the Maven dependencies (Alt-F5) (Just refreshing the project isn't sufficient).

How do I compare two Integers?

Use the equals method. Why are you so worried that it's expensive?

Stripping everything but alphanumeric chars from a string in Python

sent = "".join(e for e in sent if e.isalpha())

Can I set an unlimited length for maxJsonLength in web.config?

NOTE: this answer applies only to Web services, if you are returning JSON from a Controller method, make sure you read this SO answer below as well: https://stackoverflow.com/a/7207539/1246870


The MaxJsonLength property cannot be unlimited, is an integer property that defaults to 102400 (100k).

You can set the MaxJsonLength property on your web.config:

<configuration> 
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="50000000"/>
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration> 

How to add a linked source folder in Android Studio?

The right answer is:

android {
    ....
    ....

    sourceSets {
        main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
    }
}

Furthermore, if your external source directory is not under src/main, you could use a relative path like this:

sourceSets {
    main.java.srcDirs += 'src/main/../../../<YOUR DIRECTORY>'
}

Python - abs vs fabs

Edit: as @aix suggested, a better (more fair) way to compare the speed difference:

In [1]: %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop

In [2]: from math import fabs

In [3]: %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop

In [4]: %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop

In [5]: %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop

In [6]: %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop

In [7]: %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop

In [8]: %timeit abs(-5.0)
10000000 loops, best of 3: 91.8 ns per loop

In [9]: %timeit fabs(-5.0)
10000000 loops, best of 3: 91 ns per loop

So it seems abs() only has slight speed advantage over fabs() for integers. For floats, abs() and fabs() demonstrate similar speed.


In addition to what @aix has said, one more thing to consider is the speed difference:

In [1]: %timeit abs(-5)
10000000 loops, best of 3: 102 ns per loop

In [2]: import math

In [3]: %timeit math.fabs(-5)
10000000 loops, best of 3: 194 ns per loop

So abs() is faster than math.fabs().

'Invalid update: invalid number of rows in section 0

Swift Version --> Remove the object from your data array before you call

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        print("Deleted")

        currentCart.remove(at: indexPath.row) //Remove element from your array 
        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

Capture HTML Canvas as gif/jpg/png/pdf?

Oops. Original answer was specific to a similar question. This has been revised:

var canvas = document.getElementById("mycanvas");
var img    = canvas.toDataURL("image/png");

with the value in IMG you can write it out as a new Image like so:

document.write('<img src="'+img+'"/>');

iPhone UITextField - Change placeholder text color

For iOS 6.0 +

[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];

Hope it helps.

Note: Apple may reject (0.01% chances) your app as we are accessing private API. I am using this in all my projects since two years, but Apple didn't ask for this.

Node.js: what is ENOSPC error and how to solve?

On Linux, this is likely to be a limit on the number of file watches.

The development server uses inotify to implement hot-reloading. The inotify API allows the development server to watch files and be notified when they change.

The default inotify file watch limit varies from distribution to distribution (8192 on Fedora). The needs of the development server often exceeds this limit.

The best approach is to try increasing the file watch limit temporarily, then making that a permanent configuration change if you're happy with it. Note, though, that this changes your entire system's configuration, not just node.

To view your current limit:

sysctl fs.inotify.max_user_watches

To temporarily set a new limit:

# this limit will revert after reset
sudo sysctl fs.inotify.max_user_watches=524288
sudo sysctl -p
# now restart the server and see if it works

To set a permanent limit:

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

For Java, from a command line:

java -version

will indicate whether it's 64-bit or not.

Output from the console on my Ubuntu box:

java version "1.6.0_12-ea"
Java(TM) SE Runtime Environment (build 1.6.0_12-ea-b03)
Java HotSpot(TM) 64-Bit Server VM (build 11.2-b01, mixed mode)

IE will indicate 64-bit versions in the About dialog, I believe.

Invoke a second script with arguments from a script

I tried the accepted solution of using the Invoke-Expression cmdlet but it didn't work for me because my arguments had spaces on them. I tried to parse the arguments and escape the spaces but I couldn't properly make it work and also it was really a dirty work around in my opinion. So after some experimenting, my take on the problem is this:

function Invoke-Script
{
    param
    (
        [Parameter(Mandatory = $true)]
        [string]
        $Script,

        [Parameter(Mandatory = $false)]
        [object[]]
        $ArgumentList
    )

    $ScriptBlock = [Scriptblock]::Create((Get-Content $Script -Raw))
    Invoke-Command -NoNewScope -ArgumentList $ArgumentList -ScriptBlock $ScriptBlock -Verbose
}

# example usage
Invoke-Script $scriptPath $argumentList

The only drawback of this solution is that you need to make sure that your script doesn't have a "Script" or "ArgumentList" parameter.

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

Android button with different background colors

In the URL you pointed to, the button_text.xml is being used to set the textColor attribute.That it is reason they had the button_text.xml in res/color folder and therefore they used @color/button_text.xml

But you are trying to use it for background attribute. The background attribute looks for something in res/drawable folder.

check this i got this selector custom button from the internet.I dont have the link.but i thank the poster for this.It helped me.have this in the drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <gradient
                android:startColor="@color/yellow1"
                android:endColor="@color/yellow2"
                android:angle="270" />
            <stroke
                android:width="3dp"
                android:color="@color/grey05" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>

    <item android:state_focused="true" >
        <shape>
            <gradient
                android:endColor="@color/orange4"
                android:startColor="@color/orange5"
                android:angle="270" />
            <stroke
                android:width="3dp"
                android:color="@color/grey05" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>

    <item>        
        <shape>
            <gradient
                android:endColor="@color/white1"
                android:startColor="@color/white2"
                android:angle="270" />
            <stroke
                android:width="3dp"
                android:color="@color/grey05" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>

</selector>

And i used in my main.xml layout like this

<Button android:id="@+id/button1"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="150dip"
            android:layout_marginLeft="45dip"
            android:textSize="7pt"
            android:layout_height="wrap_content"
            android:layout_width="230dip"
            android:text="@string/welcomebtntitle1"
            android:background="@drawable/custombutton"/>

Hope this helps. Vik is correct.

EDIT : Here is the colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="yellow1">#F9E60E</color>
   <color name="yellow2">#F9F89D</color>
   <color name="orange4">#F7BE45</color>
   <color name="orange5">#F7D896</color>
   <color name="blue2">#19FCDA</color>
   <color name="blue25">#D9F7F2</color>
   <color name="grey05">#ACA899</color>
   <color name="white1">#FFFFFF</color>
   <color name="white2">#DDDDDD</color>
</resources>

How to return a result from a VBA function

The below code stores the return value in to the variable retVal and then MsgBox can be used to display the value:

Dim retVal As Integer
retVal = test()
Msgbox retVal

POST Multipart Form Data using Retrofit 2.0 including image

There is a correct way of uploading a file with its name with Retrofit 2, without any hack:

Define API interface:

@Multipart
@POST("uploadAttachment")
Call<MyResponse> uploadAttachment(@Part MultipartBody.Part filePart); 
                                   // You can add other parameters too

Upload file like this:

File file = // initialize file here

MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));

Call<MyResponse> call = api.uploadAttachment(filePart);

This demonstrates only file uploading, you can also add other parameters in the same method with @Part annotation.

Vue.JS: How to call function after page loaded?

You import the function from outside the main instance, and don't add it to the methods block. so the context of this is not the vm.

Either do this:

ready() {
  checkAuth.call(this)
}

or add the method to your methods first (which will make Vue bind this correctly for you) and call this method:

methods: {
  checkAuth: checkAuth
},
ready() {
  this.checkAuth()
}

Two Decimal places using c#

If someone looking for a way to display decimal places even if it ends with ".00", use this:

String.Format("{0:n1}", value)

Reference:

https://docs.microsoft.com/pt-br/dotnet/standard/base-types/standard-numeric-format-strings#the-numeric-n-format-specifier

Reloading .env variables without restarting server (Laravel 5, shared hosting)

In case anybody stumbles upon this question who cannot reload their webserver (long running console command like a queue runner) or needs to reload their .env file mid-request, i found a way to properly reload .env variables in laravel 5.

use Dotenv;
use InvalidArgumentException;

try {
    Dotenv::makeMutable();
    Dotenv::load(app()->environmentPath(), app()->environmentFile());
    Dotenv::makeImmutable();
} catch (InvalidArgumentException $e) {
    //
}

Issue with virtualenv - cannot activate

Tried several different commands until I came across:

source venv/Scripts/activate

This did it for me. Setup: Win 10, python 3.7, gitbash. Gitbash might be the culprit for not playing nice with other activate commands.

How to check for changes on remote (origin) Git repository

git status does not always show the difference between master and origin/master even after a fetch.

If you want the combination git fetch origin && git status to work, you need to specify the tracking information between the local branch and origin:

# git branch --set-upstream-to=origin/<branch> <branch>

For the master branch:

git branch --set-upstream-to=origin/master master

How do I query between two dates using MySQL?

Your query should have date as

select * from table between `lowerdate` and `upperdate`

try

SELECT * FROM `objects` 
WHERE  (date_field BETWEEN '2010-01-30 14:15:55' AND '2010-09-29 10:15:55')

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

I've had this happen on VS after I changed the file's line endings. Changing them back to Windows CR LF fixed the issue.

How to align 3 divs (left/center/right) inside another div?

I like my bars tight and dynamic. This is for CSS 3 & HTML 5

  1. First, setting the Width to 100px is limiting. Don't do it.

  2. Second, setting the container's width to 100% will work ok, until were talking about it being a header/footer bar for the whole app, like a navigation or credits/copyright bar. Use right: 0; instead for that scenario.

  3. You are using id's (hash #container, #left, etc) instead of classes (.container, .left, etc), which is fine, unless you want to repeat your style pattern elsewhere in your code. I'd consider using classes instead.

  4. For HTML, no need to swap order for: left, center, & right. display: inline-block; fixes this, returning your code to something cleaner and logically in order again.

  5. Lastly, you need to clear the floats all up so that it doesn't mess with future <div>. You do this with the clear: both;

To summarize:

HTML:

<div class="container">
  <div class="left"></div>
  <div class="center"></div>
  <div class="right"></div>
  <div class="clear"></div>
</div>

CSS:

.container {right: 0; text-align: center;}

.container .left, .container .center, .container .right { display: inline-block; }

.container .left { float: left; }
.container .center { margin: 0 auto; }
.container .right { float: right; }
.clear { clear: both; }

Bonus point if using HAML and SASS ;)

HAML:

.container
  .left
  .center
  .right
  .clear

SASS:

.container {
  right: 0;
  text-align: center;

  .left, .center, .right { display: inline-block; }

  .left { float: left; }
  .center { margin: 0 auto; }
  .right { float: right; }
  .clear { clear: both; }
}

not-null property references a null or transient value

Make that variable as transient.Your problem will get solved..

@Column(name="emp_name", nullable=false, length=30)
    private transient String empName;

Disabling the button after once click

$("selectorbyclassorbyIDorbyName").click(function () {
  $("selectorbyclassorbyIDorbyName").attr("disabled", true).delay(2000).attr("disabled", false);
});

select the button and by its id or text or class ... it just disables after 1st click and enables after 20 Milli sec

Works very well for post backs n place it in Master page, applies to all buttons without calling implicitly like onclientClick

How do I get the total Json record count using JQuery?

The OP is trying to count the number of properties in a JSON object. This could be done with an incremented temp variable in the iterator, but he seems to want to know the count before the iteration begins. A simple function that meets the need is provided at the bottom of this page.

Here's a cut and paste of the code, which worked for me:

function countProperties(obj) {
  var prop;
  var propCount = 0;

  for (prop in obj) {
    propCount++;
  }
  return propCount;
}

This should work well for a JSON object. For other objects, which may derive properties from their prototype chain, you would need to add a hasOwnProperty() test.

How to change default JRE for all Eclipse workspaces?

My answer will overlap with amphibient's while adding on to it.

Your JAVA_HOME variable is fine, but you also need to append the following to your Path variable :

;%JAVA_HOME%\bin

This will allow your applications in your Windows environment to access your JDK. You should also restart your computer once you've added these environment variables before checking out if they work. In my case, even logging out and then back in didn't work : I had to completely restart.

If you want to check if the environment variables are set correctly, you can open up a command prompt and type >echo %JAVA_HOME and >echo %Path% to see if those variables are working correctly. While snooping around for solutions, I have also run into people claiming that they need to add quotations marks (") around the environment variables to make them work correctly ("%JAVA_HOME%"\bin) if your JAVA_HOME path includes spaces. I thought that this was my case at first, but after doing a full restart my variables seemed to work correctly without quotation marks despite the spaces.

read subprocess stdout line by line

You want to pass these extra parameters to subprocess.Popen:

bufsize=1, universal_newlines=True

Then you can iterate as in your example. (Tested with Python 3.5)

Hide all warnings in ipython

For jupyter lab this should work (@Alasja)

from IPython.display import HTML
HTML('''<script>
var code_show_err = false; 
var code_toggle_err = function() {
 var stderrNodes = document.querySelectorAll('[data-mime-type="application/vnd.jupyter.stderr"]')
 var stderr = Array.from(stderrNodes)
 if (code_show_err){
     stderr.forEach(ele => ele.style.display = 'block');
 } else {
     stderr.forEach(ele => ele.style.display = 'none');
 }
 code_show_err = !code_show_err
} 
document.addEventListener('DOMContentLoaded', code_toggle_err);
</script>
To toggle on/off output_stderr, click <a onclick="javascript:code_toggle_err()">here</a>.''')

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

Save internal file in my own internal folder in Android

Save:

public boolean saveFile(Context context, String mytext){
    Log.i("TESTE", "SAVE");
    try {
        FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
        Writer out = new OutputStreamWriter(fos);
        out.write(mytext);
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

Load:

public String load(Context context){
    Log.i("TESTE", "FILE");
    try {
        FileInputStream fis = context.openFileInput("file_name"+".txt");
        BufferedReader r = new BufferedReader(new InputStreamReader(fis));
        String line= r.readLine();
        r.close();
        return line;
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TESTE", "FILE - false");
        return null;
    }
}

How can I make a Python script standalone executable to run without ANY dependency?

You may like py2exe. You'll also find information in there for doing it on Linux.

Magento - How to add/remove links on my account navigation?

Technically the answer of zlovelady is preferable, but as I had only to remove items from the navigation, the approach of unsetting the not-needed navigation items in the template was the fastest/easiest way for me:

Just duplicate

app/design/frontend/base/default/template/customer/account/navigation

to

app/design/frontend/YOUR_THEME/default/template/customer/account/navigation

and unset the unneeded navigation items before the get rendered, e.g.:

<?php $_links = $this->getLinks(); ?>    
<?php 
    unset($_links['recurring_profiles']);
?>

Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

or

case 
    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

What is the difference between varchar and varchar2 in Oracle?

Currently, they are the same. but previously

  1. Somewhere on the net, I read that,

VARCHAR is reserved by Oracle to support distinction between NULL and empty string in future, as ANSI standard prescribes.

VARCHAR2 does not distinguish between a NULL and empty string, and never will.

  1. Also,

Emp_name varchar(10) - if you enter value less than 10 digits then remaining space cannot be deleted. it used total of 10 spaces.

Emp_name varchar2(10) - if you enter value less than 10 digits then remaining space is automatically deleted

Flask at first run: Do not use the development server in a production environment

The official tutorial discusses deploying an app to production. One option is to use Waitress, a production WSGI server. Other servers include Gunicorn and uWSGI.

When running publicly rather than in development, you should not use the built-in development server (flask run). The development server is provided by Werkzeug for convenience, but is not designed to be particularly efficient, stable, or secure.

Instead, use a production WSGI server. For example, to use Waitress, first install it in the virtual environment:

$ pip install waitress

You need to tell Waitress about your application, but it doesn’t use FLASK_APP like flask run does. You need to tell it to import and call the application factory to get an application object.

$ waitress-serve --call 'flaskr:create_app'
Serving on http://0.0.0.0:8080

Or you can use waitress.serve() in the code instead of using the CLI command.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "<h1>Hello!</h1>"

if __name__ == "__main__":
    from waitress import serve
    serve(app, host="0.0.0.0", port=8080)
$ python hello.py

How to consume REST in Java

Just make an http request to the required URL with correct query string, or request body.

For example you could use java.net.HttpURLConnection and then consume via connection.getInputStream(), and then covnert to your objects.

In spring there is a restTemplate that makes it all a bit easier.

How to resume Fragment from BackStack if exists

I know this is quite late to answer this question but I resolved this problem by myself and thought worth sharing it with everyone.`

public void replaceFragment(BaseFragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    final FragmentManager fManager = getSupportFragmentManager();
    BaseFragment fragm = (BaseFragment) fManager.findFragmentByTag(fragment.getFragmentTag());
    transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);

    if (fragm == null) {  //here fragment is not available in the stack
        transaction.replace(R.id.container, fragment, fragment.getFragmentTag());
        transaction.addToBackStack(fragment.getFragmentTag());
    } else { 
        //fragment was found in the stack , now we can reuse the fragment
        // please do not add in back stack else it will add transaction in back stack
        transaction.replace(R.id.container, fragm, fragm.getFragmentTag()); 
    }
    transaction.commit();
}

And in the onBackPressed()

 @Override
public void onBackPressed() {
    if(getSupportFragmentManager().getBackStackEntryCount()>1){
        super.onBackPressed();
    }else{
        finish();
    }
}

Determine distance from the top of a div to top of window with javascript

Vanilla:

window.addEventListener('scroll', function(ev) {

   var someDiv = document.getElementById('someDiv');
   var distanceToTop = someDiv.getBoundingClientRect().top;

   console.log(distanceToTop);
});

Open your browser console and scroll your page to see the distance.

Find the day of a week

start = as.POSIXct("2017-09-01")
end = as.POSIXct("2017-09-06")

dat = data.frame(Date = seq.POSIXt(from = start,
                                   to = end,
                                   by = "DSTday"))

# see ?strptime for details of formats you can extract

# day of the week as numeric (Monday is 1)
dat$weekday1 = as.numeric(format(dat$Date, format = "%u"))

# abbreviated weekday name
dat$weekday2 = format(dat$Date, format = "%a")

# full weekday name
dat$weekday3 = format(dat$Date, format = "%A")

dat
# returns
    Date       weekday1 weekday2  weekday3
1 2017-09-01        5      Fri    Friday
2 2017-09-02        6      Sat    Saturday
3 2017-09-03        7      Sun    Sunday
4 2017-09-04        1      Mon    Monday
5 2017-09-05        2      Tue    Tuesday
6 2017-09-06        3      Wed    Wednesday

How to parse a month name (string) to an integer for comparison in C#?

If you are using c# 3.0 (or above) you can use extenders

How to retrieve a user environment variable in CMake (Windows)

Environment variables (that you modify using the System Properties) are only propagated to subshells when you create a new subshell.

If you had a command line prompt (DOS or cygwin) open when you changed the User env vars, then they won't show up.

You need to open a new command line prompt after you change the user settings.

The equivalent in Unix/Linux is adding a line to your .bash_rc: you need to start a new shell to get the values.

C++ templates that accept only certain types

Is there some simple equivalent to this keyword in C++?

No.

Depending on what you're trying to accomplish, there might be adequate (or even better) substitutes.

I've looked through some STL code (on linux, I think it's the one deriving from SGI's implementation). It has "concept assertions"; for instance, if you require a type which understands *x and ++x, the concept assertion would contain that code in a do-nothing function (or something similar). It does require some overhead, so it might be smart to put it in a macro whose definition depends on #ifdef debug.

If the subclass relationship is really what you want to know about, you could assert in the constructor that T instanceof list (except it's "spelled" differently in C++). That way, you can test your way out of the compiler not being able to check it for you.

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

I changed the Office365 password and then tried to send a test email and it worked like a charm for me.

I used the front end (database mail option) and settings as smtp.office365.com port number 587 and checked the secure connection option. use basic authentication and store the credentials. Hope this turns out useful for someone.

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

Where are static variables stored in C and C++?

The answer might very well depend on the compiler, so you probably want to edit your question (I mean, even the notion of segments is not mandated by ISO C nor ISO C++). For instance, on Windows an executable doesn't carry symbol names. One 'foo' would be offset 0x100, the other perhaps 0x2B0, and code from both translation units is compiled knowing the offsets for "their" foo.

how to convert an RGB image to numpy array?

You can use newer OpenCV python interface (if I'm not mistaken it is available since OpenCV 2.2). It natively uses numpy arrays:

import cv2
im = cv2.imread("abc.tiff",mode='RGB')
print type(im)

result:

<type 'numpy.ndarray'>

How to get Selected Text from select2 when using <input>

Again I suggest Simple and Easy

Its Working Perfect with ajax when user search and select it saves the selected information via ajax

 $("#vendor-brands").select2({
   ajax: {
   url:site_url('general/get_brand_ajax_json'),
  dataType: 'json',
  delay: 250,
  data: function (params) {
  return {
    q: params.term, // search term
    page: params.page
  };
},
processResults: function (data, params) {
  // parse the results into the format expected by Select2
  // since we are using custom formatting functions we do not need to
  // alter the remote JSON data, except to indicate that infinite
  // scrolling can be used
  params.page = params.page || 1;

  return {
    results: data,
    pagination: {
      more: (params.page * 30) < data.total_count
    }
  };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom    formatter work
minimumInputLength: 1,
}).on("change", function(e) {


  var lastValue = $("#vendor-brands option:last-child").val();
  var lastText = $("#vendor-brands option:last-child").text();

  alert(lastValue+' '+lastText);
 });

Dynamically select data frame columns using $ and a character value

too late.. but I guess I have the answer -

Here's my sample study.df dataframe -

   >study.df
   study   sample       collection_dt other_column
   1 DS-111 ES768098 2019-01-21:04:00:30         <NA>
   2 DS-111 ES768099 2018-12-20:08:00:30   some_value
   3 DS-111 ES768100                <NA>   some_value

And then -

> ## Selecting Columns in an Given order
> ## Create ColNames vector as per your Preference
> 
> selectCols <- c('study','collection_dt','sample')
> 
> ## Select data from Study.df with help of selection vector
> selectCols %>% select(.data=study.df,.)
   study       collection_dt   sample
1 DS-111 2019-01-21:04:00:30 ES768098
2 DS-111 2018-12-20:08:00:30 ES768099
3 DS-111                <NA> ES768100
> 

How can I return the difference between two lists?

You may call U.difference(lists) method in underscore-java library. I am the maintainer of the project. Live example

import com.github.underscore.U;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> list1 = Arrays.asList(1, 2, 3);
        List<Integer> list2 = Arrays.asList(1, 2);
        List<Integer> list3 = U.difference(list1, list2);
        System.out.println(list3);
        // [3]
    }
}

Get resultset from oracle stored procedure

My solution was to create a pipelined function. The advantages are that the query can be a single line:

  • select * from table(yourfunction(param1, param2));
  • You can join your results to other tables or filter or sort them as you please..
  • the results appear as regular query results so you can easily manipulate them.

To define the function you would need to do something like the following:

  -- Declare the record columns
  TYPE your_record IS RECORD(
     my_col1 VARCHAR2(50), 
     my_col2 varchar2(4000)
  );
  TYPE your_results IS TABLE OF your_record;

  -- Declare the function
  function yourfunction(a_Param1 varchar2, a_Param2 varchar2)
  return your_results pipelined is
    rt          your_results;
  begin
    -- Your query to load the table type
    select s.col1,s.col2
    bulk collect into rt
    from your_table s
    where lower(s.col1) like lower('%'||a_Param1||'%');

    -- Stuff the results into the pipeline..
    if rt.count > 0 then 
      for i in rt.FIRST .. rt.LAST loop 
        pipe row (rt(i)); 
      end loop; 
    end if;

    -- Add more results as you please....
    return;
  end find;

And as mentioned above, all you would do to view your results is:

select * from table(yourfunction(param1, param2)) t order by t.my_col1;

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

How can I open Java .class files in a human-readable way?

That's compiled code, you'll need to use a decompiler like JAD: http://www.kpdus.com/jad.html

java.lang.OutOfMemoryError: Java heap space

You may want to look at this site to learn more about memory in the JVM: http://developer.streamezzo.com/content/learn/articles/optimization-heap-memory-usage

I have found it useful to use visualgc to watch how the different parts of the memory model is filling up, to determine what to change.

It is difficult to determine which part of memory was filled up, hence visualgc, as you may want to just change the part that is having a problem, rather than just say,

Fine! I will give 1G of RAM to the JVM.

Try to be more precise about what you are doing, in the long run you will probably find the program better for it.

To determine where the memory leak may be you can use unit tests for that, by testing what was the memory before the test, and after, and if there is too big a change then you may want to examine it, but, you need to do the check while your test is still running.

Setting the default active profile in Spring-boot

In AWS LAMBDA:

For $ sam local you add the following line in your sam template yml file:

Resources:
   FunctionName:
       Properties:
           Environment:
               Variables:
                  SPRING_PROFILES_ACTIVE: local

But in AWS Console: in your Lambda Environment variables just add:

KEY:JAVA_TOOL_OPTIONS VALUE:-Dspring.profiles.active=dev

enter image description here

JavaScript: get code to run every minute

You could use setInterval for this.

<script type="text/javascript">
function myFunction () {
    console.log('Executed!');
}

var interval = setInterval(function () { myFunction(); }, 60000);
</script>

Disable the timer by setting clearInterval(interval).

See this Fiddle: http://jsfiddle.net/p6NJt/2/

How to solve error message: "Failed to map the path '/'."

My solution was to make sure that all IIS features are installed. So went to add remove programs in the control panel and clicked on add remove windows features and selected all options except IIS 6 console compatibility.

Requery a subform from another form?

You must use the name of the subform control, not the name of the subform, though these are often the same:

 Forms![MainForm]![subform control name Name].Form.Requery

Or, if you are on the main form:

 Me.[subform control name Name].Form.Requery

More Info: http://www.mvps.org/access/forms/frm0031.htm

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

In my case this very same error was caused by the way I was importing my custom component from the caller class i.e. I was doing

import {MyComponent} from './components/MyComponent'

instead of

import MyComponent from './components/MyComponent'

using the latter solved the issue.

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

Returning false from the function will stop the event continuing. I.e. it will stop the form submitting.

i.e.

function someFunction()
{
    if (allow) // For example, checking that a field isn't empty
    {
       return true; // Allow the form to submit
    }
    else
    {
       return false; // Stop the form submitting
    }
}

Difference between two dates in Python

Another short solution:

from datetime import date

def diff_dates(date1, date2):
    return abs(date2-date1).days

def main():
    d1 = date(2013,1,1)
    d2 = date(2013,9,13)
    result1 = diff_dates(d2, d1)
    print '{} days between {} and {}'.format(result1, d1, d2)
    print ("Happy programmer's day!")

main()

array_push() with key value pair

You don't need to use array_push() function, you can assign new value with new key directly to the array like..

$array = array("color1"=>"red", "color2"=>"blue");
$array['color3']='green';
print_r($array);


Output:

   Array(
     [color1] => red
     [color2] => blue
     [color3] => green
   )

Read text file into string array (and write)

You can use os.File (which implements the io.Reader interface) with the bufio package for that. However, those packages are build with fixed memory usage in mind (no matter how large the file is) and are quite fast.

Unfortunately this makes reading the whole file into the memory a bit more complicated. You can use a bytes.Buffer to join the parts of the line if they exceed the line limit. Anyway, I recommend you to try to use the line reader directly in your project (especially if do not know how large the text file is!). But if the file is small, the following example might be sufficient for you:

package main

import (
    "os"
    "bufio"
    "bytes"
    "fmt"
)

// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err os.Error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, err = os.Open(path); err != nil {
        return
    }
    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 1024))
    for {
        if part, prefix, err = reader.ReadLine(); err != nil {
            break
        }
        buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if err == os.EOF {
        err = nil
    }
    return
}

func main() {
    lines, err := readLines("foo.txt")
    if err != nil {
        fmt.Println("Error: %s\n", err)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }
}

Another alternative might be to use io.ioutil.ReadAll to read in the complete file at once and do the slicing by line afterwards. I don't give you an explicit example of how to write the lines back to the file, but that's basically an os.Create() followed by a loop similar to that one in the example (see main()).

Understanding the Linux oom-killer's logs

Memory management in Linux is a bit tricky to understand, and I can't say I fully understand it yet, but I'll try to share a little bit of my experience and knowledge.

Short answer to your question: Yes there are other stuff included than whats in the list.

What's being shown in your list is applications run in userspace. The kernel uses memory for itself and modules, on top of that it also has a lower limit of free memory that you can't go under. When you've reached that level it will try to free up resources, and when it can't do that anymore, you end up with an OOM problem.

From the last line of your list you can read that the kernel reports a total-vm usage of: 1498536kB (1,5GB), where the total-vm includes both your physical RAM and swap space. You stated you don't have any swap but the kernel seems to think otherwise since your swap space is reported to be full (Total swap = 524284kB, Free swap = 0kB) and it reports a total vmem size of 1,5GB.

Another thing that can complicate things further is memory fragmentation. You can hit the OOM killer when the kernel tries to allocate lets say 4096kB of continous memory, but there are no free ones availible.

Now that alone probably won't help you solve the actual problem. I don't know if it's normal for your program to require that amount of memory, but I would recommend to try a static code analyzer like cppcheck to check for memory leaks or file descriptor leaks. You could also try to run it through Valgrind to get a bit more information out about memory usage.

Open File in Another Directory (Python)

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

Edit:

Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

Trigger a button click with JavaScript on the Enter key in a text box

Short working pure JS

txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1

_x000D_
_x000D_
txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1

function doSomething() {
  console.log('');
}
_x000D_
<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
_x000D_
_x000D_
_x000D_

How to use OpenFileDialog to select a folder?

Here is another solution, that has all the source available in a single, simple ZIP file.

It presents the OpenFileDialog with additional windows flags that makes it work like the Windows 7+ Folder Selection dialog.

Per the website, it is public domain: "There’s no license as such as you are free to take and do with the code what you will."

Archive.org links:

How to download PDF automatically using js?

Use the download attribute.

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));

AngularJS format JSON string output

If you are looking to render JSON as HTML and it can be collapsed/opened, you can use this directive that I just made to render it nicely:

https://github.com/mohsen1/json-formatter/

enter image description here

How to get longitude and latitude of any address?

You need to access a geocoding service (i.e. from Google), there is no simple formula to transfer addresses to geo coordinates.

Bash scripting, multiple conditions in while loop

The extra [ ] on the outside of your second syntax are unnecessary, and possibly confusing. You may use them, but if you must you need to have whitespace between them.

Alternatively:

while [ $stats -gt 300 ] || [ $stats -eq 0 ]

The requested resource does not support HTTP method 'GET'

In my case, the route signature was different from the method parameter. I had id, but I was accepting documentId as parameter, that caused the problem.

[Route("Documents/{id}")]   <--- caused the webapi error
[Route("Documents/{documentId}")] <-- solved
public Document Get(string documentId)
{
  ..
}

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

First of all you should configure $resource in different manner: without query params in the URL. Default query parameters may be passed as properties of the second parameter in resource(url, paramDefaults, actions). It is also to be mentioned that you configure get method of resource and using query instead.

Service

angular.module('admin.services', ['ngResource'])       
  // GET TASK LIST ACTIVITY
  .factory('getTaskService', function($resource) {
    return $resource(
      '../rest/api.php',
      { method: 'getTask', q: '*' }, // Query parameters
      {'query': { method: 'GET' }}
    );
  })

Documentation

http://docs.angularjs.org/api/ngResource.$resource

Using CSS for a fade-in effect on page load

Looking forward to Web Animations in 2020.

_x000D_
_x000D_
async function moveToPosition(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        transform: `translateY(${el.getBoundingClientRect().top}px)`
      },
    ], {
      duration: durationInMs,
      easing: 'ease-in',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeIn(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        opacity: '0.5',
        offset: 0.5
      },
      {
        opacity: '1',
        offset: 1
      }
    ], {
      duration: durationInMs,
      easing: 'linear',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeInSections() {
  for (const section of document.getElementsByTagName('section')) {
    await fadeIn(section, 200);
  }
}

window.addEventListener('load', async() => {
  await moveToPosition(document.getElementById('headerContent'), 500);
  await fadeInSections();
  await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
  height: 100vh;
}

header {
  height: 20%;
}

.text-center {
  text-align: center;
}

.leading-none {
  line-height: 1;
}

.leading-3 {
  line-height: .75rem;
}

.leading-2 {
  line-height: .25rem;
}

.bg-black {
  background-color: rgba(0, 0, 0, 1);
}

.bg-gray-50 {
  background-color: rgba(249, 250, 251, 1);
}

.pt-12 {
  padding-top: 3rem;
}

.pt-2 {
  padding-top: 0.5rem;
}

.text-lightGray {
  color: lightGray;
}

.container {
  display: flex;
  /* or inline-flex */
  justify-content: space-between;
}

.container section {
  padding: 0.5rem;
}

.opacity-0 {
  opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="description" content="Web site created using create-snowpack-app" />
  <link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>

<body>
  <header class="bg-gray-50">
    <div id="headerContent">
      <h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
      <p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
    </div>
  </header>
  <div class="container">
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 1</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 2</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>

    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 3</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
  </div>
  <footer class="opacity-0">
    <h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
    <p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
  </footer>
</body>

</html>
_x000D_
_x000D_
_x000D_

alert() not working in Chrome

put this line at the end of the body. May be the DOM is not ready yet at the moment this line is read by compiler.

<script type="text/javascript" src="script.js"></script>"

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

Your asp.net account {MACHINE}\ASPNET does not have write access to that location. That is the reason why its failing.

Consider granting access rights to the resource to the ASP.NET request identity.

Right click on downloading folder Properties > Security Tab > Edit > Add > locations > choose your local machine > click OK > Type ASPNET below "Enter the object name to select" > Click Check Names Check the boxes for the desired access (Full Control). If it will not work for you do the same with Network Service

Now this should show your local {MACHINENAME}\ASPNET account, then you set the write permission to this account.

Otherwise if the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.


Or just use dedicated location for storing files in ASP.NET which is App_Data. To create it right click on your ASP.NET Project (in Visual Studio) Add > Add ASP.NET Folder > App_Data. Then you'll be able to save data to this location:

var path = Server.MapPath("~/App_Data/file.txt");
System.IO.File.WriteAllText(path, "Hello World");

How to SELECT in Oracle using a DBLINK located in a different schema?

I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.

Calling a Sub and returning a value

Sub don't return values and functions don't have side effects.

Sometimes you want both side effect and return value.

This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:

Sub getValue(retValue as Long)
    ...
    retValue = 42 
End SUb 

Sub Main()
    Dim retValue As Long
    getValue retValue 
    ... 
End SUb

Is it possible to forward-declare a function in Python?

TL;DR: Python does not need forward declarations. Simply put your function calls inside function def definitions, and you'll be fine.

def foo(count):
    print("foo "+str(count))
    if(count>0):
        bar(count-1)

def bar(count):
    print("bar "+str(count))
    if(count>0):
        foo(count-1)

foo(3)
print("Finished.")

recursive function definitions, perfectly successfully gives:

foo 3
bar 2
foo 1
bar 0
Finished.

However,

bug(13)

def bug(count):
    print("bug never runs "+str(count))

print("Does not print this.")

breaks at the top-level invocation of a function that hasn't been defined yet, and gives:

Traceback (most recent call last):
  File "./test1.py", line 1, in <module>
    bug(13)
NameError: name 'bug' is not defined

Python is an interpreted language, like Lisp. It has no type checking, only run-time function invocations, which succeed if the function name has been bound and fail if it's unbound.

Critically, a function def definition does not execute any of the funcalls inside its lines, it simply declares what the function body is going to consist of. Again, it doesn't even do type checking. So we can do this:

def uncalled():
    wild_eyed_undefined_function()
    print("I'm not invoked!")

print("Only run this one line.")

and it runs perfectly fine (!), with output

Only run this one line.

The key is the difference between definitions and invocations.

The interpreter executes everything that comes in at the top level, which means it tries to invoke it. If it's not inside a definition.
Your code is running into trouble because you attempted to invoke a function, at the top level in this case, before it was bound.

The solution is to put your non-top-level function invocations inside a function definition, then call that function sometime much later.

The business about "if __ main __" is an idiom based on this principle, but you have to understand why, instead of simply blindly following it.

There are certainly much more advanced topics concerning lambda functions and rebinding function names dynamically, but these are not what the OP was asking for. In addition, they can be solved using these same principles: (1) defs define a function, they do not invoke their lines; (2) you get in trouble when you invoke a function symbol that's unbound.

MySQL, Check if a column exists in a table with SQL

Many thanks to Mfoo who has put the really nice script for adding columns dynamically if not exists in the table. I have improved his answer with PHP. The script additionally helps you find how many tables actually needed 'Add column' mysql comand. Just taste the recipe. Works like charm.

<?php
ini_set('max_execution_time', 0);

$host = 'localhost';
$username = 'root';
$password = '';
$database = 'books';

$con = mysqli_connect($host, $username, $password);
if(!$con) { echo "Cannot connect to the database ";die();}
mysqli_select_db($con, $database);
$result=mysqli_query($con, 'show tables');
$tableArray = array();
while($tables = mysqli_fetch_row($result)) 
{
     $tableArray[] = $tables[0];    
}

$already = 0;
$new = 0;
for($rs = 0; $rs < count($tableArray); $rs++)
{
    $exists = FALSE;

    $result = mysqli_query($con, "SHOW COLUMNS FROM ".$tableArray[$rs]." LIKE 'tags'");
    $exists = (mysqli_num_rows($result))?TRUE:FALSE;

    if($exists == FALSE)
    {
        mysqli_query($con, "ALTER TABLE ".$tableArray[$rs]." ADD COLUMN tags VARCHAR(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL");
        ++$new;
        echo '#'.$new.' Table DONE!<br/>';
    }
    else
    {
        ++$already;
        echo '#'.$already.' Field defined alrady!<br/>';    
    }
    echo '<br/>';
}
?>

Difference between web server, web container and application server

Web containers are responsible to provide the run time environment to web applications. It contains components that provide naming context and manages the life cycle of a web application. Web containers are a part of a web server and they generally processes the user request and send a static response.

Servlet containers are the one where JSP created components reside. They are basically responsible to provide dynamic content as per the user request. Basically, Web containers reply with a static content as per the user request, but Servlets can create the dynamic pages.

jQuery hasClass() - check for more than one class

$.fn.extend({
    hasClasses: function (selectors) {
        var self = this;
        for (var i in selectors) {
            if ($(self).hasClass(selectors[i])) 
                return true;
        }
        return false;
    }
});

$('#element').hasClasses(['class1', 'class2', 'class3']);

This should do it, simple and easy.

Setting environment variables for accessing in PHP when using Apache

Unbelievable, but on httpd 2.2 on centos 6.4 this works.

Export env vars in /etc/sysconfig/httpd

export mydocroot=/var/www/html

Then simply do this...

<VirtualHost *:80>
  DocumentRoot ${mydocroot}
</VirtualHost>

Then finally....

service httpd restart;

NodeJS: How to get the server's port?

You might be looking for process.env.PORT. This allows you to dynamically set the listening port using what are called "environment variables". The Node.js code would look like this:

const port = process.env.PORT || 3000; 
app.listen(port, () => {console.log(`Listening on port ${port}...`)}); 

You can even manually set the dynamic variable in the terminal using export PORT=5000, or whatever port you want.

MySQL: Grant **all** privileges on database

I had this challenge when working on MySQL Ver 8.0.21

I wanted to grant permissions of a database named my_app_db to the root user running on localhost host.

But when I run the command:

use my_app_db;

GRANT ALL PRIVILEGES ON my_app_db.* TO 'root'@'localhost';

I get the error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'my_app_db.* TO 'root'@'localhost'' at line 1>

Here's how I fixed:

Login to your MySQL console. You can change root to the user you want to login with:

mysql -u root -p

Enter your mysql root password

Next, list out all the users and their host on the MySQL server. Unlike PostgreSQL this is often stored in the mysql database. So we need to select the mysql database first:

use mysql;
SELECT user, host FROM user;

Note: if you don't run the use mysql, you get the no database selected error.

This should give you an output of this sort:

+------------------+-----------+
| user             | host      |
+------------------+-----------+
| mysql.infoschema | localhost |
| mysql.session    | localhost |
| mysql.sys        | localhost |
| root             | localhost |
+------------------+-----------+
4 rows in set (0.00 sec)

Next, based on the information gotten from the list, grant privileges to the user that you want. We will need to first select the database before granting permission to it. For me, I am using the root user that runs on the localhost host:

use my_app_db;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';

Note: The GRANT ALL PRIVILEGES ON database_name.* TO 'root'@'localhost'; command may not work for modern versions of MySQL. Most modern versions of MyQL replace the database_name with * in the grant privileges command after you select the database that you want to use.

You can then exit the MySQL console:

exit

That's it.

I hope this helps

How can I tell AngularJS to "refresh"

The solution was to call...

$scope.$apply();

...in my jQuery event callback.

How can I detect if this dictionary key exists in C#?

What is the type of c.PhysicalAddresses? If it's Dictionary<TKey,TValue>, then you can use the ContainsKey method.

Retrieving a property of a JSON object by index?

Jeroen Vervaeke's answer is modular and the works fine, but it can cause problems if it is using with jQuery or other libraries that count on "object-as-hashtables" feature of Javascript.

I modified it a little to make usable with these libs.

function getByIndex(obj, index) {
  return obj[Object.keys(obj)[index]];
}

Remove columns from DataTable in C#

The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable.

So for that, here is what I did, when I came across the same problem.

string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };

foreach (string ColName in ColumnsToBeDeleted)
{
    if (dt.Columns.Contains(ColName))
        dt.Columns.Remove(ColName);
}

PDO error message?

Try this instead:

print_r($sth->errorInfo());

Add this before your prepare:

$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.

Adding and removing extensionattribute to AD object

You could try using the -Clear parameter

Example:-Clear Attribute1LDAPDisplayName, Attribute2LDAPDisplayName

http://technet.microsoft.com/en-us/library/ee617215.aspx

Collection was modified; enumeration operation may not execute in ArrayList

Don't modify the list inside of a loop which iterates through the list.

Instead, use a for() or while() with an index, going backwards through the list. (This will let you delete things without getting an invalid index.)

var foo = new List<Bar>();

for(int i = foo.Count-1; i >= 0; --i)
{
  var item = foo[i];
  // do something with item
}

background: fixed no repeat not working on mobile

background-attachment:fixed in IOS Safari has been a known bug for as long as I can recall.

Here's some other options for you:

https://stackoverflow.com/a/23420490/1004312

Since the fixed position in general is not all that stable on touch (some more than others, Chrome works great), it is still acting up in Safari IOS 8 in situations that used to work in IOS 7, therefore I generally just use JS to detect touch devices, including Windows mobile.

/* ============== SUPPORTS TOUCH OR NOT ========= */
/*! Detects touch support and adds appropriate classes to html and returns a JS object
  Copyright (c) 2013 Izilla Partners Pty Ltd  | http://www.izilla.com.au 
  Licensed under the MIT license  |  https://coderwall.com/p/egbgdw 
*/
var supports = (function() {
    var d = document.documentElement,
        c = "ontouchstart" in window || navigator.msMaxTouchPoints;
    if (c) {
        d.className += " touch";
        return {
            touch: true
        }
    } else {
        d.className += " no-touch";
        return {
            touch: false
        }
    }
})();

CSS example assumes mobile first:

.myBackgroundPrecious {
   background: url(1.jpg) no-repeat center center;
   background-size: cover;
}

.no-touch .myBackgroundPrecious {
   background-attachment:fixed;
}

What is a serialVersionUID and why should I use it?

Field data represents some information stored in the class. Class implements the Serializable interface, so eclipse automatically offered to declare the serialVersionUID field. Lets start with value 1 set there.

If you don't want that warning to come, use this:

@SuppressWarnings("serial")

Pass arguments into C program from command line

Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.

How to declare a static const char* in your header file?

Constant initializer allowed by C++ Standard only for integral or enumeration types. See 9.4.2/4 for details:

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.

And 9.4.2/7:

Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).

So you should write somewhere in cpp file:

const char* SomeClass::SOMETHING = "sommething";

Java Multithreading concept and join() method

My Comments:

When I see the output, the output is mixed with One, Two, Three which are the thread names and they run simultaneously. I am not sure when you say thread is not running by main method.

Not sure if I understood your question or not. But I m putting my answer what I could understand, hope it can help you.

1) Then you created the object, it called the constructor, in construct it has start method which started the thread and executed the contents written inside run() method.

So as you created 3 objects (3 threads - one, two, three), all 3 threads started executing simultaneously.

2) Join and Synchronization They are 2 different things, Synchronization is when there are multiple threads sharing a common resource and one thread should use that resource at a time. E.g. Threads such as DepositThread, WithdrawThread etc. do share a common object as BankObject. So while DepositThread is running, the WithdrawThread will wait if they are synchronized. wait(), notify(), notifyAll() are used for inter-thread communication. Plz google to know more.

about Join(), it is when multiple threads are running, but you join. e.g. if there are two thread t1 and t2 and in multi-thread env they run, the output would be: t1-0 t2-0 t1-1 t2-1 t1-2 t2-2

and we use t1.join(), it would be: t1-0 t1-1 t1-2 t2-0 t2-1 t2-2

This is used in realtime when sometimes you don't mix up the thread in certain conditions and one depends another to be completed (not in shared resource), so you can call the join() method.

The import org.apache.commons cannot be resolved in eclipse juno

You could just add one needed external jar file to the project. Go to your project-->java build path-->libraries, add external JARS.Then add your downloaded file from the formal website. My default name is commons-codec-1.10.jar

How eliminate the tab space in the column in SQL Server 2008

See it might be worked -------

UPDATE table_name SET column_name=replace(column_name, ' ', '') //Remove white space

UPDATE table_name SET column_name=replace(column_name, '\n', '') //Remove newline

UPDATE table_name SET column_name=replace(column_name, '\t', '') //Remove all tab

Thanks Subroto

Print "hello world" every X seconds

Here's another simple way using Runnable interface in Thread Constructor

public class Demo {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i = 0; i < 5; i++){
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("Thread T1 : "+i);
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i = 0; i < 5; i++) {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("Thread T2 : "+i);
                }
            }
        });

        Thread t3 = new Thread(new Runnable() {

            @Override
            public void run() {
                for(int i = 0; i < 5; i++){
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("Thread T3 : "+i);
                }
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}

IIS7 Settings File Locations

Also check this answer from here: Cannot manually edit applicationhost.config

The answer is simple, if not that obvious: win2008 is 64bit, notepad++ is 32bit. When you navigate to Windows\System32\inetsrv\config using explorer you are using a 64bit program to find the file. When you open the file using using notepad++ you are trying to open it using a 32bit program. The confusion occurs because, rather than telling you that this is what you are doing, windows allows you to open the file but when you save it the file's path is transparently mapped to Windows\SysWOW64\inetsrv\Config.

So in practice what happens is you open applicationhost.config using notepad++, make a change, save the file; but rather than overwriting the original you are saving a 32bit copy of it in Windows\SysWOW64\inetsrv\Config, therefore you are not making changes to the version that is actually used by IIS. If you navigate to the Windows\SysWOW64\inetsrv\Config you will find the file you just saved.

How to get around this? Simple - use a 64bit text editor, such as the normal notepad that ships with windows.

How does one use glide to download an image into a bitmap?

UPDATE FOR NEW VERSION

Glide.with(context.applicationContext)
    .load(url)
    .listener(object : RequestListener<Drawable> {
        override fun onLoadFailed(
            e: GlideException?,
            model: Any?,
            target: Target<Drawable>?,
            isFirstResource: Boolean
        ): Boolean {
            listener?.onLoadFailed(e)
            return false
        }

        override fun onResourceReady(
            resource: Drawable?,
            model: Any?,
            target: com.bumptech.glide.request.target.Target<Drawable>?,
            dataSource: DataSource?,
            isFirstResource: Boolean
        ): Boolean {
            listener?.onLoadSuccess(resource)
            return false
        }

    })
    .into(this)

OLD ANSWER

@outlyer's answer is correct, but there're some changes in new Glide version

My version: 4.7.1

Code:

 Glide.with(context.applicationContext)
                .asBitmap()
                .load(iconUrl)
                .into(object : SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                    override fun onResourceReady(resource: Bitmap, transition: com.bumptech.glide.request.transition.Transition<in Bitmap>?) {
                        callback.onReady(createMarkerIcon(resource, iconId))
                    }
                })

Note: this code run in UI Thread, thus you can use AsyncTask, Executor or somethings else for concurrency (like @outlyer's code) If you want to get original size, put Target.SIZE_ORIGINA as my code. Don't use -1, -1

Copying text outside of Vim with set mouse=a enabled

em... Keep pressing Shift and then click the right mouse button

using mailto to send email with an attachment

what about this

<FORM METHOD="post" ACTION="mailto:[email protected]" ENCTYPE="multipart/form-data">
Attachment: <INPUT TYPE="file" NAME="attachedfile" MAXLENGTH=50 ALLOW="text/*" >
 <input type="submit" name="submit" id="submit" value="Email"/>
</FORM>

Java escape JSON String?

Apache Commons

If you're already using Apache commons, it provides a static method for this:

StringEscapeUtils.escapeJson("some string")

It converts any string into one that's properly escaped for inclusion in JSON

See the documentation here

Determine device (iPhone, iPod Touch) with iOS

if([UIDevice currentDevice].userInterfaceIdiom==UIUserInterfaceIdiomPad) {
    //Device is ipad 
}else{
    //Device is iphone
}

How to submit http form using C#

Response.Write("<script> try {this.submit();} catch(e){} </script>");

How to find a hash key containing a matching value

You could use hashname.key(valuename)

Or, an inversion may be in order. new_hash = hashname.invert will give you a new_hash that lets you do things more traditionally.

Visual Studio: How to break on handled exceptions?

There is an 'exceptions' window in VS2005 ... try Ctrl+Alt+E when debugging and click on the 'Thrown' checkbox for the exception you want to stop on.

Testing if a list of integer is odd or even

Just use the modulus

loop through the list and run the following on each item

if(num % 2 == 0)
{
  //is even
}
else
{
  //is odd
}

Alternatively if you want to know if all are even you can do something like this:

bool allAreEven = lst.All(x => x % 2 == 0);

How to solve java.lang.NullPointerException error?

This error occures when you try to refer to a null object instance. I can`t tell you what causes this error by your given information, but you can debug it easily in your IDE. I strongly recommend you that use exception handling to avoid unexpected program behavior.

Is it possible to make desktop GUI application in .NET Core?

For creating a console-based UI, you can use gui.cs. It is open-source (from Miguel de Icaza, creator of Xamarin), and runs on .NET Core on Windows, Linux, and macOS.

It has the following components:

  • Buttons
  • Labels
  • Text entry
  • Text view
  • Time editing field
  • Radio buttons
  • Checkboxes
  • Dialog boxes
    • Message boxes
  • Windows
  • Menus
  • ListViews
  • Frames
  • ProgressBars
  • Scroll views and Scrollbars
  • Hexadecimal viewer/editor (HexView)

Sample screenshot

gui.cs sample output screenshot

How to form tuple column from two columns in Pandas

Pandas has the itertuples method to do exactly this:

list(df[['lat', 'long']].itertuples(index=False, name=None))

setTimeout or setInterval?

setInterval()

setInterval() is a time interval based code execution method that has the native ability to repeatedly run a specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().

If you want to loop code for animations or on a clock tick, then use setInterval().

function doStuff() {
    alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);

setTimeout()

setTimeout() is a time based code execution method that will execute a script only one time when the interval is reached. It will not repeat again unless you gear it to loop the script by nesting the setTimeout() object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().

function doStuff() {
    alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);

If you want something to happen one time after a specified period of time, then use setTimeout(). That is because it only executes one time when the specified interval is reached.

Java - ignore exception and continue

Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?

.mp4 file not playing in chrome

I was actually running into some strange errors with mp4's a while ago. What fixed it for me was re-encoding the video using known supported codecs (H.264 & MP3).

I actually used the VLC player to do so and it worked fine afterward. I converted using the mentioned codecs H.264/MP3. That solved it for me.

Maybe the problem is not in the format but in the JavaScript implementation of the play/ pause methods. May I suggest visiting the following link where Google developer explains it in a good way?

Additionally, you could choose to use the newer webp format, which Chrome supports out of the box, but be careful with other browsers. Check the support for it before implementation. Here's a link that describes the mentioned format.

On that note: I've created a small script that easily converts all standard formats to webp. You can easily configure it to fit your needs. Here's the Github repo of the same projects.

How to replace an entire line in a text file by line number

I actually used this script to replace a line of code in the cron file on our company's UNIX servers awhile back. We executed it as normal shell script and had no problems:

#Create temporary file with new line in place
cat /dir/file | sed -e "s/the_original_line/the_new_line/" > /dir/temp_file
#Copy the new file over the original file
mv /dir/temp_file /dir/file

This doesn't go by line number, but you can easily switch to a line number based system by putting the line number before the s/ and placing a wildcard in place of the_original_line.

How to send email from SQL Server?

You can do it with a cursor also. Assuming that you have created an Account and a Profile e.g. "profile" and an Account and you have the table that holds the emails ready e.g. "EmailMessageTable" you can do the following:

USE database_name
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE mass_email AS
declare @email nvarchar (50) 
declare @body nvarchar (255)  

declare test_cur cursor for             
SELECT email from [dbo].[EmailMessageTable]

open test_cur                                        

fetch next from test_cur into   
@email     
while @@fetch_status = 0       
begin                                    

set @body = (SELECT body from [dbo].[EmailMessageTable] where email = @email)
EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'profile',
    @recipients = @email,
    @body = @body,
    @subject = 'Credentials for Web';
fetch next from test_cur into  
@email 
end    
close test_cur   
deallocate test_cur

After that all you have to do is execute the Stored Procedure

EXECUTE mass_email
GO

How to display Woocommerce Category image?

_x000D_
_x000D_
<?php _x000D_
_x000D_
 $terms = get_terms( array(_x000D_
 'taxonomy' => 'product_cat',_x000D_
 'hide_empty' => false,_x000D_
 ) ); // Get Terms_x000D_
_x000D_
foreach ($terms as $key => $value) _x000D_
{_x000D_
 $metaterms = get_term_meta($value->term_id);_x000D_
 $thumbnail_id = get_woocommerce_term_meta($value->term_id, 'thumbnail_id', true );_x000D_
 $image = wp_get_attachment_url( $thumbnail_id );_x000D_
 echo '<img src="'.$image.'" alt="" />';_x000D_
} // Get Images from woocommerce term meta_x000D_
_x000D_
?>
_x000D_
_x000D_
_x000D_

how to bypass Access-Control-Allow-Origin?

Okay, but you all know that the * is a wildcard and allows cross site scripting from every domain?

You would like to send multiple Access-Control-Allow-Origin headers for every site that's allowed to - but unfortunately its officially not supported to send multiple Access-Control-Allow-Origin headers, or to put in multiple origins.

You can solve this by checking the origin, and sending back that one in the header, if it is allowed:

$origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = [
    'http://mysite1.com',
    'https://www.mysite2.com',
    'http://www.mysite2.com',
];

if (in_array($origin, $allowed_domains)) {
    header('Access-Control-Allow-Origin: ' . $origin);
}

Thats much safer. You might want to edit the matching and change it to a manual function with some regex, or something like that. At least this will only send back 1 header, and you will be sure its the one that the request came from. Please do note that all HTTP headers can be spoofed, but this header is for the client's protection. Don't protect your own data with those values. If you want to know more, read up a bit on CORS and CSRF.

Why is it safer?

Allowing access from other locations then your own trusted site allows for session highjacking. I'm going to go with a little example - image Facebook allows a wildcard origin - this means that you can make your own website somewhere, and make it fire AJAX calls (or open iframes) to facebook. This means you can grab the logged in info of the facebook of a visitor of your website. Even worse - you can script POST requests and post data on someone's facebook - just while they are browsing your website.

Be very cautious when using the ACAO headers!

How to set back button text in Swift

although these answers fix the problem but this could be some useful

class MainNavigatioController: UINavigationController {

    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        // first
        let backItem = UIBarButtonItem()
        backItem.title = "????"
        self.viewControllers.last?.navigationItem.backBarButtonItem = backItem
        // then
        super.pushViewController(viewController, animated: animated)

    }

}

How to dockerize maven project? and how many ways to accomplish it?

There may be many ways.. But I implemented by following two ways

Given example is of maven project.

1. Using Dockerfile in maven project

Use the following file structure:

Demo
+-- src
|    +-- main
|    ¦   +-- java
|    ¦       +-- org
|    ¦           +-- demo
|    ¦               +-- Application.java
|    ¦   
|    +-- test
|
+---- Dockerfile
+---- pom.xml

And update the Dockerfile as:

FROM java:8
EXPOSE 8080
ADD /target/demo.jar demo.jar
ENTRYPOINT ["java","-jar","demo.jar"]

Navigate to the project folder and type following command you will be ab le to create image and run that image:

$ mvn clean
$ mvn install
$ docker build -f Dockerfile -t springdemo .
$ docker run -p 8080:8080 -t springdemo

Get video at Spring Boot with Docker

2. Using Maven plugins

Add given maven plugin in pom.xml

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.5</version>
        <configuration>
            <imageName>springdocker</imageName>
            <baseImage>java</baseImage>
            <entryPoint>["java", "-jar", "/${project.build.finalName}.jar"]</entryPoint>
            <resources>
                <resource>
                    <targetPath>/</targetPath>
                    <directory>${project.build.directory}</directory>
                    <include>${project.build.finalName}.jar</include>
                </resource>
            </resources>
        </configuration>
    </plugin>

Navigate to the project folder and type following command you will be able to create image and run that image:

$ mvn clean package docker:build
$ docker images
$ docker run -p 8080:8080 -t <image name>

In first example we are creating Dockerfile and providing base image and adding jar an so, after doing that we will run docker command to build an image with specific name and then run that image..

Whereas in second example we are using maven plugin in which we providing baseImage and imageName so we don't need to create Dockerfile here.. after packaging maven project we will get the docker image and we just need to run that image..

How do I center text vertically and horizontally in Flutter?

Put the Text in a Center:

Container(
      height: 45,
      color: Colors.black,
      child: Center(
        child: Text(
            'test',
            style: TextStyle(color: Colors.white),
        ),
      ),
    );

Allowing Untrusted SSL Certificates with HttpClient

If you're attempting to do this in a .NET Standard library, here's a simple solution, with all of the risks of just returning true in your handler. I leave safety up to you.

var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback = 
    (httpRequestMessage, cert, cetChain, policyErrors) =>
{
    return true;
};

var client = new HttpClient(handler);

Parse JSON object with string and value only

My pseudocode example will be as follows:

JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();

for (each json in jsonArray) {
    String id = json.get("id");
    String name = json.get("name");

    newJson.put(id, name);
}

return newJson;

What is the difference between a pandas Series and a single-column DataFrame?

Quoting the Pandas docs

pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure.

So, the Series is the data structure for a single column of a DataFrame, not only conceptually, but literally, i.e. the data in a DataFrame is actually stored in memory as a collection of Series.

Analogously: We need both lists and matrices, because matrices are built with lists. Single row matricies, while equivalent to lists in functionality still cannot exist without the list(s) they're composed of.

They both have extremely similar APIs, but you'll find that DataFrame methods always cater to the possibility that you have more than one column. And, of course, you can always add another Series (or equivalent object) to a DataFrame, while adding a Series to another Series involves creating a DataFrame.

Copy files to network computers on windows command line

Below command will work in command prompt:

copy c:\folder\file.ext \\dest-machine\destfolder /Z /Y

To Copy all files:

copy c:\folder\*.* \\dest-machine\destfolder /Z /Y

SSL InsecurePlatform error when using Requests package

I just had a similar issue on a CentOS 5 server where I installed python 2.7.12 in /usr/local on top of a much older version of python2.7. Upgrading to CentOS 6 or 7 isn't an option on this server right now.

Some of the python 2.7 modules were still existing from the older version of python, but pip was failing to upgrade because the newer cryptography package is not supported by the CentOS 5 packages.

Specifically, 'pip install requests[security]' was failing because the openssl version on the CentOS 5 was 0.9.8e which is no longer supported by cryptography > 1.4.0.

To solve the OPs original issue I did:

1) pip install 'cryptography<1.3.5,>1.3.0'.  

This installed cryptography 1.3.4 which works with openssl-0.9.8e. cryptograpy 1.3.4 is also sufficient to satisfy the requirement for the following command.

2) pip install 'requests[security]'

This command now installs because it doesn't try to install cryptography > 1.4.0.

Note that on Centos 5 I also needed to:

yum install openssl-devel

To allow cryptography to build

JavaScript: IIF like statement

I typed this in my URL bar:

javascript:{ var col = 'screwdriver'; var x = '<option value="' + col + '"' + ((col == 'screwdriver') ? ' selected' : '') + '>Very roomy</option>'; alert(x); }

How to check if an object is an array?

Other methods also exist to check but I prefer the following method as my best to check (as you can easily check types of other objects).

> a = [1, 2]
[ 1, 2 ]
>
> Object.prototype.toString.call(a).slice(8,).replace(/\]$/, '')
'Array'
>
> Object.prototype.toString.call([]).slice(8,-1) // best approach
'Array'

Explanation (with simple examples on Node REPL)»

> o = {'ok': 1}
{ ok: 1 }
> a = [1, 2]
[ 1, 2 ]
> typeof o
'object'
> typeof a
'object'
>
> Object.prototype.toString.call(o)
'[object Object]'
> Object.prototype.toString.call(a)
'[object Array]'
>

Object or Array »

> Object.prototype.toString.call(o).slice(8,).replace(/\]$/, '')
'Object'
>
> Object.prototype.toString.call(a).slice(8,).replace(/\]$/, '')
'Array'
>

Null or Undefined »

> Object.prototype.toString.call(undefined).slice(8,).replace(/\]$/, '')
'Undefined'
> Object.prototype.toString.call(null).slice(8,).replace(/\]$/, '')
'Null'
>

String »

> Object.prototype.toString.call('ok').slice(8,).replace(/\]$/, '')
'String'

Number »

> Object.prototype.toString.call(19).slice(8,).replace(/\]$/, '')
'Number'
> Object.prototype.toString.call(19.0).slice(8,).replace(/\]$/, '')
'Number'
> Object.prototype.toString.call(19.7).slice(8,).replace(/\]$/, '')
'Number'
>

I appreciate @mpen's suggestion to use -1 in place of regular expression as follows.

> Object.prototype.toString.call(12).slice(8,-1)
'Number'
>
> Object.prototype.toString.call(12.0).slice(8,-1)
'Number'
>
> Object.prototype.toString.call([]).slice(8,-1)
'Array'
> Object.prototype.toString.call({}).slice(8,-1)
'Object'
>
> Object.prototype.toString.call('').slice(8,-1)
'String'
>

How to delete a certain row from mysql table with same column values?

You need to specify the number of rows which should be deleted. In your case (and I assume that you only want to keep one) this can be done like this:

DELETE FROM your_table WHERE id_users=1 AND id_product=2
LIMIT (SELECT COUNT(*)-1 FROM your_table WHERE id_users=1 AND id_product=2)

How to find index of list item in Swift?

Swift 2.1

var array = ["0","1","2","3"]

if let index = array.indexOf("1") {
   array.removeAtIndex(index)
}

print(array) // ["0","2","3"]

Swift 3

var array = ["0","1","2","3"]

if let index = array.index(of: "1") {
    array.remove(at: index)
}
array.remove(at: 1)

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

Goto to SQL server using windows Credentials - > Logins - > Select the Login - > in the Properties -> Check if the Log in is enabled/disabled. If Disabled, make it enable, this solution worked for me.

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

java.lang.ClassNotFoundException: HttpServletRequest

The same error i got

Caused by: org.apache.catalina.LifecycleException: A child container failed during start

I deleted the project from eclipse work space , deleted .settings folder of project and re imported to the eclipse. Did the trick for me.

How to make a gui in python

Using Qt in Python is a really pleasant experience: http://wiki.python.org/moin/PyQt

For the quick tutorial: http://zetcode.com/tutorials/pyqt4/

Populate one dropdown based on selection in another

Setup mine within a closure and with straight JavaScript, explanation provided in comments

_x000D_
_x000D_
(function() {_x000D_
_x000D_
  //setup an object fully of arrays_x000D_
  //alternativly it could be something like_x000D_
  //{"yes":[{value:sweet, text:Sweet}.....]}_x000D_
  //so you could set the label of the option tag something different than the name_x000D_
  var bOptions = {_x000D_
    "yes": ["sweet", "wohoo", "yay"],_x000D_
    "no": ["you suck!", "common son"]_x000D_
  };_x000D_
_x000D_
  var A = document.getElementById('A');_x000D_
  var B = document.getElementById('B');_x000D_
_x000D_
  //on change is a good event for this because you are guarenteed the value is different_x000D_
  A.onchange = function() {_x000D_
    //clear out B_x000D_
    B.length = 0;_x000D_
    //get the selected value from A_x000D_
    var _val = this.options[this.selectedIndex].value;_x000D_
    //loop through bOption at the selected value_x000D_
    for (var i in bOptions[_val]) {_x000D_
      //create option tag_x000D_
      var op = document.createElement('option');_x000D_
      //set its value_x000D_
      op.value = bOptions[_val][i];_x000D_
      //set the display label_x000D_
      op.text = bOptions[_val][i];_x000D_
      //append it to B_x000D_
      B.appendChild(op);_x000D_
    }_x000D_
  };_x000D_
  //fire this to update B on load_x000D_
  A.onchange();_x000D_
_x000D_
})();
_x000D_
<select id='A' name='A'>_x000D_
  <option value='yes' selected='selected'>yes_x000D_
  <option value='no'> no_x000D_
</select>_x000D_
<select id='B' name='B'>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Difference between a theta join, equijoin and natural join

@outis's answer is good: concise and correct as regards relations.

However, the situation is slightly more complicated as regards SQL.

Consider the usual suppliers and parts database but implemented in SQL:

SELECT * FROM S NATURAL JOIN SP;

would return a resultset** with columns

SNO, SNAME, STATUS, CITY, PNO, QTY

The join is performed on the column with the same name in both tables, SNO. Note that the resultset has six columns and only contains one column for SNO.

Now consider a theta eqijoin, where the column names for the join must be explicitly specified (plus range variables S and SP are required):

SELECT * FROM S JOIN SP ON S.SNO = SP.SNO;

The resultset will have seven columns, including two columns for SNO. The names of the resultset are what the SQL Standard refers to as "implementation dependent" but could look like this:

SNO, SNAME, STATUS, CITY, SNO, PNO, QTY

or perhaps this

S.SNO, SNAME, STATUS, CITY, SP.SNO, PNO, QTY

In other words, NATURAL JOIN in SQL can be considered to remove columns with duplicated names from the resultset (but alas will not remove duplicate rows - you must remember to change SELECT to SELECT DISTINCT yourself).


** I don't quite know what the result of SELECT * FROM table_expression; is. I know it is not a relation because, among other reasons, it can have columns with duplicate names or a column with no name. I know it is not a set because, among other reasons, the column order is significant. It's not even a SQL table or SQL table expression. I call it a resultset.

unable to set private key file: './cert.pem' type PEM

I faced this issue when I had used Open SSL and the solution was to split the cert in 3 files and use all of them doing the call with Curl:

openssl pkcs12 -in mycert.p12 -out ca.pem -cacerts -nokeys
openssl pkcs12 -in mycert.p12 -out client.pem -clcerts -nokeys 
openssl pkcs12 -in mycert.p12 -out key.pem -nocerts

curl --insecure --key key.pem --cacert ca.pem --cert client.pem:KeyChoosenByMeWhenIrunOpenSSL https://thesite

Inserting Data into Hive Table

this is supported from version hive 0.14

INSERT INTO TABLE pd_temp(dept,make,cost,id,asmb_city,asmb_ct,retail) VALUES('production','thailand',10,99202,'northcarolina','usa',20)

member names cannot be the same as their enclosing type C#

As Constructor should be at the starting of the Class , you are facing the above issue . So, you can either change the name or if you want to use it as a constructor just copy the method at the beginning of the class.

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

How can I center text (horizontally and vertically) inside a div block?

<div class="small-container">
    <span>Text centered</span>
</div>

<style>
.small-container {
    width:250px;
    height:250px;
    border:1px green solid;
    text-align:center;
    position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}
.small-container span{
    position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}
</style>

How do I stop a program when an exception is raised in Python?

import sys

try:
    import feedparser
except:
    print "Error: Cannot import feedparser.\n" 
    sys.exit(1)

Here we're exiting with a status code of 1. It is usually also helpful to output an error message, write to a log, and clean up.

fatal: Not a valid object name: 'master'

First off, when you create a "bare repository", you're not going to be doing any work with it (it doesn't contain a working copy, so the git branch command is not useful).

Now, the reason you wouldn't have a master branch even after doing a git init is that there are no commits: when you create your first commit, you will then have a master branch.

Show all current locks from get_lock

From MySQL 5.7 onwards, this is possible, but requires first enabling the mdl instrument in the performance_schema.setup_instruments table. You can do this temporarily (until the server is next restarted) by running:

UPDATE performance_schema.setup_instruments
SET enabled = 'YES'
WHERE name = 'wait/lock/metadata/sql/mdl';

Or permanently, by adding the following incantation to the [mysqld] section of your my.cnf file (or whatever config files MySQL reads from on your installation):

[mysqld]
performance_schema_instrument = 'wait/lock/metadata/sql/mdl=ON'

(Naturally, MySQL will need to be restarted to make the config change take effect if you take the latter approach.)

Locks you take out after the mdl instrument has been enabled can be seen by running a SELECT against the performance_schema.metadata_locks table. As noted in the docs, GET_LOCK locks have an OBJECT_TYPE of 'USER LEVEL LOCK', so we can filter our query down to them with a WHERE clause:

mysql> SELECT GET_LOCK('foobarbaz', -1);
+---------------------------+
| GET_LOCK('foobarbaz', -1) |
+---------------------------+
|                         1 |
+---------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM performance_schema.metadata_locks 
    -> WHERE OBJECT_TYPE='USER LEVEL LOCK'
    -> \G
*************************** 1. row ***************************
          OBJECT_TYPE: USER LEVEL LOCK
        OBJECT_SCHEMA: NULL
          OBJECT_NAME: foobarbaz
OBJECT_INSTANCE_BEGIN: 139872119610944
            LOCK_TYPE: EXCLUSIVE
        LOCK_DURATION: EXPLICIT
          LOCK_STATUS: GRANTED
               SOURCE: item_func.cc:5482
      OWNER_THREAD_ID: 35
       OWNER_EVENT_ID: 3
1 row in set (0.00 sec)

mysql> 

The meanings of the columns in this result are mostly adequately documented at https://dev.mysql.com/doc/refman/en/metadata-locks-table.html, but one point of confusion is worth noting: the OWNER_THREAD_ID column does not contain the connection ID (like would be shown in the PROCESSLIST or returned by CONNECTION_ID()) of the thread that holds the lock. Confusingly, the term "thread ID" is sometimes used as a synonym of "connection ID" in the MySQL documentation, but this is not one of those times. If you want to determine the connection ID of the connection that holds a lock (for instance, in order to kill that connection with KILL), you'll need to look up the PROCESSLIST_ID that corresponds to the THREAD_ID in the performance_schema.threads table. For instance, to kill the connection that was holding my lock above...

mysql> SELECT OWNER_THREAD_ID FROM performance_schema.metadata_locks
    -> WHERE OBJECT_TYPE='USER LEVEL LOCK'
    -> AND OBJECT_NAME='foobarbaz';
+-----------------+
| OWNER_THREAD_ID |
+-----------------+
|              35 |
+-----------------+
1 row in set (0.00 sec)

mysql> SELECT PROCESSLIST_ID FROM performance_schema.threads
    -> WHERE THREAD_ID=35;
+----------------+
| PROCESSLIST_ID |
+----------------+
|             10 |
+----------------+
1 row in set (0.00 sec)

mysql> KILL 10;
Query OK, 0 rows affected (0.00 sec)

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

In typescript you can do the following to suppress the error:

let subString?: string;

subString > !null; - Note the added exclamation mark before null.

How do I prevent CSS inheritance?

For example if you have two div in XHTML document.

<div id='div1'>
    <p>hello, how are you?</p>
    <div id='div2'>
        <p>I am fine, thank you.</p>
    </div>
</div>

Then try this in CSS.

#div1 > #div2 > p{
    color: red;
}

affect only 'div2' paragraph.

#div1 > p {
    color: red;
} 

affect only 'div1' paragraph.

matplotlib has no attribute 'pyplot'

pyplot is a sub-module of matplotlib which doesn't get imported with a simple import matplotlib.

>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>> 

It seems customary to do: import matplotlib.pyplot as plt at which time you can use the various functions and classes it contains:

p = plt.plot(...)

Print a file's last modified date in Bash

EDITED: turns out that I had forgotten the quotes needed for $entry in order to print correctly and not give the "no such file or directory" error. Thank you all so much for helping me!

Here is my final code:

    echo "Please type in the directory you want all the files to be listed with last modified dates" #bash can't find file creation dates

read directory

for entry in "$directory"/*

do
modDate=$(stat -c %y "$entry") #%y = last modified. Qoutes are needed otherwise spaces in file name with give error of "no such file"
modDate=${modDate%% *} #%% takes off everything off the string after the date to make it look pretty
echo $entry:$modDate

Prints out like this:

/home/joanne/Dropbox/cheat sheet.docx:2012-03-14
/home/joanne/Dropbox/Comp:2013-05-05
/home/joanne/Dropbox/Comp 150 java.zip:2013-02-11
/home/joanne/Dropbox/Comp 151 Java 2.zip:2013-02-11
/home/joanne/Dropbox/Comp 162 Assembly Language.zip:2013-02-11
/home/joanne/Dropbox/Comp 262 Comp Architecture.zip:2012-12-12
/home/joanne/Dropbox/Comp 345 Image Processing.zip:2013-02-11
/home/joanne/Dropbox/Comp 362 Operating Systems:2013-05-05
/home/joanne/Dropbox/Comp 447 Societal Issues.zip:2013-02-11

Convert integer to hex and hex to integer

SQL Server equivalents to Excel's string-based DEC2HEX, HEX2DEC functions:

--Convert INT to hex string:
PRINT CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), 16777215),2) --DEC2HEX

--Convert hex string to INT:
PRINT CONVERT(INT,CONVERT(VARBINARY(4),'00FFFFFF',2)) --HEX2DEC

Create Pandas DataFrame from a string

A simple way to do this is to use StringIO.StringIO (python2) or io.StringIO (python3) and pass that to the pandas.read_csv function. E.g:

import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

TESTDATA = StringIO("""col1;col2;col3
    1;4.4;99
    2;4.5;200
    3;4.7;65
    4;3.2;140
    """)

df = pd.read_csv(TESTDATA, sep=";")

Response::json() - Laravel 5.1

From a controller you can also return an Object/Array and it will be sent as a JSON response (including the correct HTTP headers).

public function show($id)
{
    return Customer::find($id);
}

ReportViewer Client Print Control "Unable to load client print control"?

Unable to load Client Print Control!
Everytime, clients wanted to print report by clicking the button print on their report viewer, they always got this error message.

I had spent nearly two weeks to fix this problem.
My environment is:
- Window Server 2003 Standard Edition R2
- Report Server Version 10.X.X.X
- Clients with windowXP SP3
My Solution is:
- Replacing the CAP file (RSClientPrint-x86.cab) in C\Program Files\Microsoft SQL
Server\MSRS10.MSSQLSERVER\Reporting Services\ReportServer\bin\
- Extract the RSClientPrint-x86.cab and destribute it to clients.


Hear is the CAB file: https://sites.google.com/site/narithsite/Home/RSClientPrint-x86.cab?attredirects=0&d=1

How to remove border from specific PrimeFaces p:panelGrid?

If BalusC answer doesn't work try this:

.companyHeaderGrid td {
     border-style: hidden !important;
}

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

In addition to REMOTE_ADDR and HTTP_X_FORWARDED_FOR there are some other headers that can be set such as:

  • HTTP_CLIENT_IP
  • HTTP_X_FORWARDED_FOR can be comma delimited list of IPs
  • HTTP_X_FORWARDED
  • HTTP_X_CLUSTER_CLIENT_IP
  • HTTP_FORWARDED_FOR
  • HTTP_FORWARDED

I found the code on the following site useful:
http://www.grantburton.com/?p=97

Find the smallest positive integer that does not occur in a given sequence

C# solution:

    public int solution(int[] A)
    {
        int result = 1;

        // write your code in Java SE 8
        foreach(int num in A)
        {
            if (num == result)
               result++;

            while (A.Contains(result))
                result++;
        }

        return result;
    }

Import Certificate to Trusted Root but not to Personal [Command Line]

If there are multiple certificates in a pfx file (key + corresponding certificate and a CA certificate) then this command worked well for me:

certutil -importpfx c:\somepfx.pfx this works but still a password is needed to be typed in manually for private key. Including -p and "password" cause error too many arguments for certutil on XP

Default values and initialization in Java

In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.

In the second code sample, a is class member variable, hence it will be initialized to the default value.

Difference between 2 dates in SQLite

In my case, I have to calculate the difference in minutes and julianday() does not give an accurate value. Instead, I use strftime():

SELECT (strftime('%s', [UserEnd]) - strftime('%s', [UserStart])) / 60

Both dates are converted to unixtime (seconds), then subtracted to get value in seconds between the two dates. Next, divide it by 60.

https://www.sqlite.org/cvstrac/wiki?p=DateAndTimeFunctions

How can I get file extensions with JavaScript?

Wallacer's answer is nice, but one more checking is needed.

If file has no extension, it will use filename as extension which is not good.

Try this one:

return ( filename.indexOf('.') > 0 ) ? filename.split('.').pop().toLowerCase() : 'undefined';

Mod in Java produces negative numbers

If the modulus is a power of 2 then you can use a bitmask:

int i = -1 & ~-2; // -1 MOD 2 is 1

By comparison the Pascal language provides two operators; REM takes the sign of the numerator (x REM y is x - (x DIV y) * y where x DIV y is TRUNC(x / y)) and MOD requires a positive denominator and returns a positive result.

Simplest way to restart service on a remote computer

I recommend the method given by doofledorfer.

If you really want to do it via a direct API call, then look at the OpenSCManager function. Below are sample functions to take a machine name and service, and stop or start them.

function ServiceStart(sMachine, sService : string) : boolean;  //start service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    psTemp     : PChar;
    dwChkP     : DWord;
begin
  ss.dwCurrentState := 0;
  schm := OpenSCManager(PChar(sMachine),Nil,SC_MANAGER_CONNECT);  //connect to the service control manager

  if(schm > 0)then begin // if successful...
    schs := OpenService( schm,PChar(sService),SERVICE_START or SERVICE_QUERY_STATUS);    // open service handle, start and query status
    if(schs > 0)then begin     // if successful...
      psTemp := nil;
      if (StartService(schs,0,psTemp)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_RUNNING <> ss.dwCurrentState)do begin
          dwChkP := ss.dwCheckPoint;  //dwCheckPoint contains a value incremented periodically to report progress of a long operation.  Store it.
          Sleep(ss.dwWaitHint);  //Sleep for recommended time before checking status again
          if(not QueryServiceStatus(schs,ss))then
            break;  //couldn't check status
          if(ss.dwCheckPoint < dwChkP)then
            Break;  //if QueryServiceStatus didn't work for some reason, avoid infinite loop
        end;  //while not running
      CloseServiceHandle(schs);
    end;  //if able to get service handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_RUNNING = ss.dwCurrentState;  //if we were able to start it, return true
end;

function ServiceStop(sMachine, sService : string) : boolean;  //stop service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    dwChkP     : DWord;
begin
  schm := OpenSCManager(PChar(sMachine),nil,SC_MANAGER_CONNECT);

  if(schm > 0)then begin
    schs := OpenService(schm,PChar(sService),SERVICE_STOP or SERVICE_QUERY_STATUS);
    if(schs > 0)then begin
      if (ControlService(schs,SERVICE_CONTROL_STOP,ss)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_STOPPED <> ss.dwCurrentState) do begin
          dwChkP := ss.dwCheckPoint;
          Sleep(ss.dwWaitHint);
          if(not QueryServiceStatus(schs,ss))then
            Break;

          if(ss.dwCheckPoint < dwChkP)then
            Break;
        end;  //while
      CloseServiceHandle(schs);
    end;  //if able to get svc handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_STOPPED = ss.dwCurrentState;
end;

How to convert a plain object into an ES6 Map?

Do I really have to first convert it into an array of arrays of key-value pairs?

No, an iterator of key-value pair arrays is enough. You can use the following to avoid creating the intermediate array:

function* entries(obj) {
    for (let key in obj)
        yield [key, obj[key]];
}

const map = new Map(entries({foo: 'bar'}));
map.get('foo'); // 'bar'