Programs & Examples On #Pathgeometry

PathGeometry is a class in the System.Windows.Media namespace. It represents a complex shape that may be composed of lines, arcs, points, polygons, etc. PathGeometry has several useful methods that can help in detecting overlap of shapes and overlapping areas. Also, it has methods for handling various operations necessary when working with odd shapes.

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

As mentioned in the comments, there cannot be a continuous scale on variable of the factor type. You could change the factor to numeric as follows, just after you define the meltDF variable.

meltDF$variable=as.numeric(levels(meltDF$variable))[meltDF$variable]

Then, execute the ggplot command

  ggplot(meltDF[meltDF$value == 1,]) + geom_point(aes(x = MW, y =   variable)) +
     scale_x_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200)) +
     scale_y_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200))

And you will have your chart.

Hope this helps

Reshape an array in NumPy

a = np.arange(18).reshape(9,2)
b = a.reshape(3,3,2).swapaxes(0,2)

# a: 
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [10, 11],
       [12, 13],
       [14, 15],
       [16, 17]])


# b:
array([[[ 0,  6, 12],
        [ 2,  8, 14],
        [ 4, 10, 16]],

       [[ 1,  7, 13],
        [ 3,  9, 15],
        [ 5, 11, 17]]])

How to Maximize window in chrome using webDriver (python)

Try

ChromeOptions options = new ChromeOptions();
options.addArguments("--start-fullscreen");

Blurring an image via CSS?

This code is working for blur effect for all browsers.

filter: blur(10px);
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

How to send a simple email from a Windows batch file?

If PowerShell is available, the Send-MailMessage commandlet is a single one-line command that could easily be called from a batch file to handle email notifications. Below is a sample of the line you would include in your batch file to call the PowerShell script (the %xVariable% is a variable you might want to pass from your batch file to the PowerShell script):

--[BATCH FILE]--

:: ...your code here...
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  -windowstyle hidden -command C:\MyScripts\EmailScript.ps1 %xVariable%

Below is an example of what you might include in your PowerShell script (you must include the PARAM line as the first non-remark line in your script if you included passing the %xVariable% from your batch file:

--[POWERSHELL SCRIPT]--

Param([String]$xVariable)
# ...your code here...
$smtp = "smtp.[emaildomain].com"
$to = "[Send to email address]"
$from = "[From email address]" 
$subject = "[Subject]" 
$body = "[Text you want to include----the <br> is a line feed: <br> <br>]"    
$body += "[This could be a second line of text]" + "<br> "

$attachment="[file name if you would like to include an attachment]"
send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Attachment $attachment -Priority high  

Getting fb.me URL

You can use bit.ly api to create facebook short urls find the documentation here http://api.bitly.com

Update a table using JOIN in SQL Server?

Seems like SQL Server 2012 can handle the old update syntax of Teradata too:

UPDATE a
SET a.CalculatedColumn= b.[Calculated Column]
FROM table1 a, table2 b 
WHERE 
    b.[common field]= a.commonfield
AND a.BatchNO = '110'

If I remember correctly, 2008R2 was giving error when I tried similar query.

Get Application Name/ Label via ADB Shell or Terminal

adb shell pm list packages will give you a list of all installed package names.

You can then use dumpsys | grep -A18 "Package \[my.package\]" to grab the package information such as version identifiers etc

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

The ThreadPoolExecutor class is the base implementation for the executors that are returned from many of the Executors factory methods. So let's approach Fixed and Cached thread pools from ThreadPoolExecutor's perspective.

ThreadPoolExecutor

The main constructor of this class looks like this:

public ThreadPoolExecutor(
                  int corePoolSize,
                  int maximumPoolSize,
                  long keepAliveTime,
                  TimeUnit unit,
                  BlockingQueue<Runnable> workQueue,
                  ThreadFactory threadFactory,
                  RejectedExecutionHandler handler
)

Core Pool Size

The corePoolSize determines the minimum size of the target thread pool. The implementation would maintain a pool of that size even if there are no tasks to execute.

Maximum Pool Size

The maximumPoolSize is the maximum number of threads that can be active at once.

After the thread pool grows and becomes bigger than the corePoolSize threshold, the executor can terminate idle threads and reach to the corePoolSize again. If allowCoreThreadTimeOut is true, then the executor can even terminate core pool threads if they were idle more than keepAliveTime threshold.

So the bottom line is if threads remain idle more than keepAliveTime threshold, they may get terminated since there is no demand for them.

Queuing

What happens when a new task comes in and all core threads are occupied? The new tasks will be queued inside that BlockingQueue<Runnable> instance. When a thread becomes free, one of those queued tasks can be processed.

There are different implementations of the BlockingQueue interface in Java, so we can implement different queuing approaches like:

  1. Bounded Queue: New tasks would be queued inside a bounded task queue.

  2. Unbounded Queue: New tasks would be queued inside an unbounded task queue. So this queue can grow as much as the heap size allows.

  3. Synchronous Handoff: We can also use the SynchronousQueue to queue the new tasks. In that case, when queuing a new task, another thread must already be waiting for that task.

Work Submission

Here's how the ThreadPoolExecutor executes a new task:

  1. If fewer than corePoolSize threads are running, tries to start a new thread with the given task as its first job.
  2. Otherwise, it tries to enqueue the new task using the BlockingQueue#offer method. The offer method won't block if the queue is full and immediately returns false.
  3. If it fails to queue the new task (i.e. offer returns false), then it tries to add a new thread to the thread pool with this task as its first job.
  4. If it fails to add the new thread, then the executor is either shut down or saturated. Either way, the new task would be rejected using the provided RejectedExecutionHandler.

The main difference between the fixed and cached thread pools boils down to these three factors:

  1. Core Pool Size
  2. Maximum Pool Size
  3. Queuing

+-----------+-----------+-------------------+---------------------------------+
| Pool Type | Core Size |    Maximum Size   |         Queuing Strategy        |
+-----------+-----------+-------------------+---------------------------------+
|   Fixed   | n (fixed) |     n (fixed)     | Unbounded `LinkedBlockingQueue` |
+-----------+-----------+-------------------+---------------------------------+
|   Cached  |     0     | Integer.MAX_VALUE |        `SynchronousQueue`       |
+-----------+-----------+-------------------+---------------------------------+


Fixed Thread Pool


Here's how the Excutors.newFixedThreadPool(n) works:

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

As you can see:

  • The thread pool size is fixed.
  • If there is high demand, it won't grow.
  • If threads are idle for quite some time, it won't shrink.
  • Suppose all those threads are occupied with some long-running tasks and the arrival rate is still pretty high. Since the executor is using an unbounded queue, it may consume a huge part of the heap. Being unfortunate enough, we may experience an OutOfMemoryError.

When should I use one or the other? Which strategy is better in terms of resource utilization?

A fixed-size thread pool seems to be a good candidate when we're going to limit the number of concurrent tasks for resource management purposes.

For example, if we're going to use an executor to handle web server requests, a fixed executor can handle the request bursts more reasonably.

For even better resource management, it's highly recommended to create a custom ThreadPoolExecutor with a bounded BlockingQueue<T> implementation coupled with reasonable RejectedExecutionHandler.


Cached Thread Pool


Here's how the Executors.newCachedThreadPool() works:

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

As you can see:

  • The thread pool can grow from zero threads to Integer.MAX_VALUE. Practically, the thread pool is unbounded.
  • If any thread is idle for more than 1 minute, it may get terminated. So the pool can shrink if threads remain too much idle.
  • If all allocated threads are occupied while a new task comes in, then it creates a new thread, as offering a new task to a SynchronousQueue always fails when there is no one on the other end to accept it!

When should I use one or the other? Which strategy is better in terms of resource utilization?

Use it when you have a lot of predictable short-running tasks.

Access parent DataContext from DataTemplate

the issue is that a DataTemplate isn't part of an element its applied to it.

this means if you bind to the template you're binding to something that has no context.

however if you put a element inside the template then when that element is applied to the parent it gains a context and the binding then works

so this will not work

<DataTemplate >
    <DataTemplate.Resources>
        <CollectionViewSource x:Key="projects" Source="{Binding Projects}" >

but this works perfectly

<DataTemplate >
    <GroupBox Header="Projects">
        <GroupBox.Resources>
            <CollectionViewSource x:Key="projects" Source="{Binding Projects}" >

because after the datatemplate is applied the groupbox is placed in the parent and will have access to its Context

so all you have to do is remove the style from the template and move it into an element in the template

note that the context for a itemscontrol is the item not the control ie ComboBoxItem for ComboBox not the ComboBox itself in which case you should use the controls ItemContainerStyle instead

Sending private messages to user

This is pretty simple here is an example

Add your command code here like:

if (cmd === `!dm`) {
 let dUser =
  message.guild.member(message.mentions.users.first()) ||
  message.guild.members.get(args[0]);
 if (!dUser) return message.channel.send("Can't find user!");
 if (!message.member.hasPermission('ADMINISTRATOR'))
  return message.reply("You can't you that command!");
 let dMessage = args.join(' ').slice(22);
 if (dMessage.length < 1) return message.reply('You must supply a message!');

 dUser.send(`${dUser} A moderator from WP Coding Club sent you: ${dMessage}`);

 message.author.send(
  `${message.author} You have sent your message to ${dUser}`
 );
}

How to make primary key as autoincrement for Room Persistence lib

You can add @PrimaryKey(autoGenerate = true) like this:

@Entity
data class Food(
        var foodName: String, 
        var foodDesc: String, 
        var protein: Double, 
        var carbs: Double, 
        var fat: Double
){
    @PrimaryKey(autoGenerate = true)
    var foodId: Int = 0 // or foodId: Int? = null
    var calories: Double = 0.toDouble()
}

How to install Java 8 on Mac

Below steps worked for me.

1) Uninstall all jdks

In the Terminal window Copy and Paste the command below:

sudo rm -fr /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin

sudo rm -fr /Library/PreferencePanes/JavaControlPanel.prefpane

2) Install APPLE jdk.

https://support.apple.com/kb/DL1572?locale=en_US

3) Download latest JDK from Oracle and install it , for me it was JDK 1.82

http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html

Thats all it will work like a charm.

Get the first item from an iterable that matches a condition

You could also use the argwhere function in Numpy. For example:

i) Find the first "l" in "helloworld":

import numpy as np
l = list("helloworld") # Create list
i = np.argwhere(np.array(l)=="l") # i = array([[2],[3],[8]])
index_of_first = i.min()

ii) Find first random number > 0.1

import numpy as np
r = np.random.rand(50) # Create random numbers
i = np.argwhere(r>0.1)
index_of_first = i.min()

iii) Find the last random number > 0.1

import numpy as np
r = np.random.rand(50) # Create random numbers
i = np.argwhere(r>0.1)
index_of_last = i.max()

The default for KeyValuePair

Try this:

if (getResult.Equals(new KeyValuePair<T,U>()))

or this:

if (getResult.Equals(default(KeyValuePair<T,U>)))

What is the difference between JDK and JRE?

suppose, if you are a developer then your role is to develop program as well as to execute the program. so you must have environment for developing and executing, which is provided by JDK.

suppose, if you are a client then you don't have to worry about developing.Just you need is, an environment to run program and get result only, which is provided by JRE.

JRE executes the application but JVM reads the instructions line by line so it's interpreter.

JDK=JRE+Development Tools

JRE=JVM+Library Classes

How do you roll back (reset) a Git repository to a particular commit?

For those with a git gui bent, you can also use gitk.

Right click on the commit you want to return to and select "Reset master branch to here". Then choose hard from the next menu.

HTML button calling an MVC Controller and Action method

Of all the suggestions, nobdy used the razor syntax (this is with bootstrap styles as well). This will make a button that redirects to the Login view in the Account controller:

    <form>
        <button class="btn btn-primary" asp-action="Login" asp- 
   controller="Account">@Localizer["Login"]</button>
    </form>

Correct location of openssl.cnf file

/usr/local/ssl/openssl.cnf

This is a local installation. You downloaded and built OpenSSL taking the default prefix, of you configured with ./config --prefix=/usr/local/ssl or ./config --openssldir=/usr/local/ssl.

You will use this if you use the OpenSSL in /usr/local/ssl/bin. That is, /usr/local/ssl/openssl.cnf will be used when you issue:

/usr/local/ssl/bin/openssl s_client -connect localhost:443 -tls1 -servername localhost

/usr/lib/ssl/openssl.cnf

This is where Ubuntu places openssl.cnf for the OpenSSL they provide.

You will use this if you use the OpenSSL in /usr/bin. That is, /usr/lib/ssl/openssl.cnf will be used when you issue:

openssl s_client -connect localhost:443 -tls1 -servername localhost

/etc/ssl/openssl.cnf

I don't know when this is used. The stuff in /etc/ssl is usually certificates and private keys, and it sometimes contains a copy of openssl.cnf. But I've never seen it used for anything.


Which is the main/correct one that I should use to make changes?

From the sounds of it, you should probably add the engine to /usr/lib/ssl/openssl.cnf. That ensures most "off the shelf" gear will use the new engine.

After you do that, add it to /usr/local/ssl/openssl.cnf also because copy/paste is easy.


Here's how to see which openssl.cnf directory is associated with a OpenSSL installation. The library and programs look for openssl.cnf in OPENSSLDIR. OPENSSLDIR is a configure option, and its set with --openssldir.

I'm on a MacBook with 3 different OpenSSL's (Apple's, MacPort's and the one I build):

# Apple    
$ /usr/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/System/Library/OpenSSL"

# MacPorts
$ /opt/local/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/opt/local/etc/openssl"

# My build of OpenSSL
$ openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/usr/local/ssl/darwin"

I have an Ubuntu system and I have installed openssl.

Just bike shedding, but be careful of Ubuntu's version of OpenSSL. It disables TLSv1.1 and TLSv1.2, so you will only have clients capable of older cipher suites; and you will not be able to use newer ciphers like AES/CTR (to replace RC4) and elliptic curve gear (like ECDHE_ECDSA_* and ECDHE_RSA_*). See Ubuntu 12.04 LTS: OpenSSL downlevel version is 1.0.0, and does not support TLS 1.2 in Launchpad.

EDIT: Ubuntu enabled TLS 1.1 and TLS 1.2 recently. See Comment 17 on the bug report.

Execute bash script from URL

This way is good and conventional:

17:04:59@itqx|~
qx>source <(curl -Ls http://192.168.80.154/cent74/just4Test) Lord Jesus Loves YOU
Remote script test...
Param size: 4

---------
17:19:31@node7|/var/www/html/cent74
arch>cat just4Test
echo Remote script test...
echo Param size: $#

What is a regular expression for a MAC Address?

Thanks a lot to @Moshe for the great answer above. After doing some more research I would like to add my extra findings, both in regards to IEEE 802 and enforcing consistent separator usage in regex.

The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits, separated by hyphens -. It is however, widely adopted convention to also allow colon :, and three groups of four hexadecimal digits separated by periods ..

Full credit to @Moshe here for his initial statement, and to @pilcrow for pointing out that IEEE 802 only covers hypens.

Here is a regex that enforces that same separator is used throughout the mac address:

^(?:(?:[0-9A-Fa-f]{2}(?=([-:]))(?:\1[0-9A-Fa-f]{2}){5}))$

Regex101 demo

And here is an additional one that allows for use of no separator at all:

^(?:(?:[0-9A-Fa-f]{2}(?=([-:]|))(?:\1[0-9A-Fa-f]{2}){5}))$

Regex101 demo

Using $_POST to get select option value from HTML

<select name="taskOption">
      <option value="first">First</option>
      <option value="second">Second</option>
      <option value="third">Third</option>
</select>

$var = $_POST['taskOption'];

Jquery: How to check if the element has certain css class/style

Or, if you need to access the element that has that property and it does not use an id, you could go this route:

$("img").each(function () {
        if ($(this).css("float") == "left") { $(this).addClass("left"); }
        if ($(this).css("float") == "right") { $(this).addClass("right"); }
    })

Test if string begins with a string?

The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.

The expensive regex method and the css attribute selector with starts with ^ operator

Option Explicit

Public Sub test()

    Debug.Print StartWithSubString("ab", "abc,d")

End Sub

Regex:

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft VBScript Regular Expressions
    Dim re As VBScript_RegExp_55.RegExp
    Set re = New VBScript_RegExp_55.RegExp

    re.Pattern = "^" & substring

    StartWithSubString = re.test(testString)

End Function

Css attribute selector with starts with operator

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft HTML Object Library
    Dim html As MSHTML.HTMLDocument
    Set html = New MSHTML.HTMLDocument

    html.body.innerHTML = "<div test=""" & testString & """></div>"

    StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0

End Function

Enumerations on PHP

What about class constants?

<?php

class YourClass
{
    const SOME_CONSTANT = 1;

    public function echoConstant()
    {
        echo self::SOME_CONSTANT;
    }
}

echo YourClass::SOME_CONSTANT;

$c = new YourClass;
$c->echoConstant();

html select only one checkbox in a group

Necromancing:
And without jQuery, for a checkbox structure like this:

<label>
<input type="checkbox" id="mytrackers_1" name="blubb_1" value="">--- Bitte ausw&#228;hlen ---
</label>
<label>
<input type="checkbox" id="mytrackers_2" name="blubb_2" value="7">Testtracker
</label>
<label>
<input type="checkbox" id="mytrackers_3" name="blubb_3" value="3">Kundenanfrage
</label>
<label>
<input type="checkbox" id="mytrackers_4" name="blubb_4" value="2">Anpassung
</label>
<label>
<input type="checkbox" id="mytrackers_5" name="blubb_5" value="1" checked="checked" >Fehler
</label>
<label>
<input type="checkbox" id="mytrackers_6" name="blubb_6" value="4">Bedienung
</label>
<label>
<input type="checkbox" id="mytrackers_7" name="blubb_7" value="5">Internes
</label>
<label>
<input type="checkbox" id="mytrackers_8" name="blubb_8" value="6">&#196;nderungswunsch
</label>

you would do it like this:

    /// attach an event handler, now or in the future, 
    /// for all elements which match childselector,
    /// within the child tree of the element maching parentSelector.
    function subscribeEvent(parentSelector, eventName, childSelector, eventCallback) {
        if (parentSelector == null)
            throw new ReferenceError("Parameter parentSelector is NULL");
        if (childSelector == null)
            throw new ReferenceError("Parameter childSelector is NULL");
        // nodeToObserve: the node that will be observed for mutations
        var nodeToObserve = parentSelector;
        if (typeof (parentSelector) === 'string')
            nodeToObserve = document.querySelector(parentSelector);
        var eligibleChildren = nodeToObserve.querySelectorAll(childSelector);
        for (var i = 0; i < eligibleChildren.length; ++i) {
            eligibleChildren[i].addEventListener(eventName, eventCallback, false);
        } // Next i 
        // https://stackoverflow.com/questions/2712136/how-do-i-make-this-loop-all-children-recursively
        function allDescendants(node) {
            if (node == null)
                return;
            for (var i = 0; i < node.childNodes.length; i++) {
                var child = node.childNodes[i];
                allDescendants(child);
            } // Next i 
            // IE 11 Polyfill 
            if (!Element.prototype.matches)
                Element.prototype.matches = Element.prototype.msMatchesSelector;
            if (node.matches) {
                if (node.matches(childSelector)) {
                    // console.log("match");
                    node.addEventListener(eventName, eventCallback, false);
                } // End if ((<Element>node).matches(childSelector))
                // else console.log("no match");
            } // End if ((<Element>node).matches) 
            // else console.log("no matchfunction");
        } // End Function allDescendants 
        // Callback function to execute when mutations are observed
        var callback = function (mutationsList, observer) {
            for (var _i = 0, mutationsList_1 = mutationsList; _i < mutationsList_1.length; _i++) {
                var mutation = mutationsList_1[_i];
                // console.log("mutation.type", mutation.type);
                // console.log("mutation", mutation);
                if (mutation.type == 'childList') {
                    for (var i = 0; i < mutation.addedNodes.length; ++i) {
                        var thisNode = mutation.addedNodes[i];
                        allDescendants(thisNode);
                    } // Next i 
                } // End if (mutation.type == 'childList') 
                // else if (mutation.type == 'attributes') { console.log('The ' + mutation.attributeName + ' attribute was modified.');
            } // Next mutation 
        }; // End Function callback 
        // Options for the observer (which mutations to observe)
        var config = { attributes: false, childList: true, subtree: true };
        // Create an observer instance linked to the callback function
        var observer = new MutationObserver(callback);
        // Start observing the target node for configured mutations
        observer.observe(nodeToObserve, config);
    } // End Function subscribeEvent 


    function radioCheckbox_onClick() 
    { 
        // console.log("click", this);
        let box = this;
        if (box.checked) 
        {
            let name = box.getAttribute("name");
            let pos = name.lastIndexOf("_");
            if (pos !== -1) name = name.substr(0, pos);

            let group = 'input[type="checkbox"][name^="' + name + '"]';
            // console.log(group);
            let eles = document.querySelectorAll(group);
            // console.log(eles);
            for (let j = 0; j < eles.length; ++j) 
            {
                eles[j].checked = false;
            }
            box.checked = true;
        }
        else
            box.checked = false;
    }


    // https://stackoverflow.com/questions/9709209/html-select-only-one-checkbox-in-a-group
    function radioCheckbox()
    { 
        // on instead of document...
        let elements = document.querySelectorAll('input[type="checkbox"]')

        for (let i = 0; i < elements.length; ++i)
        {
            // console.log(elements[i]);
            elements[i].addEventListener("click", radioCheckbox_onClick, false);

        } // Next i 

    } // End Function radioCheckbox 


    function onDomReady()
    {
        console.log("dom ready");
        subscribeEvent(document, "click", 
            'input[type="checkbox"]', 
            radioCheckbox_onClick
        ); 

        // radioCheckbox();
    }

    if (document.addEventListener) document.addEventListener("DOMContentLoaded", onDomReady, false);
    else if (document.attachEvent) document.attachEvent("onreadystatechange", onDomReady);
    else window.onload = onDomReady;

    function onPageLoaded() {
        console.log("page loaded");
    }

    if (window.addEventListener) window.addEventListener("load", onPageLoaded, false);
    else if (window.attachEvent) window.attachEvent("onload", onPageLoaded);
    else window.onload = onPageLoaded;

Is there a way to pass optional parameters to a function?

The Python 2 documentation, 7.6. Function definitions gives you a couple of ways to detect whether a caller supplied an optional parameter.

First, you can use special formal parameter syntax *. If the function definition has a formal parameter preceded by a single *, then Python populates that parameter with any positional parameters that aren't matched by preceding formal parameters (as a tuple). If the function definition has a formal parameter preceded by **, then Python populates that parameter with any keyword parameters that aren't matched by preceding formal parameters (as a dict). The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.

For instance, here's a function opt_fun which takes two positional parameters x1 and x2, and looks for another keyword parameter named "optional".

>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
...     if ('optional' in keyword_parameters):
...         print 'optional parameter found, it is ', keyword_parameters['optional']
...     else:
...         print 'no optional parameter, sorry'
... 
>>> opt_fun(1, 2)
no optional parameter, sorry
>>> opt_fun(1,2, optional="yes")
optional parameter found, it is  yes
>>> opt_fun(1,2, another="yes")
no optional parameter, sorry

Second, you can supply a default parameter value of some value like None which a caller would never use. If the parameter has this default value, you know the caller did not specify the parameter. If the parameter has a non-default value, you know it came from the caller.

Qt. get part of QString

Use the left function:

QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "

Also have a look at mid() if you want more control.

Date difference in years using C#

Maybe this will be helpful for answering the question: Count of days in given year,

new DateTime(anyDate.Year, 12, 31).DayOfYear //will include leap years too

Regarding DateTime.DayOfYear Property.

Error message "No exports were found that match the constraint contract name"

My 2 cents: Following all above lifesaving tips, I had a slightly different experience; mine is VS 2017 Community Edition, installed once, and I notice that have all these 3 folders:

%LocalAppData%\Microsoft\VisualStudio\15.0 ==> Empty
%LocalAppData%\Microsoft\VisualStudio\7f0c75b0 ==> has only the CoreCon folder

This is the one that has the ComponentModelCache:

%LocalAppData%\Microsoft\VisualStudio\15.0_7f0c75b0

Deleting only the Microsoft.VisualStudio.Default.cache had no effect.

So, I deleted all 4 files there: .cache, .err, .external and catalogs. On restarting VS, problem gone and appeared a 5th file:

Microsoft.VisualStudio.Default.scan

Can't connect to Postgresql on port 5432

Had same problem with psql via command line connecting and pgAdmin not connecting on RDS with AWS. I did have my RDS set to Publicly Accessible. I made sure my ACL and security groups were wide open and still problem so, I did the following: sudo find . -name *.conf then sudo nano ./data/pg_hba.conf then added to top of directives in pg_hba.conf file host all all 0.0.0.0/0 md5 and pgAdmin automatically logged me in.

This also worked in pg_hba.conf file host all all md5 without any IP address and this also worked with my IP address host all all <myip>/32 md5

As a side note, my RDS was in my default VPC. I had an identical RDS instance in my non-default VPC with identical security group, ACL and security group settings to my default VPC and I could not get it to work. Not sure why but, that's for another day.

How to create EditText with rounded corners?

Just to add to the other answers, I found that the simplest solution to achieve the rounded corners was to set the following as a background to your Edittext.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@android:color/white"/>
    <corners android:radius="8dp"/>

</shape>

What is Cache-Control: private?

RFC 2616, section 14.9.1:

Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache...A private (non-shared) cache MAY cache the response.


Browsers could use this information. Of course, the current "user" may mean many things: OS user, a browser user (e.g. Chrome's profiles), etc. It's not specified.

For me, a more concrete example of Cache-Control: private is that proxy servers (which typically have many users) won't cache it. It is meant for the end user, and no one else.


FYI, the RFC makes clear that this does not provide security. It is about showing the correct content, not securing content.

This usage of the word private only controls where the response may be cached, and cannot ensure the privacy of the message content.

Import CSV into SQL Server (including automatic table creation)

You can create a temp table variable and insert the data into it, then insert the data into your actual table by selecting it from the temp table.

 declare @TableVar table 
 (
    firstCol varchar(50) NOT NULL,
    secondCol varchar(50) NOT NULL
 )

BULK INSERT @TableVar FROM 'PathToCSVFile' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
GO

INSERT INTO dbo.ExistingTable
(
    firstCol,
    secondCol
)
SELECT firstCol,
       secondCol
FROM @TableVar

GO

How to draw a dotted line with css?

Do you mean something like 'border: 1px dotted black'?

w3schools.com reference

How can I run MongoDB as a Windows service?

I'm on version 2.4.9 and using a config file. The service wouldn't start until I surrounded the equals sign in the config file with spaces:

dbpath = D:\Mongo data
logpath = C:\mongodb\logs\mongo.log 
logappend = true

Originally I had:

logpath=C:\mongodb\logs\mongo.log 

I also discovered that when installing the service that you have to use an absolute path for the config file eg:

c:\mongodb\bin\>mongodb.exe C:\mongodb\bin\mongod.conf --install

Don't be tempted to put inverted commas around a dbpath with spaces. The service will appear to start when you execute net start MongoDB but it will terminate. Check the log files for confirmation that the service has really started.

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

Convert all strings in a list to int

Here is a simple solution with explanation for your query.

 a=['1','2','3','4','5'] #The integer represented as a string in this list
 b=[] #Fresh list
 for i in a: #Declaring variable (i) as an item in the list (a).
     b.append(int(i)) #Look below for explanation
 print(b)

Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).

Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.

Output console:

[1, 2, 3, 4, 5]

So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.

SSRS Field Expression to change the background color of the Cell

You can use SWITCH() function to evaluate multiple criteria to color the cell. The node <BackgroundColor> is the cell fill, <Color> is font color.

Expression:

=SWITCH(
    (
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND (Fields!User_Name.Value.Contains("TOTAL"))
    ), "Black"
    ,(
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND NOT(Fields!User_Name.Value.Contains("TOTAL"))
    ), "#595959"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND Fields!OLAP_Cube.Value.Contains("TOTAL") 
    ), "#c65911"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND NOT(Fields!OLAP_Cube.Value.Contains("TOTAL")) 
    ), "#ed7d31"
    ,true, "#e7e6e6"
    )

'Daily Totals... CellFill.&[Dark Orange]-[#c65911], TextBold.&[True]'Daily Totals... CellFill.&[Dark Orange]-[#c65911], TextBold.&[True]
'Daily Cube Totals... CellFill.&[Medium Orange]-[#eb6e19]
'Daily User List... CellFill.&[Light Grey]-[#e7e6e6]
'Date Totals All Users Total... CellFill.&[Black]-["black"], TextColor.&[Light Orange]-[#ed7d31]
'Date Totals Per User... CellFill.&[Dark Grey]-[#595959], TextColor.&[Yellow]-["yellow"]
'(ALL OTHER CONDITIONS)
'Daily User List... CellFill.&[Light Grey]-[#e7e6e6]

XML node in report definition file (SSRS-2016 / VS-2015):

                <TablixRow>
                  <Height>0.2in</Height>
                  <TablixCells>
                    <TablixCell>
                      <CellContents>
                        <Textbox Name="Usage_Date1">
                          <CanGrow>true</CanGrow>
                          <KeepTogether>true</KeepTogether>
                          <Paragraphs>
                            <Paragraph>
                              <TextRuns>
                                <TextRun>
                                  <Value>=Fields!Usage_Date.Value</Value>
                                  <Style>
                                    <FontSize>8pt</FontSize>
                                    <FontWeight>=SWITCH(
    (
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND Fields!OLAP_Cube.Value.Contains("TOTAL") 
    ), "Bold"
    ,true, "Normal"
    )</FontWeight>
                                    <Color>=SWITCH(
    (
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND (Fields!User_Name.Value.Contains("TOTAL"))
    ), "#ed7d31"
    ,(
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND NOT(Fields!User_Name.Value.Contains("TOTAL"))
    ), "Yellow"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND Fields!OLAP_Cube.Value.Contains("TOTAL") 
    ), "Black"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND NOT(Fields!OLAP_Cube.Value.Contains("TOTAL")) 
    ), "Black"
    ,true, "Black"
    )

'Daily Totals... CellFill.&amp;[Dark Orange]-[#c65911], TextBold.&amp;[True]'Daily Totals... CellFill.&amp;[Dark Orange]-[#c65911], TextBold.&amp;[True]
'Daily Cube Totals... CellFill.&amp;[Medium Orange]-[#eb6e19]
'Daily User List... CellFill.&amp;[Light Grey]-[#e7e6e6]
'Date Totals All Users Total... CellFill.&amp;[Black]-["black"], TextColor.&amp;[Light Orange]-[#ed7d31]
'Date Totals Per User... CellFill.&amp;[Dark Grey]-[#595959], TextColor.&amp;[Yellow]-["yellow"]
'(ALL OTHER CONDITIONS)
'Daily User List... CellFill.&amp;[Light Grey]-[#e7e6e6]</Color>
                                  </Style>
                                </TextRun>
                              </TextRuns>
                              <Style />
                            </Paragraph>
                          </Paragraphs>
                          <rd:DefaultName>Usage_Date1</rd:DefaultName>
                          <Style>
                            <Border>
                              <Color>LightGrey</Color>
                              <Style>Solid</Style>
                            </Border>
                            <BackgroundColor>=SWITCH(
    (
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND (Fields!User_Name.Value.Contains("TOTAL"))
    ), "Black"
    ,(
        Fields!Usage_Date.Value.Contains("TOTAL") 
        AND NOT(Fields!User_Name.Value.Contains("TOTAL"))
    ), "#595959"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND Fields!OLAP_Cube.Value.Contains("TOTAL") 
    ), "#c65911"
    ,(
        NOT(Fields!Usage_Date.Value.Contains("TOTAL")) 
        AND Fields!User_Name.Value.Contains("TOTAL") 
        AND NOT(Fields!OLAP_Cube.Value.Contains("TOTAL")) 
    ), "#ed7d31"
    ,true, "#e7e6e6"
    )

'Daily Totals... CellFill.&amp;[Dark Orange]-[#c65911], TextBold.&amp;[True]'Daily Totals... CellFill.&amp;[Dark Orange]-[#c65911], TextBold.&amp;[True]
'Daily Cube Totals... CellFill.&amp;[Medium Orange]-[#eb6e19]
'Daily User List... CellFill.&amp;[Light Grey]-[#e7e6e6]
'Date Totals All Users Total... CellFill.&amp;[Black]-["black"], TextColor.&amp;[Light Orange]-[#ed7d31]
'Date Totals Per User... CellFill.&amp;[Dark Grey]-[#595959], TextColor.&amp;[Yellow]-["yellow"]
'(ALL OTHER CONDITIONS)
'Daily User List... CellFill.&amp;[Light Grey]-[#e7e6e6]</BackgroundColor>
                            <PaddingLeft>2pt</PaddingLeft>
                            <PaddingRight>2pt</PaddingRight>
                          </Style>
                        </Textbox>
                        <rd:Selected>true</rd:Selected>
                      </CellContents>
                    </TablixCell>

HTTP Status 504

Suppose access a proxy server A(eg. nginx), and the server A forwards the request to another server B(eg. tomcat).

If this process continues for a long time (more than the proxy server read timeout setting), A still did not get a completed response of B. It happens.

for nginx, You can configure the proxy_read_timeout(in location) property to solve his.But this is usually not a good idea, if you set the value too high. This may hide the real error.You'd better improve the design to really solve this problem.

Intent.putExtra List

If you use ArrayList instead of list then also your problem wil be solved. In your code only modify List into ArrayList.

private List<Item> data;

Isn't the size of character in Java 2 bytes?

Java allocates 2 of 2 bytes for character as it follows UTF-16. It occupies minimum 2 bytes while storing a character, and maximum of 4 bytes. There is no 1 byte or 3 bytes of storage for character.

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

SELECT employee_number, course_code, MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

What is the difference between JVM, JDK, JRE & OpenJDK?

JRE executes the application but JVM reads the instructions line by line so it's interpreter.

JDK=JRE+Development Tools

JRE=JVM+Library Classes

How do I find the maximum of 2 numbers?

max(value,run)

should do it.

C++ Erase vector element by value rather than by position?

You can not do that directly. You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVec.end());. See this erasing elements from vector for more details.

CSS Input field text color of inputted text

replace:

input, select, textarea{
    color: #000;
}

with:

input, select, textarea{
    color: #f00;
}

or color: #ff0000;

Refused to apply inline style because it violates the following Content Security Policy directive

As the error message says, you have an inline style, which CSP prohibits. I see at least one (list-style: none) in your HTML. Put that style in your CSS file instead.

To explain further, Content Security Policy does not allow inline CSS because it could be dangerous. From An Introduction to Content Security Policy:

"If an attacker can inject a script tag that directly contains some malicious payload .. the browser has no mechanism by which to distinguish it from a legitimate inline script tag. CSP solves this problem by banning inline script entirely: it’s the only way to be sure."

Vertically centering a div inside another div

Vertically centering a div inside another div

_x000D_
_x000D_
#outerDiv{_x000D_
  width: 500px;_x000D_
  height: 500px;_x000D_
  position:relative;_x000D_
  _x000D_
  background-color: lightgrey;  _x000D_
}_x000D_
_x000D_
#innerDiv{_x000D_
  width: 284px;_x000D_
  height: 290px;_x000D_
  _x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  -ms-transform: translate(-50%, -50%); /* IE 9 */_x000D_
  -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ _x000D_
  _x000D_
  background-color: grey;_x000D_
}
_x000D_
<div id="outerDiv">_x000D_
  <div id="innerDiv"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

See the "Threading" section of this page: http://msdn.microsoft.com/en-us/library/ff647786.aspx, in conjunction with the "Connections" section.

Have you tried upping the maxconnection attribute of your processModel setting?

How to get first element in a list of tuples?

Those are tuples, not sets. You can do this:

l1 = [(1, u'abc'), (2, u'def')]
l2 = [(tup[0],) for tup in l1]
l2
>>> [(1,), (2,)]

How to stop default link click behavior with jQuery

$('.update-cart').click(function(e) {
    updateCartWidget();
    e.stopPropagation();
    e.preventDefault();
});

$('.update-cart').click(function() {
    updateCartWidget();
    return false;
});

The following methods achieve the exact same thing.

How to read GET data from a URL using JavaScript?

You can easily do this

const shopId =  new URLSearchParams(window.location.search).get('shop_id');
console.log(shopId);

PHP - Extracting a property from an array of objects

The solution depends on the PHP version you are using. At least there are 2 solutions:

First (Newer PHP versions)

As @JosepAlsina said before the best and also shortest solution is to use array_column as following:

$catIds = array_column($objects, 'id');

Notice: For iterating an array containing \stdClasses as used in the question it is only possible with PHP versions >= 7.0. But when using an array containing arrays you can do the same since PHP >= 5.5.

Second (Older PHP versions)

@Greg said in older PHP versions it is possible to do following:

$catIds = array_map(create_function('$o', 'return $o->id;'), $objects);

But beware: In newer PHP versions >= 5.3.0 it is better to use Closures, like followed:

$catIds = array_map(function($o) { return $o->id; }, $objects);


The difference

First solution creates a new function and puts it into your RAM. The garbage collector does not delete the already created and already called function instance out of memory for some reason. And that regardless of the fact, that the created function instance can never be called again, because we have no pointer for it. And the next time when this code is called, the same function will be created again. This behavior slowly fills your memory...

Both examples with memory output to compare them:

BAD

while (true)
{
    $objects = array_map(create_function('$o', 'return $o->id;'), $objects);

    echo memory_get_usage() . "\n";

    sleep(1);
}

// the output
4235616
4236600
4237560
4238520
...

GOOD

while (true)
{
    $objects = array_map(function($o) { return $o->id; }, $objects);

    echo memory_get_usage() . "\n";

    sleep(1);
}

// the output
4235136
4235168
4235168
4235168
...


This may also be discussed here

Memory leak?! Is Garbage Collector doing right when using 'create_function' within 'array_map'?

Child with max-height: 100% overflows parent

Here is a solution for a recently opened question marked as a duplicate of this question. The <img> tag was exceeding the max-height of the parent <div>.

Broken: Fiddle

Working: Fiddle

In this case, adding display:flex to the 2 parent <div> tags was the answer

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

How to write super-fast file-streaming code in C#?

The fastest way to do file I/O from C# is to use the Windows ReadFile and WriteFile functions. I have written a C# class that encapsulates this capability as well as a benchmarking program that looks at differnet I/O methods, including BinaryReader and BinaryWriter. See my blog post at:

http://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

How to Load Ajax in Wordpress

I thought that since the js file was already loaded, that I didn't need to load/enqueue it again in the separate add_ajax function.
But this must be necessary, or I did this and it's now working.

Hopefully will help someone else.

Here is the corrected code from the question:

// code to load jquery - working fine

// code to load javascript file - working fine

// ENABLE AJAX :
function add_ajax()
{
    wp_enqueue_script(
       'function',
       'http://host/blog/wp-content/themes/theme/js.js',
       array( 'jquery' ),
       '1.0',
       1
   );

   wp_localize_script(
      'function',
      'ajax_script',
      array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

$dirName = get_stylesheet_directory();  // use this to get child theme dir
require_once ($dirName."/ajax.php");  

add_action("wp_ajax_nopriv_function1", "function1"); // function in ajax.php

add_action('template_redirect', 'add_ajax');  

Div with horizontal scrolling only

The solution is fairly straight forward. To ensure that we don't impact the width of the cells in the table, we'll turn off white-space. To ensure we get a horizontal scroll bar, we'll turn on overflow-x. And that's pretty much it:

.container {
    width: 30em;
    overflow-x: auto;
    white-space: nowrap;
}

You can see the end-result here, or in the animation below. If the table determines the height of your container, you should not need to explicitly set overflow-y to hidden. But understand that is also an option.

enter image description here

How to check if a table exists in a given schema

For PostgreSQL 9.3 or less...Or who likes all normalized to text

Three flavors of my old SwissKnife library: relname_exists(anyThing), relname_normalized(anyThing) and relnamechecked_to_array(anyThing). All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).

/**
 * From my old SwissKnife Lib to your SwissKnife. License CC0.
 * Check and normalize to array the free-parameter relation-name.
 * Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
 */
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
     SELECT array[n.nspname::text, c.relname::text]
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
              WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1]      AND c.relname = x[2]
              WHEN $2 IS NULL THEN           n.nspname = 'public'  AND c.relname = $1
              ELSE                           n.nspname = $2        AND c.relname = $1
            END
$f$ language SQL IMMUTABLE;

CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
  SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;

CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
  SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;

Remove trailing newline from the elements of a string list

You can use lists comprehensions:

strip_list = [item.strip() for item in lines]

Or the map function:

# with a lambda
strip_list = map(lambda it: it.strip(), lines)

# without a lambda
strip_list = map(str.strip, lines)

How to get the browser to navigate to URL in JavaScript

Try these:

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

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

How can I regenerate ios folder in React Native project?

  1. Open Terminal/cmd
  2. Move to the folder/directory where the project "ProjectName" folder exist(Do not go into project directory)
  3. run command as: react-native init "ProjectName" and it will warn that project directory already exist but you continue.
  4. It will install all updated node modules as well as missing platform (android/ios) folders inside project without disturbing the code already written.
  5. cd "ProjectName" and then cd ios and then run pod install

PS: Take backup of your code in case it changes App.js

How to get status code from webclient?

You can try this code to get HTTP status code from WebException or from OpenReadCompletedEventArgs.Error. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

HttpStatusCode GetHttpStatusCode(System.Exception err)
{
    if (err is WebException)
    {
        WebException we = (WebException)err;
        if (we.Response is HttpWebResponse)
        {
            HttpWebResponse response = (HttpWebResponse)we.Response;
            return response.StatusCode;
        }
    }
    return 0;
}

How can I scroll a div to be visible in ReactJS?

I'm just adding another bit of info for others searching for a Scroll-To capability in React. I had tied several libraries for doing Scroll-To for my app, and none worked from my use case until I found react-scrollchor, so I thought I'd pass it on. https://github.com/bySabi/react-scrollchor

How to hide/show div tags using JavaScript?

try yo write document.getElementById('id').style.visibility="hidden";

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

I know this is old, this is what came up in my Google search. I needed to reference these packages on NuGet:

enter image description here

How do you get an iPhone's device name

In Unity, using C#:

SystemInfo.deviceName;

How to add two edit text fields in an alert dialog

I found another set of examples for customizing an AlertDialog from a guy named Mossila. I think they're better than Google's examples. To quickly see Google's API demos, you must import their demo jar(s) into your project, which you probably don't want.

But Mossila's example code is fully self-contained. It can be directly cut-and-pasted into your project. It just works! Then you only need to tweak it to your needs. See here

Difference between natural join and inner join

Natural Join: It is combination or combined result of all the columns in the two tables. It will return all rows of the first table with respect to the second table.

Inner Join: This join will work unless if any of the column name shall be sxame in two tables

How to know function return type and argument types?

I attended a coursera course, there was lesson in which, we were taught about design recipe.

Below docstring format I found preety useful.

def area(base, height):
    '''(number, number ) -> number    #**TypeContract**
    Return the area of a tring with dimensions base   #**Description**
    and height

    >>>area(10,5)          #**Example **
    25.0
    >>area(2.5,3)
    3.75
    '''
    return (base * height) /2 

I think if docstrings are written in this way, it might help a lot to developers.

Link to video [Do watch the video] : https://www.youtube.com/watch?v=QAPg6Vb_LgI

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

Here is an extension function for C#:

public static BitmapImage GetElementImage(this IWebDriver webDriver, By by)
{
    var elements = webDriver.FindElements(by);
    if (elements.Count == 0)
        return null;

    var element = elements[0];
    var screenShot = (webDriver as ITakesScreenshot).GetScreenshot();
    using (var ms = new MemoryStream(screenShot.AsByteArray))
    {
        Bitmap screenBitmap;
        screenBitmap = new Bitmap(ms);
        return screenBitmap.Clone(
            new Rectangle(
                element.Location.X,
                element.Location.Y,
                element.Size.Width,
                element.Size.Height
            ),
            screenBitmap.PixelFormat
        ).ToBitmapImage();
    }
}

Now you can use it to take the image of any element like this:

var image = webDriver.GetElementImage(By.Id("someId"));

What is the proper way to URL encode Unicode characters?

IRI (RFC 3987) is the latest standard that replaces the URI/URL (RFC 3986 and older) standards. URI/URL do not natively support Unicode (well, RFC 3986 adds provisions for future URI/URL-based protocols to support it, but does not update past RFCs). The "%uXXXX" scheme is a non-standard extension to allow Unicode in some situations, but is not universally implemented by everyone. IRI, on the other hand, fully supports Unicode, and requires that text be encoded as UTF-8 before then being percent-encoded.

Submit form without page reloading

this is exactly how it CAN work without jQuery and AJAX and it's working very well using a simple iFrame. I LOVE IT, works in Opera10, FF3 and IE6. Thanks to some of the above posters pointing me the right direction, that's the only reason I am posting here:

<select name="aAddToPage[65654]" 
onchange="
    if (bCanAddMore) {
        addToPage(65654,this);
    }
    else {
        alert('Could not add another, wait until previous is added.'); 
        this.options[0].selected = true;
    };
" />
<option value="">Add to page..</option>
[more options with values here]</select>

<script type="text/javascript">
function addToPage(iProduct, oSelect){
    iPage = oSelect.options[oSelect.selectedIndex].value;
    if (iPage != "") {
        bCanAddMore = false;
        window.hiddenFrame.document.formFrame.iProduct.value = iProduct;
        window.hiddenFrame.document.formFrame.iAddToPage.value = iPage;
        window.hiddenFrame.document.formFrame.submit();
    }
}
var bCanAddMore = true;</script> 

<iframe name="hiddenFrame" style="display:none;" src="frame.php?p=addProductToPage" onload="bCanAddMore = true;"></iframe>

the php code generating the page that is being called above:

if( $_GET['p'] == 'addProductToPage' ){  // hidden form processing
  if(!empty($_POST['iAddToPage'])) {
    //.. do something with it.. 
  }
  print('
    <html>
        <body>
            <form name="formFrame" id="formFrameId" style="display:none;" method="POST" action="frame.php?p=addProductToPage" >
                <input type="hidden" name="iProduct" value="" />
                <input type="hidden" name="iAddToPage" value="" />
            </form>
        </body>
    </html>
  ');
}

Syntax for if/else condition in SCSS mixin

You could default the parameter to null or false.
This way, it would be shorter to test if a value has been passed as parameter.

@mixin clearfix($width: null) {

  @if not ($width) {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

Inserting Image Into BLOB Oracle 10g

You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.

If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:

enter image description here

SQL Developer has a similar feature. See the "Load" link below:

enter image description here

If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.

Assuming ACL is complete, you'd pull the image like this:

declare
    l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
    l_http_request   UTL_HTTP.req;
    l_http_response  UTL_HTTP.resp;
    l_raw RAW(2000);
    l_blob BLOB;
begin
   -- Important: setup ACL access list first!

    DBMS_LOB.createtemporary(l_blob, FALSE);

    l_http_request  := UTL_HTTP.begin_request(l_url);
    l_http_response := UTL_HTTP.get_response(l_http_request);

  -- Copy the response into the BLOB.
  BEGIN
    LOOP
      UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
      DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
    END LOOP;
  EXCEPTION
    WHEN UTL_HTTP.end_of_body THEN
      UTL_HTTP.end_response(l_http_response);
  END;

  insert into my_pics (pic_id, pic) values (102, l_blob);
  commit;

  DBMS_LOB.freetemporary(l_blob); 
end;

Hope that helps.

JavaScript - cannot set property of undefined

In javascript almost everything is an object, null and undefined are exception.

Instances of Array is an object. so you can set property of an array, for the same reason,you can't set property of a undefined, because its NOT an object

How to negate 'isblank' function

The solution is isblank(cell)=false

Get IPv4 addresses from Dns.GetHostEntry()

    public Form1()
    {
        InitializeComponent();

        string myHost = System.Net.Dns.GetHostName();
        string myIP = null;

        for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
        {
            if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
            {
                myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
            }
        }
    }

Declare myIP and myHost in public Variable and use in any function of the form.

JavaFX and OpenJDK

Try obuildfactory.

There is need to modify these scripts (contains error and don't exactly do the "thing" required), i will upload mine scripts forked from obuildfactory in next few days. and so i will also update my answer accordingly.

Until then enjoy, sir :)

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

I used this approach to perform the same operation in my app.

var varDate = $("#dateStart").val(); 

var DateinISO = $.datepicker.parseDate('mm/dd/yy', varDate); 

var DateNewFormat = $.datepicker.formatDate( "yy-mm-dd", new Date( DateinISO ) );

$("#dateStartNewFormat").val(DateNewFormat);

Removing html5 required attribute with jQuery

If you want to set required to true

$(document).ready(function(){
$('#edit-submitted-first-name').prop('required',true);
});

if you want to set required to false

$(document).ready(function(){
$('#edit-submitted-first-name').prop('required',false);
});

Changing MongoDB data store directory

The short answer is that the --dbpath parameter in MongoDB will allow you to control what directory MongoDB reads and writes it's data from.

mongod --dbpath /usr/local/mongodb-data

Would start mongodb and put the files in /usr/local/mongodb-data.

Depending on your distribution and MongoDB installation, you can also configure the mongod.conf file to do this automatically:

# Store data in /usr/local/var/mongodb instead of the default /data/db
dbpath = /usr/local/var/mongodb

The official 10gen Linux packages (Ubuntu/Debian or CentOS/Fedora) ship with a basic configuration file which is placed in /etc/mongodb.conf, and the MongoDB service reads this when it starts up. You could make your change here.

Simulate Keypress With jQuery

I believe this is what you're looking for:

var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 40;
$("whatever").trigger(press);

From here.

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Here is a way to do it without adding an ID to the form elements.

<form method="post">
    ...
    <select name="List">
        <option value="1">Test1</option>
        <option value="2">Test2</option>
    </select>
    <select name="List">
        <option value="3">Test3</option>
        <option value="4">Test4</option>
    </select>
    ...
</form>

public ActionResult OrderProcessor()
{
    string[] ids = Request.Form.GetValues("List");
}

Then ids will contain all the selected option values from the select lists. Also, you could go down the Model Binder route like so:

public class OrderModel
{
    public string[] List { get; set; }
}

public ActionResult OrderProcessor(OrderModel model)
{
    string[] ids = model.List;
}

Hope this helps.

How is malloc() implemented internally?

It's also important to realize that simply moving the program break pointer around with brk and sbrk doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.

How to programmatically take a screenshot on Android?

For system applications only!

Process process;
process = Runtime.getRuntime().exec("screencap -p " + outputPath);
process.waitFor();

Note: System applications don't need to run "su" to execute this command.

jQuery Clone table row

Try this code, I used the following code for cloning and removing the cloned element, i have also used new class (newClass) which can be added automatically with the newly cloned html

for cloning..

 $(".tr_clone_add").live('click', function() {
    var $tr    = $(this).closest('.tr_clone');
    var newClass='newClass';
    var $clone = $tr.clone().addClass(newClass);
    $clone.find(':text').val('');
    $tr.after($clone);
});

for removing the clone element.

$(".tr_clone_remove").live('click', function() { //Once remove button is clicked
    $(".newClass:last").remove(); //Remove field html
    x--; //Decrement field counter
});

html is as followinng

<tr class="tr_clone">
                       <!-- <td>1</td>-->
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span10" readonly>
                        <span><a href="javascript:void(0);" class="tr_clone_add" title="Add field"><span><i class="icon-plus-sign"></i></span></a> <a href="javascript:void(0);" class="tr_clone_remove" title="Remove field"><span style="color: #D63939;"><i class="icon-remove-sign"></i></span></a> </span> </td> </tr>

SQL MAX of multiple columns?

Another way to use CASE WHEN

SELECT CASE true 
       WHEN max(row1) >= max(row2) THEN CASE true WHEN max(row1) >= max(row3) THEN max(row1) ELSE max(row3) end ELSE
       CASE true WHEN max(row2) >= max(row3) THEN max(row2) ELSE max(row3) END END
FROM yourTable

How does OkHttp get Json string?

As I observed in my code. If once the value is fetched of body from Response, its become blank.

String str = response.body().string();  // {response:[]}

String str1  = response.body().string();  // BLANK

So I believe after fetching once the value from body, it become empty.

Suggestion : Store it in String, that can be used many time.

How to get substring from string in c#?

You could do this manually or using IndexOf method.

Manually:

int index = 43;
string piece = myString.Substring(index);

Using IndexOf you can see where the fullstop is:

int index = myString.IndexOf(".") + 1;
string piece = myString.Substring(index);

Add a row number to result set of a SQL query

The typical pattern would be as follows, but you need to actually define how the ordering should be applied (since a table is, by definition, an unordered bag of rows):

SELECT t.A, t.B, t.C, number = ROW_NUMBER() OVER (ORDER BY t.A)
  FROM dbo.tableZ AS t
  ORDER BY t.A;

Not sure what the variables in your question are supposed to represent (they don't match).

How can I force a long string without any blank to be wrapped?

<textarea style="width:100px; word-wrap:break-word;">
  place your text here
</textarea>

Recursively list files in Java

The accepted answer is great, however it breaks down when you want to do IO inside the lambda.

Here is what you can do if your action declares IOExceptions.

You can treat the filtered stream as an Iterable, and then do your action in a regular for-each loop. This way, you don't have to handle exceptions inside a lambda.

try (Stream<Path> pathStream = Files.walk(Paths.get(path))
        .filter(Files::isRegularFile)) {

    for (Path file : (Iterable<Path>) pathStream::iterator) {
        // something that throws IOException
        Files.copy(file, System.out);
    }
}

Found that trick here: https://stackoverflow.com/a/32668807/1207791

Adding placeholder text to textbox

there are BETTER solutions, but the easiest solution is here: set the textbox text to your desired string then create a function that deletes the text, have that function fire on textbox Focus Enter event

Erase the current printed console line

Just found this old thread, looking for some kind of escape sequence to blank the actual line.

It's quite funny no one came to the idea (or I have missed it) that printf returns the number of characters written. So just print '\r' + as many blank characters as printf returned and you will exactly blank the previuosly written text.

int BlankBytes(int Bytes)
{
                char strBlankStr[16];

                sprintf(strBlankStr, "\r%%%is\r", Bytes);
                printf(strBlankStr,"");

                return 0;
}

int main(void)
{
                int iBytesWritten;
                double lfSomeDouble = 150.0;

                iBytesWritten = printf("test text %lf", lfSomeDouble);

                BlankBytes(iBytesWritten);

                return 0;
}

As I cant use VT100, it seems I have to stick with that solution

Nested jQuery.each() - continue/break

return true not work

return false working

found = false;
query = "foo";

$('.items').each(function()
{
  if($(this).text() == query)
  {
    found = true;
    return false;
  }
});

How to import image (.svg, .png ) in a React Component

Solved the problem, when moved the folder with the image in src folder. Then I turned to the image (project created through "create-react-app")
let image = document.createElement("img"); image.src = require('../assets/police.png');

What is the cleanest way to ssh and run multiple commands in Bash?

Not sure if the cleanest for long commands but certainly the easiest:

ssh user@host "cmd1; cmd2; cmd3"

Limiting the number of characters in a JTextField

public void Letters(JTextField a) {
    a.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(java.awt.event.KeyEvent e) {
            char c = e.getKeyChar();
            if (Character.isDigit(c)) {
                e.consume();
            }
            if (Character.isLetter(c)) {
                e.setKeyChar(Character.toUpperCase(c));
            }
        }
    });
}

public void Numbers(JTextField a) {
    a.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(java.awt.event.KeyEvent e) {
            char c = e.getKeyChar();
            if (!Character.isDigit(c)) {
                e.consume();
            }
        }
    });
}

public void Caracters(final JTextField a, final int lim) {
    a.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(java.awt.event.KeyEvent ke) {
            if (a.getText().length() == lim) {
                ke.consume();
            }
        }
    });
}

Getting DOM node from React child element

I found an easy way using the new callback refs. You can just pass a callback as a prop to the child component. Like this:

class Container extends React.Component {
  constructor(props) {
    super(props)
    this.setRef = this.setRef.bind(this)
  }

  setRef(node) {
    this.childRef = node
  }

  render() {
    return <Child setRef={ this.setRef }/>
  }
}

const Child = ({ setRef }) => (
    <div ref={ setRef }>
    </div>
)

Here's an example of doing this with a modal:

class Container extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      modalOpen: false
    }
    this.open = this.open.bind(this)
    this.close = this.close.bind(this)
    this.setModal = this.setModal.bind(this)
  }

  open() {
    this.setState({ open: true })
  }

  close(event) {
    if (!this.modal.contains(event.target)) {
      this.setState({ open: false })
    }
  }

  setModal(node) {
    this.modal = node
  }

  render() {
    let { modalOpen } = this.state
    return (
      <div>
        <button onClick={ this.open }>Open</button>
        {
          modalOpen ? <Modal close={ this.close } setModal={ this.setModal }/> : null
        }
      </div>
    )
  }
}

const Modal = ({ close, setModal }) => (
  <div className='modal' onClick={ close }>
    <div className='modal-window' ref={ setModal }>
    </div>
  </div>
)

Java Process with Input/Output Stream

I think you can use thread like demon-thread for reading your input and your output reader will already be in while loop in main thread so you can read and write at same time.You can modify your program like this:

Thread T=new Thread(new Runnable() {

    @Override
    public void run() {
        while(true)
        {
            String input = scan.nextLine();
            input += "\n";
            try {
                writer.write(input);
                writer.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }
} );
T.start();

and you can reader will be same as above i.e.

while ((line = reader.readLine ()) != null) {
    System.out.println ("Stdout: " + line);
}

make your writer as final otherwise it wont be able to accessible by inner class.

How can I rename a field for all documents in MongoDB?

please try db.collectionName.update({}, { $rename : { 'name.additional' : 'name.last' } }, { multi: true } )

and read this :) http://docs.mongodb.org/manual/reference/operator/rename/#_S_rename

Android lollipop change navigation bar color

  1. Create Black Color: <color name="blackColorPrimary">#000001</color> (not #000000)
  2. Write in Style: <item name="android:navigationBarColor" tools:targetApi="lollipop">@color/blackColorPrimary</item>

Problem is that android higher version make trasparent for #000000

How to delete large data of table in SQL without log?

@Francisco Goldenstein, just a minor correction. The COMMIT must be used after you set the variable, otherwise the WHILE will be executed just once:

DECLARE @Deleted_Rows INT;
SET @Deleted_Rows = 1;

WHILE (@Deleted_Rows > 0)
BEGIN
    BEGIN TRANSACTION

    -- Delete some small number of rows at a time
    DELETE TOP (10000)  LargeTable 
    WHERE readTime < dateadd(MONTH,-7,GETDATE())

    SET @Deleted_Rows = @@ROWCOUNT;

    COMMIT TRANSACTION
    CHECKPOINT -- for simple recovery model

END

How do I consume the JSON POST data in an Express application

For Express v4+

install body-parser from the npm.

$ npm install body-parser

https://www.npmjs.org/package/body-parser#installation

var express    = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res, next) {
  console.log(req.body) // populated!
  next()
})

How do I Set Background image in Flutter?

You can use the following code to set a background image to your app:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("images/background.jpg"),
            fit: BoxFit.cover,
          ),
        ),
        // use any child here
        child: null
      ),
    );
  }

If your Container's child is a Column widget, you can use the crossAxisAlignment: CrossAxisAlignment.stretch to make your background image fill the screen.

Printing newlines with print() in R

Using writeLines also allows you to dispense with the "\n" newline character, by using c(). As in:

writeLines(c("File not supplied.","Usage: ./program F=filename",[additional text for third line]))

This is helpful if you plan on writing a multiline message with combined fixed and variable input, such as the [additional text for third line] above.

NULL values inside NOT IN clause

SQL uses three-valued logic for truth values. The IN query produces the expected result:

SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE col IN (NULL, 1)
-- returns first row

But adding a NOT does not invert the results:

SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE NOT col IN (NULL, 1)
-- returns zero rows

This is because the above query is equivalent of the following:

SELECT * FROM (VALUES (1), (2)) AS tbl(col) WHERE NOT (col = NULL OR col = 1)

Here is how the where clause is evaluated:

| col | col = NULL?¹?  | col = 1 | col = NULL OR col = 1 | NOT (col = NULL OR col = 1) |
|-----|----------------|---------|-----------------------|-----------------------------|
| 1   | UNKNOWN        | TRUE    | TRUE                  | FALSE                       |
| 2   | UNKNOWN        | FALSE   | UNKNOWN?²?            | UNKNOWN?³?                  |

Notice that:

  1. The comparison involving NULL yields UNKNOWN
  2. The OR expression where none of the operands are TRUE and at least one operand is UNKNOWN yields UNKNOWN (ref)
  3. The NOT of UNKNOWN yields UNKNOWN (ref)

You can extend the above example to more than two values (e.g. NULL, 1 and 2) but the result will be same: if one of the values is NULL then no row will match.

Run a Java Application as a Service on Linux

Maybe not the best dev-ops solution, but good for the general use of a server for a lan party or similar.

Use screen to run your server in and then detach before logging out, this will keep the process running, you can then re-attach at any point.

Workflow:

Start a screen: screen

Start your server: java -jar minecraft-server.jar

Detach by pressing: Ctl-a, d

Re-attach: screen -r

More info here: https://www.gnu.org/software/screen/manual/screen.html

How to read values from the querystring with ASP.NET Core?

StringValues is an array of strings. You can get your string value by providing an index, e.g. HttpContext.Request.Query["page"][0].

Leaflet changing Marker color

Bind in the icons from this site!

https://github.com/pointhi/leaflet-color-markers

Detailed how-to information included on the website.

Edit: Use the code below to add a marker icon and just replace the link to the one with the color of your choice. (i.e. marker-icon-2x-green.png to some other image)

var greenIcon = new L.Icon({
  iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowSize: [41, 41]
});

L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map);

Firebase Storage How to store and Retrieve images

You can also use a service called Filepicker which will store your image to their servers and Filepicker which is now called Filestack, will provide you with a url to the image. You can than store the url to Firebase.

How to make PDF file downloadable in HTML link?

I solved mine using the whole url of the PDF file (Instead of just putting the file name or location to href): a href="domain . com/pdf/filename.pdf"

Converting a String to a List of Words?

This is from my attempt on a coding challenge that can't use regex,

outputList = "".join((c if c.isalnum() or c=="'" else ' ') for c in inputStr ).split(' ')

The role of apostrophe seems interesting.

Full width layout with twitter bootstrap

I think you could just use class "col-md-12" it has required left and right paddings and 100% width. Looks like this is a good replacement for container-fluid from 2nd bootstrap.

Javascript to Select Multiple options

A pure javascript solution

<select id="choice" multiple="multiple">
  <option value="1">One</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>
<script type="text/javascript">

var optionsToSelect = ['One', 'three'];
var select = document.getElementById( 'choice' );

for ( var i = 0, l = select.options.length, o; i < l; i++ )
{
  o = select.options[i];
  if ( optionsToSelect.indexOf( o.text ) != -1 )
  {
    o.selected = true;
  }
}

</script>

Although I agree this should be done server-side.

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

For those situations where you need a bit more customisation of the output (separator or decimal symbol), or who have large dataset (over 65k rows), I wrote the following:

Option Explicit

Sub rng2csv(rng As Range, fileName As String, Optional sep As String = ";", Optional decimalSign As String)
'export range data to a CSV file, allowing to chose the separator and decimal symbol
'can export using rng number formatting!
'by Patrick Honorez --- www.idevlop.com
    Dim f As Integer, i As Long, c As Long, r
    Dim ar, rowAr, sOut As String
    Dim replaceDecimal As Boolean, oldDec As String

    Dim a As Application:   Set a = Application

    ar = rng
    f = FreeFile()
    Open fileName For Output As #f

    oldDec = Format(0, ".")     'current client's decimal symbol
    replaceDecimal = (decimalSign <> "") And (decimalSign <> oldDec)

    For Each r In rng.Rows
        rowAr = a.Transpose(a.Transpose(r.Value))
        If replaceDecimal Then
            For c = 1 To UBound(rowAr)
                'use isnumber() to avoid cells with numbers formatted as strings
                If a.IsNumber(rowAr(c)) Then
                    'uncomment the next 3 lines to export numbers using source number formatting
'                    If r.cells(1, c).NumberFormat <> "General" Then
'                        rowAr(c) = Format$(rowAr(c), r.cells(1, c).NumberFormat)
'                    End If
                    rowAr(c) = Replace(rowAr(c), oldDec, decimalSign, 1, 1)
                End If
            Next c
        End If
        sOut = Join(rowAr, sep)
        Print #f, sOut
    Next r
    Close #f

End Sub

Sub export()
    Debug.Print Now, "Start export"
    rng2csv shOutput.Range("a1").CurrentRegion, RemoveExt(ThisWorkbook.FullName) & ".csv", ";", "."
    Debug.Print Now, "Export done"
End Sub

cast or convert a float to nvarchar?

DECLARE @MyFloat [float]

SET @MyFloat = 1000109360.050

SELECT REPLACE (RTRIM (REPLACE (REPLACE (RTRIM ((REPLACE (CAST (CAST (@MyFloat AS DECIMAL (38 ,18 )) AS VARCHAR( max)), '0' , ' '))), ' ' , '0'), '.', ' ')), ' ','.')

Center an item with position: relative

If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto

Vertical centering is a bit tricker, but possible.

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

In this particular case, an even simpler fix would be to just get rid of the "+" all together because AGE is a string literal and what comes before and after are also string literals. You could write line 3 as:

str += "Do you feel " AGE " years old?";

This is because most C/C++ compilers will concatenate string literals automatically. The above is equivalent to:

str += "Do you feel " "42" " years old?";

which the compiler will convert to:

str += "Do you feel 42 years old?";

How do I properly escape quotes inside HTML attributes?

Another option is replacing double quotes with single quotes if you don't mind whatever it is. But I don't mention this one:

<option value='"asd'>test</option>

I mention this one:

<option value="'asd">test</option>

In my case I used this solution.

'was not declared in this scope' error

You need to declare y and c outside the scope of the if/else statement. A variable is only valid inside the scope it is declared (and a scope is marked with { })

#include <iostream> 
using namespace std; 
//Using the Gaussian algorithm 
int dayofweek(int date, int month, int year ){ 
int d=date; 
int y, c;
if (month==1||month==2) 
        {y=((year-1)%100);c=(year-1)/100;} 
else 
        {y=year%100;c=year/100;} 
int m=(month+9)%12+1; 
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c); 
return product%7; 
} 

int main(){ 
cout<<dayofweek(19,1,2054); 
return 0; 
} 

How to convert an array of key-value tuples into an object

With Object.fromEntries, you can convert from Array to Object:

_x000D_
_x000D_
var entries = [_x000D_
  ['cardType', 'iDEBIT'],_x000D_
  ['txnAmount', '17.64'],_x000D_
  ['txnId', '20181'],_x000D_
  ['txnType', 'Purchase'],_x000D_
  ['txnDate', '2015/08/13 21:50:04'],_x000D_
  ['respCode', '0'],_x000D_
  ['isoCode', '0'],_x000D_
  ['authCode', ''],_x000D_
  ['acquirerInvoice', '0'],_x000D_
  ['message', ''],_x000D_
  ['isComplete', 'true'],_x000D_
  ['isTimeout', 'false']_x000D_
];_x000D_
var obj = Object.fromEntries(entries);_x000D_
console.log(obj);
_x000D_
_x000D_
_x000D_

What are the most-used vim commands/keypresses?

Go to Efficient Editing with vim and learn what you need to get started. Not everything on that page is essential starting off, so cherry pick what you want.

From there, use vim for everything. "hjkl", "y", and "p" will get you a long way, even if it's not the most efficient way. When you come up against a task for which you don't know the magic key to do it efficiently (or at all), and you find yourself doing it more than a few times, go look it up. Little by little it will become second nature.

I found vim daunting many moons ago (back when it didn't have the "m" on the end), but it only took about a week of steady use to get efficient. I still find it the quickest editor in which to get stuff done.

What is a quick way to force CRLF in C# / .NET?

Environment.NewLine;

A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

Just use ojdb6.jar and will fix all such issues.

For maven based applications:

  1. Download and copy ojdbc6.jar to a directory in your local machine

  2. From the location where you have copied your jar install the ojdbc6.jar in your local .M2 Repo by issuing below command C:\SRK\Softwares\Libraries>mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=ojdbc6.jar -DgeneratePom=true

  3. Add the below in your project pom.xml as ojdbc6.jar dependency

    <dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>11.2.0.3</version>
    </dependency>
    

PS: The issue might be due to uses of @Lob annotation in JPA for storing large objects specifically in oracle db columns. Upgrading to 11.2.0.3 (ojdbc6.jar) can resolve the issue.

Adding item to Dictionary within loop

In your current code, what Dictionary.update() does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.

If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_list as a list and then append case to it (instead of update) .

Example -

case_list = []
for entry in entries_list:
    case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
    case_list.append(case)

Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1 or entry2 , etc and the value being the corresponding dictionary for that entry.

case_list = {}
for entry in entries_list:
    case = {'key1': value, 'key2': value, 'key3':value }
    case_list[entryname] = case  #you will need to come up with the logic to get the entryname.

How to visualize an XML schema?

There is a new free-to-use webtool, where you can view any xml schema:

Online XML Schema Viewer

www.xml-tools.net

It's written completely in JavaScript, so it's running in most modern browsers.

What is the difference between the operating system and the kernel?

The difference between an operating system and a kernel:

The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:

  1. memory management
  2. network management
  3. device driver
  4. file management
  5. process management

Responsively change div size keeping aspect ratio

(function( $ ) {
  $.fn.keepRatio = function(which) {
      var $this = $(this);
      var w = $this.width();
      var h = $this.height();
      var ratio = w/h;
      $(window).resize(function() {
          switch(which) {
              case 'width':
                  var nh = $this.width() / ratio;
                  $this.css('height', nh + 'px');
                  break;
              case 'height':
                  var nw = $this.height() * ratio;
                  $this.css('width', nw + 'px');
                  break;
          }
      });

  }
})( jQuery );      

$(document).ready(function(){
    $('#foo').keepRatio('width');
});

Working example: http://jsfiddle.net/QtftX/1/

What are good grep tools for Windows?

dnGREP is an open source grep tool for Windows. It supports a number of cool features including:

  • Undo for replace
  • Ability to search by right clicking on folder in explorer
  • Advance search options such as phonetic search and xpath
  • Search inside PDF files, archives, and Word documents

IMHO, it has a nice and clean interface too :)

Moving average or running mean

I feel this can be elegantly solved using bottleneck

See basic sample below:

import numpy as np
import bottleneck as bn

a = np.random.randint(4, 1000, size=100)
mm = bn.move_mean(a, window=5, min_count=1)
  • "mm" is the moving mean for "a".

  • "window" is the max number of entries to consider for moving mean.

  • "min_count" is min number of entries to consider for moving mean (e.g. for first few elements or if the array has nan values).

The good part is Bottleneck helps to deal with nan values and it's also very efficient.

Configure Flask dev server to be visible across the network

Add below lines to your project

if __name__ == '__main__':
    app.debug = True
    app.run(host = '0.0.0.0',port=5005)

How to set default values in Go structs

type Config struct {
    AWSRegion                               string `default:"us-west-2"`
}

open link in iframe

Try this:

<iframe name="iframe1" src="target.html"></iframe>

<a href="link.html" target="iframe1">link</a>

The "target" attribute should open in the iframe.

jQuery bind/unbind 'scroll' event on $(window)

try this:

$(window).unbind('scroll');

it works in my project

How to set the style -webkit-transform dynamically using JavaScript?

Here are the JavaScript notations for most common vendors:

webkitProperty
MozProperty
msProperty
OProperty
property

I reset inline transform styles like:

element.style.webkitTransform = "";
element.style.MozTransform = "";
element.style.msTransform = "";
element.style.OTransform = "";
element.style.transform = "";

And like this using jQuery:

$(element).css({
    "webkitTransform":"",
    "MozTransform":"",
    "msTransform":"",
    "OTransform":"",
    "transform":""
});

See blog post Coding Vendor Prefixes with JavaScript (2012-03-21).

How to map an array of objects in React

try the following snippet

const renObjData = this.props.data.map(function(data, idx) {
    return <ul key={idx}>{$.map(data,(val,ind) => {
        return (<li>{val}</li>);
    }
    }</ul>;
});

read complete file without using loop in java

Since Java 11 you can do it even simpler:

import java.nio.file.Files;

Files.readString(Path path);
Files.readString?(Path path, Charset cs)

Source: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)

milliseconds to time in javascript

var 
         /**
         * Parses time in milliseconds to time structure
         * @param {Number} ms
         * @returns {Object} timeStruct
         * @return {Integer} timeStruct.d days
         * @return  {Integer} timeStruct.h hours
         * @return  {Integer} timeStruct.m minutes
         * @return  {Integer} timeStruct.s seconds
         */
        millisecToTimeStruct = function (ms) {
            var d, h, m, s;
            if (isNaN(ms)) {
                return {};
            }
            d = ms / (1000 * 60 * 60 * 24);
            h = (d - ~~d) * 24;
            m = (h - ~~h) * 60;
            s = (m - ~~m) * 60;
            return {d: ~~d, h: ~~h, m: ~~m, s: ~~s};
        },

        toFormattedStr = function(tStruct){
           var res = '';
           if (typeof tStruct === 'object'){
               res += tStruct.m + ' min. ' + tStruct.s + ' sec.';
           }
           return res;
        };

// client code:
var
        ms = new Date().getTime(),
        timeStruct = millisecToTimeStruct(ms),
        formattedString = toFormattedStr(timeStruct);
alert(formattedString);

Checking if date is weekend PHP

If you're using PHP 5.5 or PHP 7 above, you may want to use:

function isTodayWeekend() {
    return in_array(date("l"), ["Saturday", "Sunday"]);
}

and it will return "true" if today is weekend and "false" if not.

WPF: ItemsControl with scrollbar (ScrollViewer)

You have to modify the control template instead of ItemsPanelTemplate:

<ItemsControl >
    <ItemsControl.Template>
        <ControlTemplate>
            <ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
                <ItemsPresenter />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
</ItemsControl>

Maybe, your code does not working because StackPanel has own scrolling functionality. Try to use StackPanel.CanVerticallyScroll property.

Android Percentage Layout Height

You could add another empty layout below that one and set them both to have the same layout weight. They should get 50% of the space each.

Git fast forward VS no fast forward merge

I can give an example commonly seen in project.

Here, option --no-ff (i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff (i.e. fast-forward merge) is by default.

$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature'         // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk                           // => see details with graph

$ git checkout -b anotherFeature        // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature       // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk                           // => see details with graph

(*) Note that here if the newFeature branch is re-used, instead of creating a new branch, git will have to do a --no-ff merge anyway. This means fast forward merge is not always eligible.

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

Xcode 9 Swift Language Version (SWIFT_VERSION)

This Solution works when nothing else works:

I spent more than a week to convert the whole project and came to a solution below:

First, de-integrate the cocopods dependency from the project and then start converting the project to the latest swift version.

Go to Project Directory in the Terminal and Type:

pod deintegrate

This will de-integrate cocopods from the project and No traces of CocoaPods will be left in the project. But at the same time, it won't delete the xcworkspace and podfiles. It's ok if they are present.

Now you have to open xcodeproj(not xcworkspace) and you will get lots of errors because you have called cocoapods dependency methods in your main projects.

So to remove those errors you have two options:

  1. Comment down all the code you have used from cocoapods library.
  2. Create a wrapper class which has dummy methods similar to cocopods library, and then call it.

Once all the errors get removed you can convert the code to the latest swift version.

Sometimes if you are getting weird errors then try cleaning derived data and try again.

What is the difference between single-quoted and double-quoted strings in PHP?

A single-quoted string does not have variables within it interpreted. A double-quoted string does.

Also, a double-quoted string can contain apostrophes without backslashes, while a single-quoted string can contain unescaped quotation marks.

The single-quoted strings are faster at runtime because they do not need to be parsed.

Best way to create a temp table with same columns and type as a permanent table

Clone Temporary Table Structure to New Physical Table in SQL Server

enter image description here

we will see how to Clone Temporary Table Structure to New Physical Table in SQL Server.This is applicable for both Azure SQL db and on-premises.

Demo SQL Script

IF OBJECT_ID('TempDB..#TempTable') IS NOT NULL
    DROP TABLE #TempTable;

SELECT 1 AS ID,'Arul' AS Names
INTO
#TempTable;

SELECT * FROM #TempTable;

METHOD 1

SELECT * INTO TempTable1 FROM #TempTable WHERE 1=0;

EXEC SP_HELP TempTable1;

enter image description here

METHOD 2

SELECT TOP 0 * INTO TempTable1 FROM #TempTable;

EXEC SP_HELP TempTable1;

enter image description here

PKIX path building failed in Java application

If you are using Eclipse just cross check in Eclipse Windows--> preferences---->java---> installed JREs is pointing the current JRE and the JRE where you have configured your certificate. If not remove the JRE and add the jre where your certificate is installed

iOS app 'The application could not be verified' only on one device

I faced this issue a lot. I am not sure if this is the issue, but I think, when xCode saw that there is an app with the same bundle identifier as of the app, I am trying to install, it didn't allow me. So, I had to delete the older one and attempted to install and it worked. However sometimes for testing purpose, I needed multiple version of the same app and in that case, I would change the bundle identifier and try to install. It only works if, I am using an wildcard provisioning profile.

strcpy() error in Visual studio 2012

If you are getting an error saying something about deprecated functions, try doing #define _CRT_SECURE_NO_WARNINGS or #define _CRT_SECURE_NO_DEPRECATE. These should fix it. You can also use Microsoft's "secure" functions, if you want.

maven error: package org.junit does not exist

if you are using Eclipse watch your POM dependencies and your Eclipse buildpath dependency on junit

if you select use Junit4 eclipse create TestCase using org.junit package but your POM use by default Junit3 (junit.framework package) that is the cause, like this picture:

see JUNIT conflict

Just update your Junit dependency in your POM file to Junit4 or your Eclipse BuildPath to Junit3

Java TreeMap Comparator

You can not sort TreeMap on values.

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used You will need to provide comparator for Comparator<? super K> so your comparator should compare on keys.

To provide sort on values you will need SortedSet. Use

SortedSet<Map.Entry<String, Double>> sortedset = new TreeSet<Map.Entry<String, Double>>(
            new Comparator<Map.Entry<String, Double>>() {
                @Override
                public int compare(Map.Entry<String, Double> e1,
                        Map.Entry<String, Double> e2) {
                    return e1.getValue().compareTo(e2.getValue());
                }
            });

  sortedset.addAll(myMap.entrySet());

To give you an example

    SortedMap<String, Double> myMap = new TreeMap<String, Double>();
    myMap.put("a", 10.0);
    myMap.put("b", 9.0);
    myMap.put("c", 11.0);
    myMap.put("d", 2.0);
    sortedset.addAll(myMap.entrySet());
    System.out.println(sortedset);

Output:

  [d=2.0, b=9.0, a=10.0, c=11.0]

javac error: Class names are only accepted if annotation processing is explicitly requested

chandan@cmaster:~/More$ javac New.java
chandan@cmaster:~/More$ javac New
error: Class names, 'New', are only accepted if annotation processing is explicitly requested
1 error

So if you by mistake after compiling again use javac for running a program.

How to query as GROUP BY in django?

The following module allows you to group Django models and still work with a QuerySet in the result: https://github.com/kako-nawao/django-group-by

For example:

from django_group_by import GroupByMixin

class BookQuerySet(QuerySet, GroupByMixin):
    pass

class Book(Model):
    title = TextField(...)
    author = ForeignKey(User, ...)
    shop = ForeignKey(Shop, ...)
    price = DecimalField(...)

class GroupedBookListView(PaginationMixin, ListView):
    template_name = 'book/books.html'
    model = Book
    paginate_by = 100

    def get_queryset(self):
        return Book.objects.group_by('title', 'author').annotate(
            shop_count=Count('shop'), price_avg=Avg('price')).order_by(
            'name', 'author').distinct()

    def get_context_data(self, **kwargs):
        return super().get_context_data(total_count=self.get_queryset().count(), **kwargs)

'book/books.html'

<ul>
{% for book in object_list %}
    <li>
        <h2>{{ book.title }}</td>
        <p>{{ book.author.last_name }}, {{ book.author.first_name }}</p>
        <p>{{ book.shop_count }}</p>
        <p>{{ book.price_avg }}</p>
    </li>
{% endfor %}
</ul>

The difference to the annotate/aggregate basic Django queries is the use of the attributes of a related field, e.g. book.author.last_name.

If you need the PKs of the instances that have been grouped together, add the following annotation:

.annotate(pks=ArrayAgg('id'))

NOTE: ArrayAgg is a Postgres specific function, available from Django 1.9 onwards: https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/aggregates/#arrayagg

When is "java.io.IOException:Connection reset by peer" thrown?

java.io.IOException: Connection reset by peer

The other side has abruptly aborted the connection in midst of a transaction. That can have many causes which are not controllable from the server side on. E.g. the enduser decided to shutdown the client or change the server abruptly while still interacting with your server, or the client program has crashed, or the enduser's internet connection went down, or the enduser's machine crashed, etc, etc.

Single statement across multiple lines in VB.NET without the underscore character

No, you have to use the underscore, but I believe that VB.NET 10 will allow multiple lines w/o the underscore, only requiring if it can't figure out where the end should be.

Cannot GET / Nodejs Error

Much like leonardocsouza, I had the same problem. To clarify a bit, this is what my folder structure looked like when I ran node server.js

node_modules/
app/
  index.html
  server.js

After printing out the __dirname path, I realized that the __dirname path was where my server was running (app/).

So, the answer to your question is this:

If your server.js file is in the same folder as the files you are trying to render, then

app.use( express.static( path.join( application_root, 'site') ) );

should actually be

app.use(express.static(application_root));

The only time you would want to use the original syntax that you had would be if you had a folder tree like so:

app/
  index.html
node_modules
server.js

where index.html is in the app/ directory, whereas server.js is in the root directory (i.e. the same level as the app/ directory).

Side note: Intead of calling the path utility, you can use the syntax application_root + 'site' to join a path.

Overall, your code could look like:

// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
mongoose = require( 'mongoose' ); //MongoDB integration

//Create server
var app = express();

// Configure server
app.configure( function() {

    //Don't change anything here...

    //Where to serve static content
    app.use( express.static( application_root ) );

    //Nothing changes here either...
});

//Start server --- No changes made here
var port = 5000;
app.listen( port, function() {
    console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});

How do I sort a VARCHAR column in SQL server that contains numbers?

 SELECT *,
       ROW_NUMBER()OVER(ORDER BY CASE WHEN ISNUMERIC (ID)=1 THEN CONVERT(NUMERIC(20,2),SUBSTRING(Id, PATINDEX('%[0-9]%', Id), LEN(Id)))END DESC)Rn ---- numerical
        FROM
            (

        SELECT '1'Id UNION ALL
        SELECT '25.20' Id UNION ALL

    SELECT 'A115' Id UNION ALL
    SELECT '2541' Id UNION ALL
    SELECT '571.50' Id UNION ALL
    SELECT '67' Id UNION ALL
    SELECT 'B48' Id UNION ALL
    SELECT '500' Id UNION ALL
    SELECT '147.54' Id UNION ALL
    SELECT 'A-100' Id
    )A

    ORDER BY 
    CASE WHEN ISNUMERIC (ID)=0                                /* alphabetical sort */ 
         THEN CASE WHEN PATINDEX('%[0-9]%', Id)=0
                   THEN LEFT(Id,PATINDEX('%[0-9]%',Id))
                   ELSE LEFT(Id,PATINDEX('%[0-9]%',Id)-1)
              END
    END DESC

Android EditText delete(backspace) key event

NOTE: onKeyListener doesn't work for soft keyboards.

You can set OnKeyListener for you editText so you can detect any key press
EDIT: A common mistake we are checking KeyEvent.KEYCODE_BACK for backspace, but really it is KeyEvent.KEYCODE_DEL (Really that name is very confusing! )

editText.setOnKeyListener(new OnKeyListener() {                 
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        //You can identify which key pressed buy checking keyCode value with KeyEvent.KEYCODE_
        if(keyCode == KeyEvent.KEYCODE_DEL) {  
            //this is for backspace
        }
        return false;       
    }
});

How to read a HttpOnly cookie using JavaScript

The whole point of HttpOnly cookies is that they can't be accessed by JavaScript.

The only way (except for exploiting browser bugs) for your script to read them is to have a cooperating script on the server that will read the cookie value and echo it back as part of the response content. But if you can and would do that, why use HttpOnly cookies in the first place?

Inline comments for Bash?

$(: ...) is a little less ugly, but still not good.

How do I execute a string containing Python code in Python?

You accomplish executing code using exec, as with the following IDLE session:

>>> kw = {}
>>> exec( "ret = 4" ) in kw
>>> kw['ret']

4

Easy way to use variables of enum types as string in C?

Here is a solution using macros with the following features:

  1. only write each value of the enum once, so there are no double lists to maintain

  2. don't keep the enum values in a separate file that is later #included, so I can write it wherever I want

  3. don't replace the enum itself, I still want to have the enum type defined, but in addition to it I want to be able to map every enum name to the corresponding string (to not affect legacy code)

  4. the searching should be fast, so preferably no switch-case, for those huge enums

https://stackoverflow.com/a/20134475/1812866

Hidden Columns in jqGrid

This feature is built into jqGrid.

setup your grid function as follows.

$('#myGrid').jqGrid({
   ...
   colNames: ['Manager', 'Name', 'HiddenSalary'],
   colModel: [               
               { name: 'Manager', editable: true },
               { name: 'Price', editable: true },
               { name: 'HiddenSalary', hidden: true , editable: true, 
                  editrules: {edithidden:true} 
               }
             ],
   ...
};

There are other editrules that can be applied but this basic setup would hide the manager's salary in the grid view but would allow editing when the edit form was displayed.

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

I had the same issue. But this method solved it. Go to the android folder using cd android then gradlew clean or ./gradlew clean whichever works for your os.

Convert hex to binary

Just use the module coden (note: I am the author of the module)

You can convert haxedecimal to binary there.

  1. Install using pip
pip install coden
  1. Convert
a_hexadecimal_number = "f1ff"
binary_output = coden.hex_to_bin(a_hexadecimal_number)

The converting Keywords are:

  • hex for hexadeimal
  • bin for binary
  • int for decimal
  • _to_ - the converting keyword for the function

So you can also format: e. hexadecimal_output = bin_to_hex(a_binary_number)

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

Just in case you want to try something else. This is what worked for me:

Based on Ternary Operator which has following structure:

condition ? value-if-true : value-if-false

As result:

{{gallery.date?(gallery.date | date:'mediumDate'):"Various" }}

Usage of unicode() and encode() functions in Python

Make sure you've set your locale settings right before running the script from the shell, e.g.

$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8

Docs: man locale, man setlocale.

How do I split a string in Rust?

There is a special method split for struct String:

fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> where P: Pattern<'a>

Split by char:

let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);

Split by string:

let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);

Split by closure:

let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
assert_eq!(v, ["abc", "def", "ghi"]);

How to change MySQL column definition?

Syntax to change column name in MySql:

alter table table_name change old_column_name new_column_name data_type(size);

Example:

alter table test change LowSal Low_Sal integer(4);

How to use GROUP_CONCAT in a CONCAT in MySQL

IF OBJECT_ID('master..test') is not null Drop table test

CREATE TABLE test (ID INTEGER, NAME VARCHAR (50), VALUE INTEGER );
INSERT INTO test VALUES (1, 'A', 4);
INSERT INTO test VALUES (1, 'A', 5);
INSERT INTO test VALUES (1, 'B', 8);
INSERT INTO test VALUES (2, 'C', 9);

select distinct NAME , LIST = Replace(Replace(Stuff((select ',', +Value from test where name = _a.name for xml path('')), 1,1,''),'<Value>', ''),'</Value>','') from test _a order by 1 desc

My table name is test , and for concatination I use the For XML Path('') syntax. The stuff function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

STUFF functions looks like this : STUFF (character_expression , start , length ,character_expression )

character_expression Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.

start Is an integer value that specifies the location to start deletion and insertion. If start or length is negative, a null string is returned. If start is longer than the first character_expression, a null string is returned. start can be of type bigint.

length Is an integer that specifies the number of characters to delete. If length is longer than the first character_expression, deletion occurs up to the last character in the last character_expression. length can be of type bigint.

Subtract days from a DateTime

I've had issues using AddDays(-1).

My solution is TimeSpan.

DateTime.Now - TimeSpan.FromDays(1);

Is it a good practice to place C++ definitions in header files?

Template code should be in headers only. Apart from that all definitions except inlines should be in .cpp. The best argument for this would be the std library implementations which follow the same rule. You would not disagree the std lib developers would be right regarding this.

Travel/Hotel API's?

HotelsCombined has an easy-to-access and useful service to download the data feed files with hotels. Not exactly API, but something you can get, parse and use. Here is how you do it:

  1. Go to http://www.hotelscombined.com/Affiliates.aspx
  2. Register there (no company or bank data is needed)
  3. Open “Data feeds” page
  4. Choose “Standard data feed” -> “Single file” -> “CSV format” (you may get XML as well)

If you are interested in details, you may find the sample Python code to filter CSV file to get hotels for a specific city here:

http://mikhail.io/2012/05/17/api-to-get-the-list-of-hotels/

Update:

Unfortunately, HotelsCombined.com has introduced the new regulations: they've restricted the access to data feeds by default. To get the access, a partner must submit some information on why one needs the data. The HC team will review it and then (maybe) will grant access.

SQL Server: converting UniqueIdentifier to string in a case statement

I think I found the answer:

convert(nvarchar(50), RequestID)

Here's the link where I found this info:

http://msdn.microsoft.com/en-us/library/ms187928.aspx

Declaring and using MySQL varchar variables

Looks like you forgot the @ in variable declaration. Also I remember having problems with SET in MySql a long time ago.

Try

DECLARE @FOO varchar(7);
DECLARE @oldFOO varchar(7);
SELECT @FOO = '138';
SELECT @oldFOO = CONCAT('0', @FOO);

update mypermits 
   set person = @FOO 
 where person = @oldFOO;

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

there is a bit other case - data is sent from client to server. when you are using controller method and model is huge :

    [HttpPost]
    public ActionResult AddOrUpdateConsumerFile(FileMetaDataModelView inputModel)
    {
        if (inputModel == null) return null;
     ....
    }

system throws exception like this "Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. Parameter name: input"

Only changing Web.config settings is not enough to help in this case. You could additionally override mvc json serializer for supporting huge data model sizes or manually deserialize model from Request. Your controller method becomes:

   [HttpPost]
    public ActionResult AddOrUpdateConsumerFile()
    {
        FileMetaDataModelView inputModel = RequestManager.GetModelFromJsonRequest<FileMetaDataModelView>(HttpContext.Request);
        if (inputModel == null) return null;
        ......
    }

   public static T GetModelFromJsonRequest<T>(HttpRequestBase request)
    {
        string result = "";
        using (Stream req = request.InputStream)
        {
            req.Seek(0, System.IO.SeekOrigin.Begin);
            result = new StreamReader(req).ReadToEnd();
        }
        return JsonConvert.DeserializeObject<T>(result);
    }

PHP Multiple Checkbox Array

Also remember you can include custom indices to the array sent to the server like this

<form method='post' id='userform' action='thisform.php'>
<tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[4]' value='Option One'>4<br>
    <input type='checkbox' name='checkboxvar[6]' value='Option Two'>6<br>
    <input type='checkbox' name='checkboxvar[9]' value='Option Three'>9
    </td>
</tr>
<input type='submit' class='buttons'>
</form>

This is particularly useful when you want to use the id of individual objects in a server array accounts (for instance) to send data back to the server and recognize same at server

<form method='post' id='userform' action='thisform.php'>
<tr>
    <td>Trouble Type</td>
    <td>
    <?php foreach($accounts as $account) { ?>
        <input type='checkbox' name='accounts[<?php echo $account->id ?>]' value='<?php echo $account->name ?>'>
        <?php echo $account->name ?>
        <br>
    <?php } ?>
    </td>
</tr>
<input type='submit' class='buttons'>
</form>

<?php 
if (isset($_POST['accounts'])) 
{
    print_r($_POST['accounts']); 
}
?>

How to get table cells evenly spaced?

In your CSS file:

.TableHeader { width: 100px; }

This will set all of the td tags below each header to 100px. You can also add a width definition (in the markup) to each individual th tag, but the above solution would be easier.

How to do what head, tail, more, less, sed do in Powershell?

I got some better solutions:

gc log.txt -ReadCount 5 | %{$_;throw "pipeline end!"} # head
gc log.txt | %{$num=0;}{$num++;"$num $_"}             # cat -n
gc log.txt | %{$num=0;}{$num++; if($num -gt 2 -and $num -lt 7){"$num $_"}} # sed

Tomcat Server Error - Port 8080 already in use

I would suggest to end java.exe or javaw.exe process from task manager and try again. This will not end the entire eclipse application but will free the port.

Align <div> elements side by side

Apply float:left; to both of your divs should make them stand side by side.

What is the simplest and most robust way to get the user's current location on Android?

This is the way I am requesting User Permissions.

Outside your application tag in AndroidManifest.xml add these permission requests.

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

Then add Google's Location dependencies in the App Gradle file.

implementation 'com.google.android.gms:play-services-location:15.0.0'

Now declare some Global variables.

private lateinit var mFusedLocationProvider:FusedLocationProviderClient
private lateinit var mLocationCallback: LocationCallback
private lateinit var mLocationRequest: LocationRequest
private var mLocationPermissionGranted:Boolean = false

In OnCreate method of your Activity (I was not able to Format the Code Properly, Apology for that)

mFusedLocationProvider = LocationServices.getFusedLocationProviderClient(this)

//Location Callback
mLocationCallback = object: LocationCallback(){
 override fun onLocationResult(p0: LocationResult?) {
  if(p0==null){
     //todo(request user to enable location from settings then remove return)
     return
  }else{
      getDeviceLocation()
       }
  }
}

//Location Request
mLocationRequest = LocationRequest.create()
mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
//Set the Interval for Latest Interval Update
mLocationRequest.interval = 5000
//Set How Many Location Updated you Want
mLocationRequest.numUpdates = 1

getLocationPermission()
getDeviceLocation()

Now create both the functions.

 private fun getLocationPermission() {

            val permission:Array<String> = arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION)
            if(ContextCompat.checkSelfPermission(applicationContext,Constant.FINE_LOCATION)== PermissionChecker.PERMISSION_GRANTED){
                if(ContextCompat.checkSelfPermission(applicationContext,Constant.COARSE_LOCATION)== PermissionChecker.PERMISSION_GRANTED){
                    mLocationPermissionGranted = true
                }
            }else{
                ActivityCompat.requestPermissions(this,permission,Constant.LOCATION_REQUEST_CODE)
            }

    }

Second Method

private fun getDeviceLocation() {
        try{
            if(mLocationPermissionGranted){

                mFusedLocationProvider.lastLocation.addOnCompleteListener(this,{task: Task<Location> ->
                    if(task.isSuccessful){
                        var currentLocation: Location? = task.result
                        if(currentLocation!=null){

                            Log.i("Location","Latitude is ${currentLocation.latitude} and Longitude" +
                                    "${currentLocation.longitude}")
                        }

                        else
                            mFusedLocationProvider.requestLocationUpdates(mLocationRequest,mLocationCallback,null)
                    }
                })
            }
        }catch (e:SecurityException){
            Log.e("Error", "Security Exception ${e.message}")
        }
    }

For Constant.kt

class Constant{
    companion object {

        //Location Request Settings
        const val SET_INTERVAL:Long = 2000
        const val NUM_UPDATES:Int = 1

        //Location Permission
        const val FINE_LOCATION:String = android.Manifest.permission.ACCESS_FINE_LOCATION
        const val COARSE_LOCATION:String = android.Manifest.permission.ACCESS_COARSE_LOCATION
    }
}

Illegal character in path at index 16

There's an illegal character at index 16. I'd say it doesn't like the space in the path. You can percent encode special characters like spaces. Replace it with a %20 in this case.

The question I linked to above suggests using URLEncoder:

String thePath = "file://E:/Program Files/IBM/SDP/runtimes/base";
thePath = URLEncoder.encode(thePath, "UTF-8"); 

Using the AND and NOT Operator in Python

You should write :

if (self.a != 0) and (self.b != 0) :

"&" is the bit wise operator and does not suit for boolean operations. The equivalent of "&&" is "and" in Python.

A shorter way to check what you want is to use the "in" operator :

if 0 not in (self.a, self.b) :

You can check if anything is part of a an iterable with "in", it works for :

  • Tuples. I.E : "foo" in ("foo", 1, c, etc) will return true
  • Lists. I.E : "foo" in ["foo", 1, c, etc] will return true
  • Strings. I.E : "a" in "ago" will return true
  • Dict. I.E : "foo" in {"foo" : "bar"} will return true

As an answer to the comments :

Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.

For the triangle check, it's easier to read :

0 not in (self.a, self.b, self.c)

Than

(self.a != 0) and (self.b != 0) and (self.c != 0) 

It's easier to refactor too.

Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs.

How can I commit files with git?

The command for commiting all changed files:

git commit -a -m 'My commit comments'

-a = all edited files

-m = following string is a comment.

This will commit to your local drives / folders repo. If you want to push your changes to a git server / remotely hosted server, after the above command type:

git push

GitHub's cheat sheet is quite handy.

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

Cause you need to add jQuery library to your file:

jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.

<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>

How to make a progress bar

var myPer = 35;
$("#progressbar")
    .progressbar({ value: myPer })
    .children('.ui-progressbar-value')
    .html(myPer.toPrecision(3) + '%')
    .css("display", "block");

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

Change old commit message on Git

Here's a very nice Gist that covers all the possible cases: https://gist.github.com/nepsilon/156387acf9e1e72d48fa35c4fabef0b4

Overview:

git rebase -i HEAD~X
# X is the number of commits to go back
# Move to the line of your commit, change pick into edit,
# then change your commit message:
git commit --amend
# Finish the rebase with:
git rebase --continue

Python class input argument

Remove the name param from the class declaration. The init method is used to pass arguments to a class at creation.

class Person(object):
  def __init__(self, name):
    self.name = name

me = Person("TheLazyScripter")
print me.name

CSS Selector for <input type="?"

Sadly the other posters are correct that you're ...actually as corrected by kRON, you are ok with your IE7 and a strict doc, but most of us with IE6 requirements are reduced to JS or class references for this, but it is a CSS2 property, just one without sufficient support from IE^h^h browsers.

Out of completeness, the type selector is - similar to xpath - of the form [attribute=value] but many interesting variants exist. It will be quite powerful when it's available, good thing to keep in your head for IE8.