Programs & Examples On #Grahams scan

How to make div same height as parent (displayed as table-cell)

Another option is to set your child div to display: inline-block;

.content {
    display: inline-block;
    height: 100%;
    width: 100%;
    background-color: blue;
}

_x000D_
_x000D_
.container {_x000D_
  display: table;_x000D_
}_x000D_
.child {_x000D_
  width: 30px;_x000D_
  background-color: red;_x000D_
  display: table-cell;_x000D_
  vertical-align: top;_x000D_
}_x000D_
.content {_x000D_
  display: inline-block;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="child">_x000D_
    a_x000D_
    <br />a_x000D_
    <br />a_x000D_
  </div>_x000D_
  <div class="child">_x000D_
    a_x000D_
    <br />a_x000D_
    <br />a_x000D_
    <br />a_x000D_
    <br />a_x000D_
    <br />a_x000D_
    <br />a_x000D_
  </div>_x000D_
  <div class="child">_x000D_
    <div class="content">_x000D_
      a_x000D_
      <br />a_x000D_
      <br />a_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


JSFiddle Demo

Input button target="_blank" isn't causing the link to load in a new window/tab

use formtarget="_blank" its working for me

<input type="button" onClick="parent.location='http://www.facebook.com/'" value="facebook" formtarget="_blank">

Browser compatibility: from caniuse.com
IE: 10+ | Edge: 12+ | Firefox: 4+ | Chrome: 15+ | Safari/iOS: 5.1+ | Android: 4+

Draw on HTML5 Canvas using a mouse

A super short version, here, without position:absolute in vanilla JavaScript. The main idea is to move the canvas' context to the right coordinates and draw a line. Uncomment click handler and comment mousedown & mousemove handlers below to get a feel for how it is working.

<!DOCTYPE html>
<html>
<body>

<p style="margin: 50px">Just some padding in y direction</p>

<canvas id="myCanvas" width="300" height="300" style="background: #000; margin-left: 100px;">Your browser does not support the HTML5 canvas tag.</canvas>

<script>
    const c = document.getElementById("myCanvas");
    // c.addEventListener("click", penTool); // fires after mouse left btn is released
    c.addEventListener("mousedown", setLastCoords); // fires before mouse left btn is released
    c.addEventListener("mousemove", freeForm);


    const ctx = c.getContext("2d");

    function setLastCoords(e) {
        const {x, y} = c.getBoundingClientRect();
        lastX = e.clientX - x;
        lastY = e.clientY - y;
    }

    function freeForm(e) {
        if (e.buttons !== 1) return; // left button is not pushed yet
        penTool(e);
    }

    function penTool(e) {
        const {x, y} = c.getBoundingClientRect();
        const newX = e.clientX - x;
        const newY = e.clientY - y;

        ctx.beginPath();
        ctx.lineWidth = 5;
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(newX, newY);
        ctx.strokeStyle = 'white';
        ctx.stroke();
        ctx.closePath();

        lastX = newX;
        lastY = newY;
    }

    let lastX = 0;
    let lastY = 0;  
</script>

</body>
</html>

jQuery scroll to element

If you are not much interested in the smooth scroll effect and just interested in scrolling to a particular element, you don't require some jQuery function for this. Javascript has got your case covered:

https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView

So all you need to do is: $("selector").get(0).scrollIntoView();

.get(0) is used because we want to retrieve the JavaScript's DOM element and not the JQuery's DOM element.

How do I draw a set of vertical lines in gnuplot?

To elaborate on previous answers about the "every x units" part, here is what I came up with:

# Draw 5 vertical lines
n = 5

# ... evenly spaced between x0 and x1
x0 = 1.0
x1 = 2.0
dx = (x1-x0)/(n-1.0)

# ... each line going from y0 to y1
y0 = 0
y1 = 10

do for [i = 0:n-1] {
    x = x0 + i*dx
    set arrow from x,y0 to x,y1 nohead linecolor "blue" # add other styling options if needed
}

using stored procedure in entity framework

// Add some tenants to context so we have something for the procedure to return! AddTenentsToContext(Context);

    // ACT
    // Get the results by calling the stored procedure from the context extention method 
    var results = Context.ExecuteStoredProcedure(procedure);

    // ASSERT
    Assert.AreEqual(expectedCount, results.Count);
}

How to solve privileges issues when restore PostgreSQL Database

AWS RDS users if you are getting this it is because you are not a superuser and according to aws documentation you cannot be one. I have found I have to ignore these errors.

Find a string by searching all tables in SQL Server Management Studio 2008

A bit late but hopefully useful.

Why not try some of the third party tools that can be integrated into SSMS.

I’ve worked with ApexSQL Search (100% free) with good success for both schema and data search and there is also SSMS tools pack that has this feature (not free for SQL 2012 but quite affordable).

Stored procedure above is really great; it’s just that this is way more convenient in my opinion. Also, it would require some slight modifications if you want to search for datetime columns or GUID columns and such…

What’s the best way to load a JSONObject from a json text file?

try this:

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils; 

    public class JsonParsing {

        public static void main(String[] args) throws Exception {
            InputStream is = 
                    JsonParsing.class.getResourceAsStream( "sample-json.txt");
            String jsonTxt = IOUtils.toString( is );

            JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );        
            double coolness = json.getDouble( "coolness" );
            int altitude = json.getInt( "altitude" );
            JSONObject pilot = json.getJSONObject("pilot");
            String firstName = pilot.getString("firstName");
            String lastName = pilot.getString("lastName");

            System.out.println( "Coolness: " + coolness );
            System.out.println( "Altitude: " + altitude );
            System.out.println( "Pilot: " + lastName );
        }
    }

and this is your sample-json.txt , should be in json format

{
 'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':
     {
         'firstName':'Buzz',
         'lastName':'Aldrin'
     },
 'mission':'apollo 11'
}

What's the HTML to have a horizontal space between two objects?

I think what you mean is putting 2 paragraphs (for example) in 2 columns instead of one below the other? In that case, I think float is your solution.

<div style="float: left"> <!-- would cause this to hang on the left -->
<div style="float: right"> <!-- would cause this to hang on the right-->

Here's an example: http://jsfiddle.net/XPfLA/1

How to compare files from two different branches?

There are many ways to compare files from two different branches:

  • Option 1: If you want to compare the file from n specific branch to another specific branch:

    git diff branch1name branch2name path/to/file
    

    Example:

    git diff mybranch/myfile.cs mysecondbranch/myfile.cs
    

    In this example you are comparing the file in “mybranch” branch to the file in the “mysecondbranch” branch.

  • Option 2: Simple way:

     git diff branch1:file branch2:file
    

    Example:

     git diff mybranch:myfile.cs mysecondbranch:myfile.cs
    

    This example is similar to the option 1.

  • Option 3: If you want to compare your current working directory to some branch:

    git diff ..someBranch path/to/file
    

    Example:

    git diff ..master myfile.cs
    

    In this example you are comparing the file from your actual branch to the file in the master branch.

Difference between UTF-8 and UTF-16?

This is unrelated to UTF-8/16 (in general, although it does convert to UTF16 and the BE/LE part can be set w/ a single line), yet below is the fastest way to convert String to byte[]. For instance: good exactly for the case provided (hash code). String.getBytes(enc) is relatively slow.

static byte[] toBytes(String s){
        byte[] b=new byte[s.length()*2];
        ByteBuffer.wrap(b).asCharBuffer().put(s);
        return b;
    }

JSON - Iterate through JSONArray

JsonArray jsonArray;
Iterator<JsonElement> it = jsonArray.iterator();
while(it.hasNext()){
    System.out.println(it.next());
}

css3 text-shadow in IE9

The answer of crdunst is pretty neat and the best looking answer I've found but there's no explanation on how to use and the code is bigger than needed.

The only code you need:

#element {
    background-color: #cacbcf;
    text-shadow: 2px 2px 4px rgba(0,0,0, 0.5);
    filter: chroma(color=#cacbcf) progid:DXImageTransform.Microsoft.dropshadow(color=#60000000, offX=2, offY=2);
}

First you MUST specify a background-color - if your element should be transparent just copy the background-color of the parent or let it inherit. The color at the chroma-filter must match the background-color to fix those artifacts around the text (but here you must copy the color, you can't write inherit). Note that I haven't shortened the dropshadow-filter - it works but the shadows are then cut to the element dimensions (noticeable with big shadows; try to set the offsets to atleast 4).

TIP: If you want to use colors with transparency (alpha-channel) write in a #AARRGGBB notation, where AA stands for a hexadezimal value of the opacity - from 01 to FE, because FF and ironically also 00 means no transparency and is therefore useless.. ^^ Just go a little lower than in the rgba notation because the shadows aren't soft and the same alpha value would appear darker then. ;)

A nice snippet to convert the alpha value for IE (JavaScript, just paste into the console):

var number = 0.5; //alpha value from the rgba() notation
("0"+(Math.round(0.75 * number * 255).toString(16))).slice(-2);

ISSUES: The text/font behaves like an image after the shadow is applied; it gets pixelated and blurry after you zoom in... But that's IE's issue, not mine.

Live demo of the shadow here: http://jsfiddle.net/12khvfru/2/

Angular 2 filter/search list

You have to manually filter result based on change of input each time by keeping listener over input event. While doing manually filtering make sure you should maintain two copy of variable, one would be original collection copy & second would be filteredCollection copy. The advantage for going this way could save your couple of unnecessary filtering on change detection cycle. You may see a more code, but this would be more performance friendly.

Markup - HTML Template

<md-input #myInput placeholder="Item name..." [(ngModel)]="name" (input)="filterItem(myInput.value)"></md-input>

<div *ngFor="let item of filteredItems">
   {{item.name}}
</div>

Code

assignCopy(){
   this.filteredItems = Object.assign([], this.items);
}
filterItem(value){
   if(!value){
       this.assignCopy();
   } // when nothing has typed
   this.filteredItems = Object.assign([], this.items).filter(
      item => item.name.toLowerCase().indexOf(value.toLowerCase()) > -1
   )
}
this.assignCopy();//when you fetch collection from server.

Laravel: How to Get Current Route Name? (v5 ... v7)

In a controller action, you could just do:

public function someAction(Request $request)
{
    $routeName = $request->route()->getName();
}

$request here is resolved by Laravel's service container.

getName() returns the route name for named routes only, null otherwise (but you could still explore the \Illuminate\Routing\Route object for something else of interest).

In other words, you should have your route defined like this to have "nameOfMyRoute" returned:

Route::get('my/some-action', [
    'as' => 'nameOfMyRoute',
    'uses' => 'MyController@someAction'
]);

How to impose maxlength on textArea in HTML using JavaScript

Also add the following event to deal with pasting into the textarea:

...

txts[i].onkeyup = function() {
  ...
}

txts[i].paste = function() {
  var len = parseInt(this.getAttribute("maxlength"), 10);

  if (this.value.length + window.clipboardData.getData("Text").length > len) {
    alert('Maximum length exceeded: ' + len);
    this.value = this.value.substr(0, len);
    return false;
  }
}

...

How to convert Windows end of line in Unix end of line (CR/LF to LF)

Actually, vim does allow what you're looking for. Enter vim, and type the following commands:

:args **/*.java
:argdo set ff=unix | update | next

The first of these commands sets the argument list to every file matching **/*.java, which is all Java files, recursively. The second of these commands does the following to each file in the argument list, in turn:

  • Sets the line-endings to Unix style (you already know this)
  • Writes the file out iff it's been changed
  • Proceeds to the next file

Why use armeabi-v7a code over armeabi code?

EABI = Embedded Application Binary Interface. It is such specifications to which an executable must conform in order to execute in a specific execution environment. It also specifies various aspects of compilation and linkage required for interoperation between toolchains used for the ARM Architecture. In this context when we speak about armeabi we speak about ARM architecture and GNU/Linux OS. Android follows the little-endian ARM GNU/Linux ABI.

armeabi application will run on ARMv5 (e.g. ARM9) and ARMv6 (e.g. ARM11). You may use Floating Point hardware if you build your application using proper GCC options like -mfpu=vfpv3 -mfloat-abi=softfp which tells compiler to generate floating point instructions for VFP hardware and enables the soft-float calling conventions. armeabi doesn't support hard-float calling conventions (it means FP registers are not used to contain arguments for a function), but FP operations in HW are still supported.

armeabi-v7a application will run on Cortex A# devices like Cortex A8, A9, and A15. It supports multi-core processors and it supports -mfloat-abi=hard. So, if you build your application using -mfloat-abi=hard, many of your function calls will be faster.

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

Instead of hiding view, create the width constrain and change it to 0 in code when you want to hide the UIView.

It may be the simplest way to do so. Also, it will preserve the view and you don't need to recreate it if you want to show it again (ideal to use inside table cells). To change the constant value you need to create a constant reference outlet (the same way as you do outlets for the view).

How to open up a form from another form in VB.NET?

You could use:

Dim MyForm As New Form1
MyForm.Show()

or rather:

MyForm.ShowDialog()

to open the form as a dialog box to ensure that user interacts with the new form or closes it.

live output from subprocess command

Executive Summary (or "tl;dr" version): it's easy when there's at most one subprocess.PIPE, otherwise it's hard.

It may be time to explain a bit about how subprocess.Popen does its thing.

(Caveat: this is for Python 2.x, although 3.x is similar; and I'm quite fuzzy on the Windows variant. I understand the POSIX stuff much better.)

The Popen function needs to deal with zero-to-three I/O streams, somewhat simultaneously. These are denoted stdin, stdout, and stderr as usual.

You can provide:

  • None, indicating that you don't want to redirect the stream. It will inherit these as usual instead. Note that on POSIX systems, at least, this does not mean it will use Python's sys.stdout, just Python's actual stdout; see demo at end.
  • An int value. This is a "raw" file descriptor (in POSIX at least). (Side note: PIPE and STDOUT are actually ints internally, but are "impossible" descriptors, -1 and -2.)
  • A stream—really, any object with a fileno method. Popen will find the descriptor for that stream, using stream.fileno(), and then proceed as for an int value.
  • subprocess.PIPE, indicating that Python should create a pipe.
  • subprocess.STDOUT (for stderr only): tell Python to use the same descriptor as for stdout. This only makes sense if you provided a (non-None) value for stdout, and even then, it is only needed if you set stdout=subprocess.PIPE. (Otherwise you can just provide the same argument you provided for stdout, e.g., Popen(..., stdout=stream, stderr=stream).)

The easiest cases (no pipes)

If you redirect nothing (leave all three as the default None value or supply explicit None), Pipe has it quite easy. It just needs to spin off the subprocess and let it run. Or, if you redirect to a non-PIPE—an int or a stream's fileno()—it's still easy, as the OS does all the work. Python just needs to spin off the subprocess, connecting its stdin, stdout, and/or stderr to the provided file descriptors.

The still-easy case: one pipe

If you redirect only one stream, Pipe still has things pretty easy. Let's pick one stream at a time and watch.

Suppose you want to supply some stdin, but let stdout and stderr go un-redirected, or go to a file descriptor. As the parent process, your Python program simply needs to use write() to send data down the pipe. You can do this yourself, e.g.:

proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
proc.stdin.write('here, have some data\n') # etc

or you can pass the stdin data to proc.communicate(), which then does the stdin.write shown above. There is no output coming back so communicate() has only one other real job: it also closes the pipe for you. (If you don't call proc.communicate() you must call proc.stdin.close() to close the pipe, so that the subprocess knows there is no more data coming through.)

Suppose you want to capture stdout but leave stdin and stderr alone. Again, it's easy: just call proc.stdout.read() (or equivalent) until there is no more output. Since proc.stdout() is a normal Python I/O stream you can use all the normal constructs on it, like:

for line in proc.stdout:

or, again, you can use proc.communicate(), which simply does the read() for you.

If you want to capture only stderr, it works the same as with stdout.

There's one more trick before things get hard. Suppose you want to capture stdout, and also capture stderr but on the same pipe as stdout:

proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

In this case, subprocess "cheats"! Well, it has to do this, so it's not really cheating: it starts the subprocess with both its stdout and its stderr directed into the (single) pipe-descriptor that feeds back to its parent (Python) process. On the parent side, there's again only a single pipe-descriptor for reading the output. All the "stderr" output shows up in proc.stdout, and if you call proc.communicate(), the stderr result (second value in the tuple) will be None, not a string.

The hard cases: two or more pipes

The problems all come about when you want to use at least two pipes. In fact, the subprocess code itself has this bit:

def communicate(self, input=None):
    ...
    # Optimization: If we are only using one pipe, or no pipe at
    # all, using select() or threads is unnecessary.
    if [self.stdin, self.stdout, self.stderr].count(None) >= 2:

But, alas, here we've made at least two, and maybe three, different pipes, so the count(None) returns either 1 or 0. We must do things the hard way.

On Windows, this uses threading.Thread to accumulate results for self.stdout and self.stderr, and has the parent thread deliver self.stdin input data (and then close the pipe).

On POSIX, this uses poll if available, otherwise select, to accumulate output and deliver stdin input. All this runs in the (single) parent process/thread.

Threads or poll/select are needed here to avoid deadlock. Suppose, for instance, that we've redirected all three streams to three separate pipes. Suppose further that there's a small limit on how much data can be stuffed into to a pipe before the writing process is suspended, waiting for the reading process to "clean out" the pipe from the other end. Let's set that small limit to a single byte, just for illustration. (This is in fact how things work, except that the limit is much bigger than one byte.)

If the parent (Python) process tries to write several bytes—say, 'go\n'to proc.stdin, the first byte goes in and then the second causes the Python process to suspend, waiting for the subprocess to read the first byte, emptying the pipe.

Meanwhile, suppose the subprocess decides to print a friendly "Hello! Don't Panic!" greeting. The H goes into its stdout pipe, but the e causes it to suspend, waiting for its parent to read that H, emptying the stdout pipe.

Now we're stuck: the Python process is asleep, waiting to finish saying "go", and the subprocess is also asleep, waiting to finish saying "Hello! Don't Panic!".

The subprocess.Popen code avoids this problem with threading-or-select/poll. When bytes can go over the pipes, they go. When they can't, only a thread (not the whole process) has to sleep—or, in the case of select/poll, the Python process waits simultaneously for "can write" or "data available", writes to the process's stdin only when there is room, and reads its stdout and/or stderr only when data are ready. The proc.communicate() code (actually _communicate where the hairy cases are handled) returns once all stdin data (if any) have been sent and all stdout and/or stderr data have been accumulated.

If you want to read both stdout and stderr on two different pipes (regardless of any stdin redirection), you will need to avoid deadlock too. The deadlock scenario here is different—it occurs when the subprocess writes something long to stderr while you're pulling data from stdout, or vice versa—but it's still there.


The Demo

I promised to demonstrate that, un-redirected, Python subprocesses write to the underlying stdout, not sys.stdout. So, here is some code:

from cStringIO import StringIO
import os
import subprocess
import sys

def show1():
    print 'start show1'
    save = sys.stdout
    sys.stdout = StringIO()
    print 'sys.stdout being buffered'
    proc = subprocess.Popen(['echo', 'hello'])
    proc.wait()
    in_stdout = sys.stdout.getvalue()
    sys.stdout = save
    print 'in buffer:', in_stdout

def show2():
    print 'start show2'
    save = sys.stdout
    sys.stdout = open(os.devnull, 'w')
    print 'after redirect sys.stdout'
    proc = subprocess.Popen(['echo', 'hello'])
    proc.wait()
    sys.stdout = save

show1()
show2()

When run:

$ python out.py
start show1
hello
in buffer: sys.stdout being buffered

start show2
hello

Note that the first routine will fail if you add stdout=sys.stdout, as a StringIO object has no fileno. The second will omit the hello if you add stdout=sys.stdout since sys.stdout has been redirected to os.devnull.

(If you redirect Python's file-descriptor-1, the subprocess will follow that redirection. The open(os.devnull, 'w') call produces a stream whose fileno() is greater than 2.)

jQuery ui datepicker with Angularjs

You main Index.html file for Angular can use the body tag as the ng-view. Then all you need to do is include a script tag at the bottom of whatever page is being pulled into Index.html by Angular like so:

<script type="text/javascript">
$( function() {
    $( "#mydatepickerid" ).datepicker({changeMonth: true, changeYear: true, 
        yearRange: '1930:'+new Date().getFullYear(), dateFormat: "yy-mm-dd"});
});
</script>

Why overcomplicate things??

system("pause"); - Why is it wrong?

In summary, it has to pause the programs execution and make a system call and allocate unnecessary resources when you could be using something as simple as cin.get(). People use System("PAUSE") because they want the program to wait until they hit enter to they can see their output. If you want a program to wait for input, there are built in functions for that which are also cross platform and less demanding.

Further explanation in this article.

Protractor : How to wait for page complete after click a button?

In this case, you can used:

Page Object:

    waitForURLContain(urlExpected: string, timeout: number) {
        try {
            const condition = browser.ExpectedConditions;
            browser.wait(condition.urlContains(urlExpected), timeout);
        } catch (e) {
            console.error('URL not contain text.', e);
        };
    }

Page Test:

page.waitForURLContain('abc#/efg', 30000);

numpy: most efficient frequency counts for unique values in an array

Even though it has already been answered, I suggest a different approach that makes use of numpy.histogram. Such function given a sequence it returns the frequency of its elements grouped in bins.

Beware though: it works in this example because numbers are integers. If they where real numbers, then this solution would not apply as nicely.

>>> from numpy import histogram
>>> y = histogram (x, bins=x.max()-1)
>>> y
(array([5, 3, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       1]),
 array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,
        12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,  22.,
        23.,  24.,  25.]))

Compare objects in Angular

To compare two objects you can use:

angular.equals(obj1, obj2)

It does a deep comparison and does not depend on the order of the keys See AngularJS DOCS and a little Demo

var obj1 = {
  key1: "value1",
  key2: "value2",
  key3: {a: "aa", b: "bb"}
}

var obj2 = {
  key2: "value2",
  key1: "value1",
  key3: {a: "aa", b: "bb"}
}

angular.equals(obj1, obj2) //<--- would return true

Does not contain a definition for and no extension method accepting a first argument of type could be found

placeBets(betList, stakeAmt) is an instance method not a static method. You need to create an instance of CBetfairAPI first:

MyBetfair api = new MyBetfair();
ArrayList bets = api.placeBets(betList, stakeAmt);

How to invoke function from external .c file in C?

you shouldn't include c-files in other c-files. Instead create a header file where the function is declared that you want to call. Like so: file ClasseAusiliaria.h:

int addizione(int a, int b); // this tells the compiler that there is a function defined and the linker will sort the right adress to call out.

In your Main.c file you can then include the newly created header file:

#include <stdlib.h>
#include <stdio.h>
#include <ClasseAusiliaria.h>

int main(void)
{
    int risultato;
    risultato = addizione(5,6);
    printf("%d\n",risultato);
}

handling DATETIME values 0000-00-00 00:00:00 in JDBC

I wrestled with this problem and implemented the 'convertToNull' solutions discussed above. It worked in my local MySql instance. But when I deployed my Play/Scala app to Heroku it no longer would work. Heroku also concatenates several args to the DB URL that they provide users, and this solution, because of Heroku's use concatenation of "?" before their own set of args, will not work. However I found a different solution which seems to work equally well.

SET sql_mode = 'NO_ZERO_DATE';

I put this in my table descriptions and it solved the problem of '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp

SQL Server SELECT LAST N Rows

This may not be quite the right fit to the question, but…

OFFSET clause

The OFFSET number clause enables you to skip over a number of rows and then return rows after that.

That doc link is to Postgres; I don't know if this applies to Sybase/MS SQL Server.

Display Parameter(Multi-value) in Report

You can use the "Join" function to create a single string out of the array of labels, like this:

=Join(Parameters!Product.Label, ",")

How do I get the collection of Model State Errors in ASP.NET MVC?

Here is the VB.

Dim validationErrors As String = String.Join(",", ModelState.Values.Where(Function(E) E.Errors.Count > 0).SelectMany(Function(E) E.Errors).[Select](Function(E) E.ErrorMessage).ToArray())

Convert a row of a data frame to vector

Columns of data frames are already vectors, you just have to pull them out. Note that you place the column you want after the comma, not before it:

> newV <- df[,1]
> newV
[1] 1 2 4 2

If you actually want a row, then do what Ben said and please use words correctly in the future.

Changing text color onclick

Do something like this:

<script>
function changeColor(id)
{
  document.getElementById(id).style.color = "#ff0000"; // forecolor
  document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
}
</script>

<div id="myid">Hello There !!</div>

<a href="#" onclick="changeColor('myid'); return false;">Change Color</a>

Custom Date/Time formatting in SQL Server

Not answering your question specifically, but isn't that something that should be handled by the presentation layer of your application. Doing it the way you describe creates extra processing on the database end as well as adding extra network traffic (assuming the database exists on a different machine than the application), for something that could be easily computed on the application side, with more rich date processing libraries, as well as being more language agnostic, especially in the case of your first example which contains the abbreviated month name. Anyway the answers others give you should point you in the right direction if you still decide to go this route.

How to copy data to clipboard in C#

There are two classes that lives in different assemblies and different namespaces.

  • WinForms: use following namespace declaration, make sure Main is marked with [STAThread] attribute:

    using System.Windows.Forms;
    
  • WPF: use following namespace declaration

    using System.Windows;
    
  • console: add reference to System.Windows.Forms, use following namespace declaration, make sure Main is marked with [STAThread] attribute. Step-by-step guide in another answer

    using System.Windows.Forms;
    

To copy an exact string (literal in this case):

Clipboard.SetText("Hello, clipboard");

To copy the contents of a textbox either use TextBox.Copy() or get text first and then set clipboard value:

Clipboard.SetText(txtClipboard.Text);

See here for an example. Or... Official MSDN documentation or Here for WPF.


Remarks:

how to parse xml to java object?

JAXB is an ideal solution. But you do not necessarily need xsd and xjc for that. More often than not you don't have an xsd but you know what your xml is. Simply analyze your xml, e.g.,

<customer id="100">
    <age>29</age>
    <name>mkyong</name>
</customer>

Create necessary model class(es):

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}

Try to unmarshal:

JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(new File("C:\\file.xml"));

Check results, fix bugs!

Create SQLite database in android

Better example is here

 try {
   myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);

   /* Create a Table in the Database. */
   myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");

   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Saranga', 22);");

   /*retrieve data from database */
   Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);

   int Column1 = c.getColumnIndex("Field1");
   int Column2 = c.getColumnIndex("Field2");

   // Check if our result was valid.
   c.moveToFirst();
   if (c != null) {
    // Loop through all Results
    do {
     String Name = c.getString(Column1);
     int Age = c.getInt(Column2);
     Data =Data +Name+"/"+Age+"\n";
    }while(c.moveToNext());
   }

How to rotate x-axis tick labels in Pandas barplot

For bar graphs, you can include the angle which you finally want the ticks to have.

Here I am using rot=0 to make them parallel to the x axis.

series.plot.bar(rot=0)
plt.show()
plt.close()

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

I'd try to declare i outside of the loop!

Good luck on solving 3n+1 :-)

Here's an example:

#include <stdio.h>

int main() {

   int i;

   /* for loop execution */
   for (i = 10; i < 20; i++) {
       printf("i: %d\n", i);
   }   

   return 0;
}

Read more on for loops in C here.

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

I had a very similar problem where for the form action, I had something like:

<form action="http://www.example.com/?q=content/something" method="GET">
   <input type="submit" value="Go away..." />&nbsp;
</form>

The button would get the user to the site, but the query info disappeared so the user landed on the home page rather than the desired content page. The solution in my case was to find out how to code the URL without the query that would get the user to the desired page. In this case my target was a Drupal site, so as it turned out /content/something also worked. I also could have used a node number (i.e. /node/123).

Send request to curl with post data sourced from a file

You're looking for the --data-binary argument:

curl -i -X POST host:port/post-file \
  -H "Content-Type: text/xml" \
  --data-binary "@path/to/file"

In the example above, -i prints out all the headers so that you can see what's going on, and -X POST makes it explicit that this is a post. Both of these can be safely omitted without changing the behaviour on the wire. The path to the file needs to be preceded by an @ symbol, so curl knows to read from a file.

Ajax success function

It is because Ajax is asynchronous, the success or the error function will be called later, when the server answer the client. So, just move parts depending on the result into your success function like that :

jQuery.ajax({

            type:"post",
            dataType:"json",
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                successmessage = 'Data was succesfully captured';
                $("label#successmessage").text(successmessage);
            },
            error: function(data) {
                successmessage = 'Error';
                $("label#successmessage").text(successmessage);
            },
        });

        $(":input").val('');
        return false;

Recreate the default website in IIS

I suppose you want to publish and access your applications/websites from LAN; probably as virtual directories under the default website.The steps could vary depending on your IIS version, but basically it comes down to these steps:

Restore your "Default Website" Website :

  1. create a new website

  2. set "Default Website" as its name

  3. In the Binding section (bottom panel), enter your local IP address in the "IP Address" edit.

  4. Keep the "Host" edit empty

that's it: now whenever you type your local ip address in your browser, you will get the website you just added. Now if you want to access any of your other webapplications/websites from LAN, just add a virtual application under your default website pointing to the directory containing your published application/website. Now you can type : http://yourLocalIPAddress/theNameOfYourApplication to access it from your LAN.

Differences between contentType and dataType in jQuery ajax function

enter image description here

In English:

  • ContentType: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8, which is fine for most cases.
  • Accepts: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType.
  • DataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp.

What is function overloading and overriding in php?

Strictly speaking, there's no difference, since you cannot do either :)

Function overriding could have been done with a PHP extension like APD, but it's deprecated and afaik last version was unusable.

Function overloading in PHP cannot be done due to dynamic typing, ie, in PHP you don't "define" variables to be a particular type. Example:

$a=1;
$a='1';
$a=true;
$a=doSomething();

Each variable is of a different type, yet you can know the type before execution (see the 4th one). As a comparison, other languages use:

int a=1;
String s="1";
bool a=true;
something a=doSomething();

In the last example, you must forcefully set the variable's type (as an example, I used data type "something").


Another "issue" why function overloading is not possible in PHP: PHP has a function called func_get_args(), which returns an array of current arguments, now consider the following code:

function hello($a){
  print_r(func_get_args());
}

function hello($a,$a){
  print_r(func_get_args());
}

hello('a');
hello('a','b');

Considering both functions accept any amount of arguments, which one should the compiler choose?


Finally, I'd like to point out why the above replies are partially wrong; function overloading/overriding is NOT equal to method overloading/overriding.

Where a method is like a function but specific to a class, in which case, PHP does allow overriding in classes, but again no overloading, due to language semantics.

To conclude, languages like Javascript allow overriding (but again, no overloading), however they may also show the difference between overriding a user function and a method:

/// Function Overriding ///

function a(){
   alert('a');
}
a=function(){
   alert('b');
}

a(); // shows popup with 'b'


/// Method Overriding ///

var a={
  "a":function(){
    alert('a');
  }
}
a.a=function(){
   alert('b');
}

a.a(); // shows popup with 'b'

When would you use the different git merge strategies?

I'm not familiar with resolve, but I've used the others:

Recursive

Recursive is the default for non-fast-forward merges. We're all familiar with that one.

Octopus

I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.

An octopus branch merges multiple heads in one commit as long as it can do it cleanly.

For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).

A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):

series of recursive merges

However, a single octopus merge would look like this:

commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...

octopus merge

Ours

Ours == I want to pull in another head, but throw away all of the changes that head introduces.

This keeps the history of a branch without any of the effects of the branch.

(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use git merge -X ours)

Subtree

Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.

How to check size of a file using Bash?

This works in both linux and macos

function filesize
{
    local file=$1
    size=`stat -c%s $file 2>/dev/null` # linux
    if [ $? -eq 0 ]
    then
        echo $size
        return 0
    fi

    eval $(stat -s $file) # macos
    if [ $? -eq 0 ]
    then
        echo $st_size
        return 0
    fi

    return -1
}

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

Swift 4

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let delete = UIContextualAction(style: .destructive, title: "Delete") { (action, sourceView, completionHandler) in
        print("index path of delete: \(indexPath)")
        completionHandler(true)
    }
    let rename = UIContextualAction(style: .normal, title: "Edit") { (action, sourceView, completionHandler) in
        print("index path of edit: \(indexPath)")
        completionHandler(true)
    }
    let swipeActionConfig = UISwipeActionsConfiguration(actions: [rename, delete])
    swipeActionConfig.performsFirstActionWithFullSwipe = false
    return swipeActionConfig
}

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

How to display raw html code in PRE or something like it but without escaping it

xmp is the way to go, i.e.:

<xmp>
  # your code...
</xmp>

AngularJS - Trigger when radio button is selected

Another approach is using Object.defineProperty to set valueas a getter setter property in the controller scope, then each change on the value property will trigger a function specified in the setter:

The HTML file:

<input type="radio" ng-model="value" value="one"/>
<input type="radio" ng-model="value" value="two"/>
<input type="radio" ng-model="value" value="three"/>

The javascript file:

var _value = null;
Object.defineProperty($scope, 'value', {
  get: function () {
    return _value;
  },         
  set: function (value) {
    _value = value;
    someFunction();
  }
});

see this plunker for the implementation

Setting session variable using javascript

It is very important to understand both sessionStorage and localStorage as they both have different uses:

From MDN:

All of your web storage data is contained within two object-like structures inside the browser: sessionStorage and localStorage. The first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opened again.

sessionStorage - Saves data until the browser is closed, the data is deleted when the tab/browser is closed.

localStorage - Saves data "forever" even after the browser is closed BUT you shouldn't count on the data you store to be there later, the data might get deleted by the browser at any time because of pretty much anything, or deleted by the user, best practice would be to validate that the data is there first, and continue the rest if it is there. (or set it up again if its not there)

To understand more, read here: localStorage | sessionStorage

How to provide user name and password when connecting to a network share

Also ported to F# to use with FAKE

module NetworkShare

open System
open System.ComponentModel
open System.IO
open System.Net
open System.Runtime.InteropServices

type ResourceScope =
| Connected = 1
| GlobalNetwork = 2
| Remembered = 3
| Recent = 4
type ResourceType =
| Any = 0
| Disk = 1
| Print = 2
| Reserved = 8
type ResourceDisplayType =
| Generic = 0x0
| Domain = 0x01
| Server = 0x02
| Share = 0x03
| File = 0x04
| Group = 0x05
| Network = 0x06
| Root = 0x07
| Shareadmin = 0x08
| Directory = 0x09
| Tree = 0x0a
| Ndscontainer = 0x0b

//Uses of this construct may result in the generation of unverifiable .NET IL code.
#nowarn "9"
[<StructLayout(LayoutKind.Sequential)>]
type NetResource =
  struct
    val mutable Scope : ResourceScope
    val mutable ResourceType : ResourceType
    val mutable DisplayType : ResourceDisplayType
    val mutable Usage : int
    val mutable LocalName : string
    val mutable RemoteName : string
    val mutable Comment : string
    val mutable Provider : string
    new(name) = {
      // lets preset needed fields
      NetResource.Scope = ResourceScope.GlobalNetwork
      ResourceType = ResourceType.Disk
      DisplayType = ResourceDisplayType.Share
      Usage = 0
      LocalName = null
      RemoteName = name
      Comment = null
      Provider = null
    }
  end

type WNetConnection(networkName : string, credential : NetworkCredential) =
  [<Literal>]
  static let Mpr = "mpr.dll"
  [<DllImport(Mpr, EntryPoint = "WNetAddConnection2")>]
  static extern int connect(NetResource netResource, string password, string username, int flags)
  [<DllImport(Mpr, EntryPoint = "WNetCancelConnection2")>]
  static extern int disconnect(string name, int flags, bool force)

  let mutable disposed = false;

  do
    let userName = if String.IsNullOrWhiteSpace credential.Domain
                   then credential.UserName
                   else credential.Domain + "\\" + credential.UserName
    let resource = new NetResource(networkName)

    let result = connect(resource, credential.Password, userName, 0)

    if result <> 0 then
      let msg = "Error connecting to remote share " + networkName
      new Win32Exception(result, msg)
      |> raise

  let cleanup(disposing:bool) =
    if not disposed then
      disposed <- true
      if disposing then () // TODO dispose managed resources here
      disconnect(networkName, 0, true) |> ignore

  interface IDisposable with
    member __.Dispose() =
      disconnect(networkName, 0, true) |> ignore
      GC.SuppressFinalize(__)

  override __.Finalize() = cleanup(false)

type CopyPath =
  | RemotePath of string * NetworkCredential
  | LocalPath of string

let createDisposable() =
  {
    new IDisposable with
      member __.Dispose() = ()
  }

let copyFile overwrite destPath srcPath : unit =
  use _srcConn =
    match srcPath with
    | RemotePath(path, credential) -> new WNetConnection(path, credential) :> IDisposable
    | LocalPath(_) -> createDisposable()
  use _destConn =
    match destPath with
    | RemotePath(path, credential) -> new WNetConnection(path, credential) :> IDisposable
    | LocalPath(_) -> createDisposable()
  match srcPath, destPath with
  | RemotePath(src, _), RemotePath(dest, _)
  | LocalPath(src), RemotePath(dest, _)
  | RemotePath(src, _), LocalPath(dest)
  | LocalPath(src), LocalPath(dest) ->
    if FileInfo(src).Exists |> not then
      failwith ("Source file not found: " + src)
    let destFilePath =
      if DirectoryInfo(dest).Exists then Path.Combine(dest, Path.GetFileName src)
      else dest
    File.Copy(src, destFilePath, overwrite)

let rec copyDir copySubDirs filePattern destPath srcPath =
  use _srcConn =
    match srcPath with
    | RemotePath(path, credential) -> new WNetConnection(path, credential) :> IDisposable
    | LocalPath(_) -> createDisposable()
  use _destConn =
    match destPath with
    | RemotePath(path, credential) -> new WNetConnection(path, credential) :> IDisposable
    | LocalPath(_) -> createDisposable()
  match srcPath, destPath with
  | RemotePath(src, _), RemotePath(dest, _)
  | LocalPath(src), RemotePath(dest, _)
  | RemotePath(src, _), LocalPath(dest)
  | LocalPath(src), LocalPath(dest) ->
    let dir = DirectoryInfo(src)
    if dir.Exists |> not then
      failwith ("Source directory not found: " + src)

    let dirs = dir.GetDirectories()
    if Directory.Exists(dest) |> not then
      Directory.CreateDirectory(dest) |> ignore

    let files = dir.GetFiles(filePattern)
    for file in files do
      let tempPath = Path.Combine(dest, file.Name)
      file.CopyTo(tempPath, false) |> ignore

    if copySubDirs then
      for subdir in dirs do
        let subdirSrc =
          match srcPath with
          | RemotePath(_, credential) -> RemotePath(Path.Combine(dest, subdir.Name), credential)
          | LocalPath(_) -> LocalPath(Path.Combine(dest, subdir.Name))
        let subdirDest =
          match destPath with
          | RemotePath(_, credential) -> RemotePath(subdir.FullName, credential)
          | LocalPath(_) -> LocalPath(subdir.FullName)
        copyDir copySubDirs filePattern subdirDest subdirSrc

How do I declare a two dimensional array?

Or for larger arrays, all with the same value:

$m_by_n_array = array_fill(0, $n, array_fill(0, $m, $value);

will create an $m by $n array with everything set to $value.

tap gesture recognizer - which object was tapped?

Its been a year asking this question but still for someone.

While declaring the UITapGestureRecognizer on a particular view assign the tag as

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureHandlerMethod:)];
[yourGestureEnableView addGestureRecognizer:tapRecognizer];
yourGestureEnableView.tag=2;

and in your handler do like this

-(void)gestureHandlerMethod:(UITapGestureRecognizer*)sender {
    if(sender.view.tag == 2) {
        // do something here
    }
}

Difference between PCDATA and CDATA in DTD

  • PCDATA is text that will be parsed by a parser. Tags inside the text will be treated as markup and entities will be expanded.
  • CDATA is text that will not be parsed by a parser. Tags inside the text will not be treated as markup and entities will not be expanded.

By default, everything is PCDATA. In the following example, ignoring the root, <bar> will be parsed, and it'll have no content, but one child.

<?xml version="1.0"?>
<foo>
<bar><test>content!</test></bar>
</foo>

When we want to specify that an element will only contain text, and no child elements, we use the keyword PCDATA, because this keyword specifies that the element must contain parsable character data – that is , any text except the characters less-than (<) , greater-than (>) , ampersand (&), quote(') and double quote (").

In the next example, <bar> contains CDATA. Its content will not be parsed and is thus <test>content!</test>.

<?xml version="1.0"?>
<foo>
<bar><![CDATA[<test>content!</test>]]></bar>
</foo>

There are several content models in SGML. The #PCDATA content model says that an element may contain plain text. The "parsed" part of it means that markup (including PIs, comments and SGML directives) in it is parsed instead of displayed as raw text. It also means that entity references are replaced.

Another type of content model allowing plain text contents is CDATA. In XML, the element content model may not implicitly be set to CDATA, but in SGML, it means that markup and entity references are ignored in the contents of the element. In attributes of CDATA type however, entity references are replaced.

In XML, #PCDATA is the only plain text content model. You use it if you at all want to allow text contents in the element. The CDATA content model may be used explicitly through the CDATA block markup in #PCDATA, but element contents may not be defined as CDATA per default.

In a DTD, the type of an attribute that contains text must be CDATA. The CDATA keyword in an attribute declaration has a different meaning than the CDATA section in an XML document. In a CDATA section all characters are legal (including <,>,&,' and " characters), except the ]]> end tag.

#PCDATA is not appropriate for the type of an attribute. It is used for the type of "leaf" text.

#PCDATA is prepended by a hash in the content model to distinguish this keyword from an element named PCDATA (which would be perfectly legal).

How can I check if character in a string is a letter? (Python)

I found a good way to do this with using a function and basic code. This is a code that accepts a string and counts the number of capital letters, lowercase letters and also 'other'. Other is classed as a space, punctuation mark or even Japanese and Chinese characters.

def check(count):

    lowercase = 0
    uppercase = 0
    other = 0

    low = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
    upper = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'



    for n in count:
        if n in low:
            lowercase += 1
        elif n in upper:
            uppercase += 1
        else:
            other += 1

    print("There are " + str(lowercase) + " lowercase letters.")
    print("There are " + str(uppercase) + " uppercase letters.")
    print("There are " + str(other) + " other elements to this sentence.")

Calculating percentile of dataset column

You can also use the hmisc package that will give you the following percentiles:

0.05, 0.1, 0.25, 0.5, 0.75, 0.9 , 0.95

Just use the describe(table_ages)

Get current scroll position of ScrollView in React Native

Disclaimer: what follows is primarily the result of my own experimentation in React Native 0.50. The ScrollView documentation is currently missing a lot of the information covered below; for instance onScrollEndDrag is completely undocumented. Since everything here relies upon undocumented behaviour, I can unfortunately make no promises that this information will remain correct a year or even a month from now.

Also, everything below assumes a purely vertical scrollview whose y offset we are interested in; translating to x offsets, if needed, is hopefully an easy exercise for the reader.


Various event handlers on a ScrollView take an event and let you get the current scroll position via event.nativeEvent.contentOffset.y. Some of these handlers have slightly different behaviour between Android and iOS, as detailed below.

onScroll

On Android

Fires every frame while the user is scrolling, on every frame while the scroll view is gliding after the user releases it, on the final frame when the scroll view comes to rest, and also whenever the scroll view's offset changes as a result of its frame changing (e.g. due to rotation from landscape to portrait).

On iOS

Fires while the user is dragging or while the scroll view is gliding, at some frequency determined by scrollEventThrottle and at most once per frame when scrollEventThrottle={16}. If the user releases the scroll view while it has enough momentum to glide, the onScroll handler will also fire when it comes to rest after gliding. However, if the user drags and then releases the scroll view while it is stationary, onScroll is not guaranteed to fire for the final position unless scrollEventThrottle has been set such that onScroll fires every frame of scrolling.

There is a performance cost to setting scrollEventThrottle={16} that can be reduced by setting it to a larger number. However, this means that onScroll will not fire every frame.

onMomentumScrollEnd

Fires when the scroll view comes to a stop after gliding. Does not fire at all if the user releases the scroll view while it is stationary such that it does not glide.

onScrollEndDrag

Fires when the user stops dragging the scroll view - regardless of whether the scroll view is left stationary or begins to glide.


Given these differences in behaviour, the best way to keep track of the offset depends upon your precise circumstances. In the most complicated case (you need to support Android and iOS, including handling changes in the ScrollView's frame due to rotation, and you don't want to accept the performance penalty on Android from setting scrollEventThrottle to 16), and you need to handle changes to the content in the scroll view too, then it's a right damn mess.

The simplest case is if you only need to handle Android; just use onScroll:

<ScrollView
  onScroll={event => { 
    this.yOffset = event.nativeEvent.contentOffset.y
  }}
>

To additionally support iOS, if you're happy to fire the onScroll handler every frame and accept the performance implications of that, and if you don't need to handle frame changes, then it's only a little bit more complicated:

<ScrollView
  onScroll={event => { 
    this.yOffset = event.nativeEvent.contentOffset.y
  }}
  scrollEventThrottle={16}
>

To reduce the performance overhead on iOS while still guaranteeing that we record any position that the scroll view settles on, we can increase scrollEventThrottle and additionally provide an onScrollEndDrag handler:

<ScrollView
  onScroll={event => { 
    this.yOffset = event.nativeEvent.contentOffset.y
  }}
  onScrollEndDrag={event => { 
    this.yOffset = event.nativeEvent.contentOffset.y
  }}
  scrollEventThrottle={160}
>

But if we want to handle frame changes (e.g. because we allow the device to be rotated, changing the available height for the scroll view's frame) and/or content changes, then we must additionally implement both onContentSizeChange and onLayout to keep track of the height of both the scroll view's frame and its contents, and thereby continually calculate the maximum possible offset and infer when the offset has been automatically reduced due to a frame or content size change:

<ScrollView
  onLayout={event => {
    this.frameHeight = event.nativeEvent.layout.height;
    const maxOffset = this.contentHeight - this.frameHeight;
    if (maxOffset < this.yOffset) {
      this.yOffset = maxOffset;
    }
  }}
  onContentSizeChange={(contentWidth, contentHeight) => {
    this.contentHeight = contentHeight;
    const maxOffset = this.contentHeight - this.frameHeight;
    if (maxOffset < this.yOffset) {
      this.yOffset = maxOffset;
    }
  }}
  onScroll={event => { 
    this.yOffset = event.nativeEvent.contentOffset.y;
  }}
  onScrollEndDrag={event => { 
    this.yOffset = event.nativeEvent.contentOffset.y;
  }}
  scrollEventThrottle={160}
>

Yeah, it's pretty horrifying. I'm also not 100% certain that it'll always work right in cases where you simultaneously change the size of both the frame and content of the scroll view. But it's the best I can come up with, and until this feature gets added within the framework itself, I think this is the best that anyone can do.

Working with a List of Lists in Java

Something like this would work for reading:

String filename = "something.csv";
BufferedReader input = null;
List<List<String>> csvData = new ArrayList<List<String>>();
try 
{
    input =  new BufferedReader(new FileReader(filename));
    String line = null;
    while (( line = input.readLine()) != null)
    {
        String[] data = line.split(",");
        csvData.add(Arrays.toList(data));
    }
}
catch (Exception ex)
{
      ex.printStackTrace();
}
finally 
{
    if(input != null)
    {
        input.close();
    }
}

Swift Beta performance: sorting arrays

Swift Array performance revisited:

I wrote my own benchmark comparing Swift with C/Objective-C. My benchmark calculates prime numbers. It uses the array of previous prime numbers to look for prime factors in each new candidate, so it is quite fast. However, it does TONS of array reading, and less writing to arrays.

I originally did this benchmark against Swift 1.2. I decided to update the project and run it against Swift 2.0.

The project lets you select between using normal swift arrays and using Swift unsafe memory buffers using array semantics.

For C/Objective-C, you can either opt to use NSArrays, or C malloc'ed arrays.

The test results seem to be pretty similar with fastest, smallest code optimization ([-0s]) or fastest, aggressive ([-0fast]) optimization.

Swift 2.0 performance is still horrible with code optimization turned off, whereas C/Objective-C performance is only moderately slower.

The bottom line is that C malloc'd array-based calculations are the fastest, by a modest margin

Swift with unsafe buffers takes around 1.19X - 1.20X longer than C malloc'd arrays when using fastest, smallest code optimization. the difference seems slightly less with fast, aggressive optimization (Swift takes more like 1.18x to 1.16x longer than C.

If you use regular Swift arrays, the difference with C is slightly greater. (Swift takes ~1.22 to 1.23 longer.)

Regular Swift arrays are DRAMATICALLY faster than they were in Swift 1.2/Xcode 6. Their performance is so close to Swift unsafe buffer based arrays that using unsafe memory buffers does not really seem worth the trouble any more, which is big.

BTW, Objective-C NSArray performance stinks. If you're going to use the native container objects in both languages, Swift is DRAMATICALLY faster.

You can check out my project on github at SwiftPerformanceBenchmark

It has a simple UI that makes collecting stats pretty easy.

It's interesting that sorting seems to be slightly faster in Swift than in C now, but that this prime number algorithm is still faster in Swift.

How can I set a cookie in react?

Use vanilla js, example

document.cookie = `referral_key=hello;max-age=604800;domain=example.com`

Read more at: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

How to quickly drop a user with existing privileges

I faced the same problem and now found a way to solve it. First you have to delete the database of the user that you wish to drop. Then the user can be easily deleted.

I created an user named "msf" and struggled a while to delete the user and recreate it. I followed the below steps and Got succeeded.

1) Drop the database

dropdb msf

2) drop the user

dropuser msf

Now I got the user successfully dropped.

set serveroutput on in oracle procedure

If you want to execute any procedure then firstly you have to set serveroutput on in the sqldeveloper work environment like.

->  SET SERVEROUTPUT ON;
-> BEGIN
dbms_output.put_line ('Hello World..');
dbms_output.put_line('Its displaying the values only for the Testing purpose');
END;
/

How can I build a recursive function in python?

Let's say you want to build: u(n+1)=f(u(n)) with u(0)=u0

One solution is to define a simple recursive function:

u0 = ...

def f(x):
  ...

def u(n):
  if n==0: return u0
  return f(u(n-1))

Unfortunately, if you want to calculate high values of u, you will run into a stack overflow error.

Another solution is a simple loop:

def u(n):
  ux = u0
  for i in xrange(n):
    ux=f(ux)
  return ux

But if you want multiple values of u for different values of n, this is suboptimal. You could cache all values in an array, but you may run into an out of memory error. You may want to use generators instead:

def u(n):
  ux = u0
  for i in xrange(n):
    ux=f(ux)
  yield ux

for val in u(1000):
  print val

There are many other options, but I guess these are the main ones.

maximum value of int

What about (1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2)). This is the same as 2^(8*sizeof(int)-2) - 1 + 2^(8*sizeof(int)-2).

If sizeof(int) = 4 => 2^(8*4-2) - 1 + 2^(8*4-2) = 2^30 - 1 + 20^30 = (2^32)/2 - 1 [max signed int of 4 bytes].

You can't use 2*(1 << (8*sizeof(int)-2)) - 1 because it will overflow, but (1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2)) works.

Calculating the distance between 2 points

Here is my 2 cents:

double dX = x1 - x2;
double dY = y1 - y2;
double multi = dX * dX + dY * dY;
double rad = Math.Round(Math.Sqrt(multi), 3, MidpointRounding.AwayFromZero);

x1, y1 is the first coordinate and x2, y2 the second. The last line is the square root with it rounded to 3 decimal places.

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

Add a helper class:

public static class Redirector {
        public static void RedirectTo(this Controller ct, string action) {
            UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);

            ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action));
        }

        public static void RedirectTo(this Controller ct, string action, string controller) {
            UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);

            ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller));
        }

        public static void RedirectTo(this Controller ct, string action, string controller, object routeValues) {
            UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);

            ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller, routeValues));
        }
    }

Then call in your action:

this.RedirectTo("Index", "Cement");

Add javascript code to any global javascript included file or layout file to intercept all ajax requests:

_x000D_
_x000D_
<script type="text/javascript">_x000D_
  $(function() {_x000D_
    $(document).ajaxComplete(function (event, xhr, settings) {_x000D_
            var urlHeader = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
_x000D_
            if (urlHeader != null && urlHeader !== undefined) {_x000D_
                window.location = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
            }_x000D_
        });_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

Use of Application.DoEvents()

From my experience I would advise great caution with using DoEvents in .NET. I experienced some very strange results when using DoEvents in a TabControl containing DataGridViews. On the other hand, if all you're dealing with is a small form with a progress bar then it might be OK.

The bottom line is: if you are going to use DoEvents, then you need to test it thoroughly before deploying your application.

How to convert ISO8859-15 to UTF8?

We have this problem and to solve

Create a script file called to-utf8.sh

#!/bin/bash
TO="UTF-8"; FILE=$1
FROM=$(file -i $FILE | cut -d'=' -f2)
if [[ $FROM = "binary" ]]; then
 echo "Skipping binary $FILE..."
 exit 0
fi
iconv -f $FROM -t $TO -o $FILE.tmp $FILE; ERROR=$?
if [[ $ERROR -eq 0 ]]; then
  echo "Converting $FILE..."
  mv -f $FILE.tmp $FILE
else
  echo "Error on $FILE"
fi

Set the executable bit

chmod +x to-utf8.sh

Do a conversion

./to-utf8.sh MyFile.txt

If you want to convert all files under a folder, do

find /your/folder/here | xargs -n 1 ./to-utf8.sh

Hope it's help.

How To Create Table with Identity Column

CREATE TABLE [dbo].[History](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RequestID] [int] NOT NULL,
    [EmployeeID] [varchar](50) NOT NULL,
    [DateStamp] [datetime] NOT NULL,
 CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)
) ON [PRIMARY]

How to save user input into a variable in html and js

It doesn't work because name is a reserved word in JavaScript. Change the function name to something else.

See http://www.quackit.com/javascript/javascript_reserved_words.cfm

<form id="form" onsubmit="return false;">
    <input style="position:absolute; top:80%; left:5%; width:40%;" type="text" id="userInput" />
    <input style="position:absolute; top:50%; left:5%; width:40%;" type="submit" onclick="othername();" />
</form>

function othername() {
    var input = document.getElementById("userInput").value;
    alert(input);
}

Querying Datatable with where condition

something like this ? :

DataTable dt = ...
DataView dv = new DataView(dt);
dv.RowFilter = "(EmpName != 'abc' or EmpName != 'xyz') and (EmpID = 5)"

Is it what you are searching for?

How do I convert a single character into it's hex ascii value in python

To use the hex encoding in Python 3, use

>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'

In legacy Python, there are several other ways of doing this:

>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

I would do it this this way:

  1. Stage all unstaged changes.

    git add .
    
  2. Stash the changes.

    git stash save
    
  3. Sync with remote.

    git pull -r
    
  4. Reapply the local changes.

    git stash pop
    

    or

    git stash apply
    

How to change the blue highlight color of a UITableViewCell?

1- Add a view to the content view of your cell.
2- Right click your cell.
3- Make the added view as "selectedBackgroundView" enter image description here

how to set auto increment column with sql developer

If you want to make your PK auto increment, you need to set the ID column property for that primary key.

  1. Right click on the table and select "Edit".
  2. In "Edit" Table window, select "columns", and then select your PK column.
  3. Go to ID Column tab and select Column Sequence as Type. This will create a trigger and a sequence, and associate the sequence to primary key.

See the picture below for better understanding.

enter image description here

// My source is: http://techatplay.wordpress.com/2013/11/22/oracle-sql-developer-create-auto-incrementing-primary-key/

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

I understand where the problem lies and when I look at the specs its clear that unescaped single quotes should be parsed correctly.

I am using jquery`s jQuery.parseJSON function to parse the JSON string but still getting the parse error when there is a single quote in the data that is prepared with json_encode.

Could it be a mistake in my implementation that looks like this (PHP - server side):

$data = array();

$elem = array();
$elem['name'] = 'Erik';
$elem['position'] = 'PHP Programmer';
$data[] = json_encode($elem);

$elem = array();
$elem['name'] = 'Carl';
$elem['position'] = 'C Programmer';
$data[] = json_encode($elem);

$jsonString = "[" . implode(", ", $data) . "]";

The final step is that I store the JSON encoded string into an JS variable:

<script type="text/javascript">
employees = jQuery.parseJSON('<?=$marker; ?>');
</script>

If I use "" instead of '' it still throws an error.

SOLUTION:

The only thing that worked for me was to use bitmask JSON_HEX_APOS to convert the single quotes like this:

json_encode($tmp, JSON_HEX_APOS);

Is there another way of tackle this issue? Is my code wrong or poorly written?

Thanks

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

I would like to augment to Stephen C's answer, my case was on the first dot. So since we have DHCP to allocate IP addresses in the company, DHCP changed my machine's address without of course asking neither me nor Oracle. So out of the blue oracle refused to do anything and gave the minus one dreaded exception. So if you want to workaround this once and for ever, and since TCP.INVITED_NODES of SQLNET.ora file does not accept wildcards as stated here, you can add you machine's hostname instead of the IP address.

CSS width of a <span> tag

Having fixed the height and width you sholud tell the how to bahave if the text inside it overflows its area. So add in the css

overflow: auto;

ssh: connect to host github.com port 22: Connection timed out

For me, the problem was from ISP side. The Port number was not enabled by the Internet Service Provider. So asked them to enable the port number over my network and it started working.
Only to test: Connect to mobile hotspot and type ssh -T [email protected] or git pull.
If it works, then ask your ISP to enable the port.

Javascript how to split newline

  1. Move the var ks = $('#keywords').val().split("\n"); inside the event handler
  2. Use alert(ks[k]) instead of alert(k)

  (function($){
     $(document).ready(function(){
        $('#data').submit(function(e){
           e.preventDefault();
           var ks = $('#keywords').val().split("\n");
           alert(ks[0]);
           $.each(ks, function(k){
              alert(ks[k]);
           });
        });
     });
  })(jQuery);

Demo

String Pattern Matching In Java

That's just a matter of String.contains:

if (input.contains("{item}"))

If you need to know where it occurs, you can use indexOf:

int index = input.indexOf("{item}");
if (index != -1) // -1 means "not found"
{
    ...
}

That's fine for matching exact strings - if you need real patterns (e.g. "three digits followed by at most 2 letters A-C") then you should look into regular expressions.

EDIT: Okay, it sounds like you do want regular expressions. You might want something like this:

private static final Pattern URL_PATTERN =
    Pattern.compile("/\\{[a-zA-Z0-9]+\\}/");

...

if (URL_PATTERN.matches(input).find())

Python, how to check if a result set is empty?

cursor.rowcount will usually be set to 0.

If, however, you are running a statement that would never return a result set (such as INSERT without RETURNING, or SELECT ... INTO), then you do not need to call .fetchall(); there won't be a result set for such statements. Calling .execute() is enough to run the statement.


Note that database adapters are also allowed to set the rowcount to -1 if the database adapter can't determine the exact affected count. See the PEP 249 Cursor.rowcount specification:

The attribute is -1 in case no .execute*() has been performed on the cursor or the rowcount of the last operation is cannot be determined by the interface.

The sqlite3 library is prone to doing this. In all such cases, if you must know the affected rowcount up front, execute a COUNT() select in the same transaction first.

Get unique values from arraylist in java

I hope I understand your question correctly: assuming that the values are of type String, the most efficient way is probably to convert to a HashSet and iterate over it:

ArrayList<String> values = ... //Your values
HashSet<String> uniqueValues = new HashSet<>(values);
for (String value : uniqueValues) {
   ... //Do something
}

Rails 3.1 and Image Assets

You'll want to change the extension of your css file from .css.scss to .css.scss.erb and do:

background-image:url(<%=asset_path "admin/logo.png"%>);

You may need to do a "hard refresh" to see changes. CMD+SHIFT+R on OSX browsers.

In production, make sure

rm -rf public/assets    
bundle exec rake assets:precompile RAILS_ENV=production

happens upon deployment.

How can I find out what version of git I'm running?

Or even just

git version

Results in something like

git version 1.8.3.msysgit.0

Add a column to existing table and uniquely number them on MS SQL Server

And the Postgres equivalent (second line is mandatory only if you want "id" to be a key):

ALTER TABLE tableName ADD id SERIAL;
ALTER TABLE tableName ADD PRIMARY KEY (id);

Parse String to Date with Different Format in Java

tl;dr

LocalDate.parse( 
    "19/05/2009" , 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) 
)

Details

The other Answers with java.util.Date, java.sql.Date, and SimpleDateFormat are now outdated.

LocalDate

The modern way to do date-time is work with the java.time classes, specifically LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

DateTimeFormatter

To parse, or generate, a String representing a date-time value, use the DateTimeFormatter class.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "19/05/2009" , f );

Do not conflate a date-time object with a String representing its value. A date-time object has no format, while a String does. A date-time object, such as LocalDate, can generate a String to represent its internal value, but the date-time object and the String are separate distinct objects.

You can specify any custom format to generate a String. Or let java.time do the work of automatically localizing.

DateTimeFormatter f = 
    DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
                     .withLocale( Locale.CANADA_FRENCH ) ;
String output = ld.format( f );

Dump to console.

System.out.println( "ld: " + ld + " | output: " + output );

ld: 2009-05-19 | output: mardi 19 mai 2009

See in action in IdeOne.com.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Redefining the Index in a Pandas DataFrame object

Why don't you simply use set_index method?

In : col = ['a','b','c']

In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)

In : data
Out:
    a   b   c
0   1   2   3
1  10  11  12
2  20  21  22

In : data2 = data.set_index('a')

In : data2
Out:
     b   c
a
1    2   3
10  11  12
20  21  22

Java: Reading integers from a file into an array

You must have an empty line in your file.

You may want to wrap your parseInt calls in a "try" block:

try {
  tall[i++] = Integer.parseInt(s);
}
catch (NumberFormatException ex) {
  continue;
}

Or simply check for empty strings before parsing:

if (s.length() == 0) 
  continue;

Note that by initializing your index variable i inside the loop, it is always 0. You should move the declaration before the while loop. (Or make it part of a for loop.)

How to remove all duplicate items from a list

No, it's simply a typo, the "list" at the end must be capitalized. You can nest loops over the same variable just fine (although there's rarely a good reason to).

However, there are other problems with the code. For starters, you're iterating through lists, so i and j will be items not indices. Furthermore, you can't change a collection while iterating over it (well, you "can" in that it runs, but madness lies that way - for instance, you'll propably skip over items). And then there's the complexity problem, your code is O(n^2). Either convert the list into a set and back into a list (simple, but shuffles the remaining list items) or do something like this:

seen = set()
new_x = []
for x in xs:
    if x in seen:
        continue
    seen.add(x)
    new_xs.append(x)

Both solutions require the items to be hashable. If that's not possible, you'll probably have to stick with your current approach sans the mentioned problems.

TypeError: worker() takes 0 positional arguments but 1 was given

When doing Flask Basic auth I got this error and then I realized I had wrapped_view(**kwargs) and it worked after changing it to wrapped_view(*args, **kwargs).

Can I create view with parameter in MySQL?

I previously came up with a different workaround that doesn't use stored procedures, but instead uses a parameter table and some connection_id() magic.

EDIT (Copied up from comments)

create a table that contains a column called connection_id (make it a bigint). Place columns in that table for parameters for the view. Put a primary key on the connection_id. replace into the parameter table and use CONNECTION_ID() to populate the connection_id value. In the view use a cross join to the parameter table and put WHERE param_table.connection_id = CONNECTION_ID(). This will cross join with only one row from the parameter table which is what you want. You can then use the other columns in the where clause for example where orders.order_id = param_table.order_id.

Download old version of package with NuGet

Browse to its page in the package index, eg. http://www.nuget.org/packages/Newtonsoft.Json/4.0.5

Then follow the install instructions given:

Install-Package Newtonsoft.Json -Version 4.0.5

Alternatively to download the .nupkg file, follow the 'Download' link eg. https://www.nuget.org/api/v2/package/Newtonsoft.Json/4.0.5

Obsolete: install my Chrome extension Nutake which inserts a download link.

How to check if a string is a number?

I need to do the same thing for a project I am currently working on. Here is how I solved things:

/* Prompt user for input */
printf("Enter a number: ");

/* Read user input */
char input[255]; //Of course, you can choose a different input size
fgets(input, sizeof(input), stdin);

/* Strip trailing newline */
size_t ln = strlen(input) - 1;
if( input[ln] == '\n' ) input[ln] = '\0';

/* Ensure that input is a number */
for( size_t i = 0; i < ln; i++){
    if( !isdigit(input[i]) ){
        fprintf(stderr, "%c is not a number. Try again.\n", input[i]);
        getInput(); //Assuming this is the name of the function you are using
        return;
    }
}

How do I get an Excel range using row and column numbers in VSTO / C#?

I found a good short method that seems to work well...

Dim x, y As Integer
x = 3: y = 5  
ActiveSheet.Cells(y, x).Select
ActiveCell.Value = "Tada"

In this example we are selecting 3 columns over and 5 rows down, then putting "Tada" in the cell.

Merge 2 arrays of objects

merge(a, b, key) {
    let merged = [];
    a.forEach(aitem => {
        let found = b.find( bitem => aitem[key] === bitem[key]);
        merged.push(found? found: aitem);
    });
    return merged;
}

Iterating through a range of dates in Python

For those who are interested in Pythonic functional way:

from datetime import date, timedelta
from itertools import count, takewhile

for d in takewhile(lambda x: x<=date(2009,6,9), map(lambda x:date(2009,5,30)+timedelta(days=x), count())):
    print(d)

Multiple left-hand assignment with JavaScript

var var1 = 1, var2 = 1, var3 = 1;

In this case var keyword is applicable to all the three variables.

var var1 = 1,
    var2 = 1,
    var3 = 1;

which is not equivalent to this:

var var1 = var2 = var3 = 1;

In this case behind the screens var keyword is only applicable to var1 due to variable hoisting and rest of the expression is evaluated normally so the variables var2, var3 are becoming globals

Javascript treats this code in this order:

/*
var 1 is local to the particular scope because of var keyword
var2 and var3 will become globals because they've used without var keyword
*/

var var1;   //only variable declarations will be hoisted.

var1= var2= var3 = 1; 

Nginx location "not equal to" regex

i was looking for the same. and found this solution.

Use negative regex assertion:

location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) { 
.... # your stuff 
} 

Source Negated Regular Expressions in location

Explanation of Regex :

If URL does not match any of the following path

example.com/favicon.ico
example.com/resources
example.com/robots.txt

Then it will go inside that location block and will process it.

How to use the CancellationToken property?

You can create a Task with cancellation token, when you app goto background you can cancel this token.

You can do this in PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle

var cancelToken = new CancellationTokenSource();
Task.Factory.StartNew(async () => {
    await Task.Delay(10000);
    // call web API
}, cancelToken.Token);

//this stops the Task:
cancelToken.Cancel(false);

Anther solution is user Timer in Xamarin.Forms, stop timer when app goto background https://xamarinhelp.com/xamarin-forms-timer/

How to present UIAlertController when not in a view controller?

Pretty generic UIAlertController extension for all cases of UINavigationController and/or UITabBarController. Also works if there's a modal VC on screen at the moment.

Usage:

//option 1:
myAlertController.show()
//option 2:
myAlertController.present(animated: true) {
    //completion code...
}

This is the extension:

//Uses Swift1.2 syntax with the new if-let
// so it won't compile on a lower version.
extension UIAlertController {

    func show() {
        present(animated: true, completion: nil)
    }

    func present(#animated: Bool, completion: (() -> Void)?) {
        if let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController {
            presentFromController(rootVC, animated: animated, completion: completion)
        }
    }

    private func presentFromController(controller: UIViewController, animated: Bool, completion: (() -> Void)?) {
        if  let navVC = controller as? UINavigationController,
            let visibleVC = navVC.visibleViewController {
                presentFromController(visibleVC, animated: animated, completion: completion)
        } else {
          if  let tabVC = controller as? UITabBarController,
              let selectedVC = tabVC.selectedViewController {
                presentFromController(selectedVC, animated: animated, completion: completion)
          } else {
              controller.presentViewController(self, animated: animated, completion: completion)
          }
        }
    }
}

How to do a Jquery Callback after form submit?

I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.

<form id="form">
...
<button type="submit"></button>
</form>

<script>
$(document).ready(function() {
  $("#form_selector").submit(function() {

    $.ajax({
     type: "POST",
      url: "form_handler.php",
      data: $(this).serialize(),
      success: function() {
        // callback code here
       }
    })

  })
})
</script>

How to vertically align an image inside a div

http://jsfiddle.net/MBs64/

.frame {
    height: 35px;      /* Equals maximum image height */
    width: 160px;
    border: 1px solid red;
    text-align: center;
    margin: 1em 0;
    display: table-cell;
    vertical-align: middle;
}
img {
    background: #3A6F9A;
    display: block;
    max-height: 35px;
    max-width: 160px;
}

The key property is display: table-cell; for .frame. Div.frame is displayed as inline with this, so you need to wrap it in a block element.

This works in Firefox, Opera, Chrome, Safari and Internet Explorer 8 (and later).

UPDATE

For Internet Explorer 7 we need to add a CSS expression:

*:first-child+html img {
    position: relative;
    top: expression((this.parentNode.clientHeight-this.clientHeight)/2+"px");
}

uppercase first character in a variable with bash

To capitalize first word only:

foo='one two three'
foo="${foo^}"
echo $foo

One two three


To capitalize every word in the variable:

foo="one two three"
foo=( $foo ) # without quotes
foo="${foo[@]^}"
echo $foo

One Two Three


(works in bash 4+)

How do you create a remote Git branch?

If you want to create a branch from the current branch

git checkout -b {your_local_branch_name} 

you want a branch from a remote branch, you can try

git checkout -b {your_local_branch_name} origin/<remote_branch_name>

If you are done with changes you can add the file.

git add -A or git add <each_file_names>

Then do a commit locally

git commit -m 'your commit message'

When you want to push to remote repo

git push -u origin <your_local_branch_name>

All together will be

git checkout -b bug_fixes 

or If you want to create a branch from a remote branch say development

git checkout -b bug_fixes origin/development

You can push to the branch to remote repo by

git push -u origin bug_fixes

Anytime you want to update your branch from any other branch say master.

git pull origin master.

'innerText' works in IE, but not in Firefox

As per Prakash K's answer Firefox does not support the innerText property. So you can simply test whether the user agent supports this property and proceed accordingly as below:

function changeText(elem, changeVal) {
    if (typeof elem.textContent !== "undefined") {
        elem.textContent = changeVal;
    } else {
        elem.innerText = changeVal;
    }
}

How do I convert uint to int in C#?

Given:

 uint n = 3;

int i = checked((int)n); //throws OverflowException if n > Int32.MaxValue
int i = unchecked((int)n); //converts the bits only 
                           //i will be negative if n > Int32.MaxValue

int i = (int)n; //same behavior as unchecked

or

int i = Convert.ToInt32(n); //same behavior as checked

--EDIT

Included info as mentioned by Kenan E. K.

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

Styling text input caret

It is enough to use color property alongside with -webkit-text-fill-color this way:

_x000D_
_x000D_
    input {_x000D_
        color: red; /* color of caret */_x000D_
        -webkit-text-fill-color: black; /* color of text */_x000D_
    }
_x000D_
<input type="text"/>
_x000D_
_x000D_
_x000D_

Works in WebKit browsers (but not in iOS Safari, where is still used system color for caret) and also in Firefox.

The -webkit-text-fill-color CSS property specifies the fill color of characters of text. If this property is not set, the value of the color property is used. MDN

So this means we set text color with text-fill-color and caret color with standard color property. In unsupported browser, caret and text will have same color – color of the caret.

How do I convert a TimeSpan to a formatted string?

You can use the following code.

public static class TimeSpanExtensions
{
  public static String Verbose(this TimeSpan timeSpan)
  {
    var hours = timeSpan.Hours;
    var minutes = timeSpan.Minutes;

    if (hours > 0) return String.Format("{0} hours {1} minutes", hours, minutes);
    return String.Format("{0} minutes", minutes);
  }
}

WindowsError: [Error 126] The specified module could not be found

NestedCaveats solution worked for me.

Imported my .dll files before importing torch and gpytorch, and all went smoothly.

So I just want to add that its not just importing pytorch but I can confirm that torch and gpytorch have this issue as well. I'd assume it covers any other torch-related libraries.

How can I check if PostgreSQL is installed or not via Linux script?

For many years I used the command:

ps aux | grep postgres

On one hand it is useful (for any process) and gives useful info (but from process POV). But on the other hand it is for checking if the server you know, you already installed is running.

At some point I found this tutorial, where the usage of the locate command is shown. It looks like this command is much more to the point for this case.

How to execute an Oracle stored procedure via a database link

The syntax is

EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );

C/C++ check if one bit is set in, i.e. int variable

For the low-level x86 specific solution use the x86 TEST opcode.

Your compiler should turn _bittest into this though...

C Programming: How to read the whole file contents into a buffer

A portable solution could use getc.

#include <stdio.h>

char buffer[MAX_FILE_SIZE];
size_t i;

for (i = 0; i < MAX_FILE_SIZE; ++i)
{
    int c = getc(fp);

    if (c == EOF)
    {
        buffer[i] = 0x00;
        break;
    }

    buffer[i] = c;
}

If you don't want to have a MAX_FILE_SIZE macro or if it is a big number (such that buffer would be to big to fit on the stack), use dynamic allocation.

How to align input forms in HTML

Well for the very basics you can try aligning them in the table. However the use of table is bad for layout since table is meant for contents.

What you can use is CSS floating techniques.

CSS Code

.styleform label{float:left;}
.styleform input{margin-left:200px;} /* this gives space for the label on the left */
.styleform .clear{clear:both;} /* prevent elements from stacking weirdly */

HTML

<div class="styleform">
<form>
<label>First Name:</label><input type="text" name="first" /><div class="clear"></div>
<label>Last Name:</label><input type="text" name="first" /><div class="clear"></div>
<label>Email:</label><input type="text" name="first" /><div class="clear"></div>
</form>
</div>

An elaborated article I wrote can be found answering the question of IE7 float problem: IE7 float right problems

How to get min, seconds and milliseconds from datetime.now() in python?

What about:

datetime.now().strftime('%M:%S.%f')[:-4]

I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.

EDIT

If the %f modifier doesn't work for you, you can try something like:

now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]

Again, I'm assuming you just want to truncate the precision.

Simple mediaplayer play mp3 from file path?

Use the code below it worked for me.

MediaPlayer mp = new MediaPlayer();
mp.setDataSource("/mnt/sdcard/yourdirectory/youraudiofile.mp3");
mp.prepare();
mp.start();

Rails DateTime.now without Time

What you need is the function strftime:

Time.now.strftime("%Y-%d-%m %H:%M:%S %Z")

Migration: Cannot add foreign key constraint

In my case the problem was with migration timing be careful while creating migrations firstly create the child migration than the base migration. Because if you create base migration first which have your foreign key will look for child table and there wont be table which then throw an exception.

Further more:

When you create migration it has a timestamp in the beginning of it. lets say you have created a migration cat so it will look like 2015_08_19_075954_the_cats_time.php and it has this code

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class TheCatsTime extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cat', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');  
            $table->date('date_of_birth');
            $table->integer('breed_id')->unsigned()->nullable(); 
        });

        Schema::table('cat', function($table) {
        $table->foreign('breed_id')->references('id')->on('breed');
      });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('cat');
    }
}

And after creating the base table you create another migration breed which is child table it has its own creation time and date stamp. The code will look like :

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class BreedTime extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('breed', function (Blueprint $table) {
             $table->increments('id');    
             $table->string('name');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('breed');
    }
}

it seems these both table are correct but when you run php artisan migrate. It will throw an exception because migration will first create the base table in your database because you have created this migration first and our base table has foreign key constraint in it which will look for child table and the child table doesn't exist which is probably an exception..

So:

Create child table migration first.

Create base table migration after child migration is created.

php artisan migrate.

done it will work

How to add not null constraint to existing column in MySQL

Try this, you will know the difference between change and modify,

ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]

ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
  • You can change name and datatype of the particular column using CHANGE.
  • You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

Hope, I explained well in detail.

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

What it is telling you is - the 2nd guard let or the if let check is not happening on an Optional Int or Optional String. You already have a non-optional value, so guarding or if-letting is not needed anymore

Remove the last character from a string

An alternative to substr is the following, as a function:

substr_replace($string, "", -1)

Is it the fastest? I don't know, but I'm willing to bet these alternatives are all so fast that it just doesn't matter.

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

SELECT INTO USING UNION QUERY

You can also try:

create table new_table as
select * from table1
union
select * from table2

How to compare objects by multiple fields

Its easy to do using Google's Guava library.

e.g. Objects.equal(name, name2) && Objects.equal(age, age2) && ...

More examples:

how do I insert a column at a specific column index in pandas?

see docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html

using loc = 0 will insert at the beginning

df.insert(loc, column, value)

df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]})

df
Out: 
   B  C
0  1  4
1  2  5
2  3  6

idx = 0
new_col = [7, 8, 9]  # can be a list, a Series, an array or a scalar   
df.insert(loc=idx, column='A', value=new_col)

df
Out: 
   A  B  C
0  7  1  4
1  8  2  5
2  9  3  6

Retrieving the first digit of a number

This way might makes more sense if you don't want to use str methods

int first = 1;
for (int i = 10; i < number; i *= 10) {
    first = number / i;
}

Change font-weight of FontAwesome icons?

.star-light::after {
    content: "\f005";
    font-family: "FontAwesome";
    font-size: 3.2rem;
    color: #fff;
    font-weight: 900;
    background-color: red;
}

PHP Date Time Current Time Add Minutes

echo $date = date('H:i:s', strtotime('13:00:00 + 30 minutes') );

13:00:00 - any inputted time

30 minutes - any interval you wish (20 hours, 10 minutes, 1 seconds etc...)

Downloading MySQL dump from command line

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%.%MM%.%DD%.%HH%.%Min%.%Sec%"
set drive=your backup folder
set databaseName=your databasename
set user="your database user"
set password="your database password"
subst Z: "C:\Program Files\7-Zip" 
subst M: "D:\AppServ\MySQL\bin"
set zipFile="%drive%\%databaseName%-%datestamp%.zip"
set sqlFile="%drive%\%databaseName%-%datestamp%.sql"
M:\mysqldump.exe --user=%user% --password=%password% --result-file="%sqlFile%" --databases %databaseName%
@echo Mysql Backup Created
Z:\7z.exe a -tzip "%zipFile%" "%sqlFile%"
@echo File Compress End
del %sqlFile%
@echo Delete mysql file
pause;

How do I get some variable from another class in Java?

Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.

How does one remove a Docker image?

docker rm container_name

docker rmi image_name

docker help

rm Remove one or more containers

rmi Remove one or more images

Finding rows that don't contain numeric data in Oracle

I've found this useful:

 select translate('your string','_0123456789','_') from dual

If the result is NULL, it's numeric (ignoring floating point numbers.)

However, I'm a bit baffled why the underscore is needed. Without it the following also returns null:

 select translate('s123','0123456789', '') from dual

There is also one of my favorite tricks - not perfect if the string contains stuff like "*" or "#":

 SELECT 'is a number' FROM dual WHERE UPPER('123') = LOWER('123')

How do I test if a variable does not equal either of two values?

You used the word "or" in your pseudo code, but based on your first sentence, I think you mean and. There was some confusion about this because that is not how people usually speak.

You want:

var test = $("#test").val();
if (test !== 'A' && test !== 'B'){
    do stuff;
}
else {
    do other stuff;
}

Can't connect to docker from docker-compose

if you are using docker-machine then you have to activate the environment using env variable. incase you are not using docker-machine then run your commands with sudo

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

I should add: You should not be putting your dll's into \system32\ anyway! Modify your code, modify your installer... find a home for your bits that is NOT anywhere under c:\windows\

For example, your installer puts your dlls into:

\program files\<your app dir>\

or

\program files\common files\<your app name>\

(Note: The way you actually do this is to use the environment var: %ProgramFiles% or %ProgramFiles(x86)% to find where Program Files is.... you do not assume it is c:\program files\ ....)

and then sets a registry tag :

HKLM\software\<your app name>
-- dllLocation

The code that uses your dlls reads the registry, then dynamically links to the dlls in that location.

The above is the smart way to go.

You do not ever install your dlls, or third party dlls into \system32\ or \syswow64. If you have to statically load, you put your dlls in your exe dir (where they will be found). If you cannot predict the exe dir (e.g. some other exe is going to call your dll), you may have to put your dll dir into the search path (avoid this if at all poss!)

system32 and syswow64 are for Windows provided files... not for anyone elses files. The only reason folks got into the bad habit of putting stuff there is because it is always in the search path, and many apps/modules use static linking. (So, if you really get down to it, the real sin is static linking -- this is a sin in native code and managed code -- always always always dynamically link!)

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I had the same issue too, to solve this, check in References of your project if the version of Newtonsoft.Json was updated (probablly don´t), then remove it and check in your either Web.config or App.config wheter the element dependentAssembly was updated as follows:

<dependentAssembly>
  <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>

After that, rebuild the project again (the dll will be replaced with the correct version)

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

I noticed this problem recently myself, and I'm not sure how it comes about but it would appear sometimes firefox gets stuck on something loaded in cache. After clearing cache and restarting firefox it appears to function again.

Is Ruby pass by reference or by value?

The other answerers are all correct, but a friend asked me to explain this to him and what it really boils down to is how Ruby handles variables, so I thought I would share some simple pictures / explanations I wrote for him (apologies for the length and probably some oversimplification):


Q1: What happens when you assign a new variable str to a value of 'foo'?

str = 'foo'
str.object_id # => 2000

enter image description here

A: A label called str is created that points at the object 'foo', which for the state of this Ruby interpreter happens to be at memory location 2000.


Q2: What happens when you assign the existing variable str to a new object using =?

str = 'bar'.tap{|b| puts "bar: #{b.object_id}"} # bar: 2002
str.object_id # => 2002

enter image description here

A: The label str now points to a different object.


Q3: What happens when you assign a new variable = to str?

str2 = str
str2.object_id # => 2002

enter image description here

A: A new label called str2 is created that points at the same object as str.


Q4: What happens if the object referenced by str and str2 gets changed?

str2.replace 'baz'
str2 # => 'baz'
str  # => 'baz'
str.object_id # => 2002
str2.object_id # => 2002

enter image description here

A: Both labels still point at the same object, but that object itself has mutated (its contents have changed to be something else).


How does this relate to the original question?

It's basically the same as what happens in Q3/Q4; the method gets its own private copy of the variable / label (str2) that gets passed in to it (str). It can't change which object the label str points to, but it can change the contents of the object that they both reference to contain else:

str = 'foo'

def mutate(str2)
  puts "str2: #{str2.object_id}"
  str2.replace 'bar'
  str2 = 'baz'
  puts "str2: #{str2.object_id}"
end

str.object_id # => 2004
mutate(str) # str2: 2004, str2: 2006
str # => "bar"
str.object_id # => 2004

How to call an action after click() in Jquery?

you can write events on elements like chain,

$(element).on('click',function(){
   //action on click
}).on('mouseup',function(){
   //action on mouseup (just before click event)
});

i've used it for removing cart items. same object, doing some action, after another action

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

What I did was creating my own Window and Style. Because I like to have control over everything and I didn't want some external libraries just to use a Window from it. I looked at already mentioned MahApps.Metro on GitHub

MahApps

and also very nice Modern UI on GitHub. (.NET4.5 only)

Modern UI

There is one more it's Elysium but I really didn't try this one.

Elysium

The style I did was really easy when I looked how it's done in these. Now I have my own Window and I can do whatever I want with xaml... for me it's the main reason why I did my own. And I made one more for you too :) I should probably say that I wouldn't be able to do it without exploring Modern UI it was great help. I tried to make it look like VS2012 Window. It looks like this.

MyWindow

Here is code (please note that it's targeting .NET4.5)

public class MyWindow : Window
{

    public MyWindow()
    {
        this.CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, this.OnCloseWindow));
        this.CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, this.OnMaximizeWindow, this.OnCanResizeWindow));
        this.CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, this.OnMinimizeWindow, this.OnCanMinimizeWindow));
        this.CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, this.OnRestoreWindow, this.OnCanResizeWindow));
    }

    private void OnCanResizeWindow(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = this.ResizeMode == ResizeMode.CanResize || this.ResizeMode == ResizeMode.CanResizeWithGrip;
    }

    private void OnCanMinimizeWindow(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = this.ResizeMode != ResizeMode.NoResize;
    }

    private void OnCloseWindow(object target, ExecutedRoutedEventArgs e)
    {
        SystemCommands.CloseWindow(this);
    }

    private void OnMaximizeWindow(object target, ExecutedRoutedEventArgs e)
    {
        SystemCommands.MaximizeWindow(this);
    }

    private void OnMinimizeWindow(object target, ExecutedRoutedEventArgs e)
    {
        SystemCommands.MinimizeWindow(this);
    }

    private void OnRestoreWindow(object target, ExecutedRoutedEventArgs e)
    {
        SystemCommands.RestoreWindow(this);
    }
}

And here resources:

<BooleanToVisibilityConverter x:Key="bool2VisibilityConverter" />

<Color x:Key="WindowBackgroundColor">#FF2D2D30</Color>
<Color x:Key="HighlightColor">#FF3F3F41</Color>
<Color x:Key="BlueColor">#FF007ACC</Color>
<Color x:Key="ForegroundColor">#FFF4F4F5</Color>

<SolidColorBrush x:Key="WindowBackgroundColorBrush" Color="{StaticResource WindowBackgroundColor}"/>
<SolidColorBrush x:Key="HighlightColorBrush" Color="{StaticResource HighlightColor}"/>
<SolidColorBrush x:Key="BlueColorBrush" Color="{StaticResource BlueColor}"/>
<SolidColorBrush x:Key="ForegroundColorBrush" Color="{StaticResource ForegroundColor}"/>

<Style x:Key="WindowButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
    <Setter Property="Padding" Value="1" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter x:Name="contentPresenter"
                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                          Margin="{TemplateBinding Padding}"
                          RecognizesAccessKey="True" />
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="{StaticResource HighlightColorBrush}" />
                    </Trigger>
                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="{DynamicResource BlueColorBrush}" />
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter TargetName="contentPresenter" Property="Opacity" Value=".5" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style x:Key="MyWindowStyle" TargetType="local:MyWindow">
    <Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
    <Setter Property="Background" Value="{DynamicResource WindowBackgroundBrush}"/>
    <Setter Property="ResizeMode" Value="CanResizeWithGrip" />
    <Setter Property="UseLayoutRounding" Value="True" />
    <Setter Property="TextOptions.TextFormattingMode" Value="Display" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyWindow">
                <Border x:Name="WindowBorder" Margin="{Binding Source={x:Static SystemParameters.WindowNonClientFrameThickness}}" Background="{StaticResource WindowBackgroundColorBrush}">
                    <Grid>
                        <Border BorderThickness="1">
                            <AdornerDecorator>
                                <Grid x:Name="LayoutRoot">
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="25" />
                                        <RowDefinition Height="*" />
                                        <RowDefinition Height="15" />
                                    </Grid.RowDefinitions>
                                    <ContentPresenter Grid.Row="1" Grid.RowSpan="2" Margin="7"/>
                                    <Rectangle x:Name="HeaderBackground" Height="25" Fill="{DynamicResource WindowBackgroundColorBrush}" VerticalAlignment="Top" Grid.Row="0"/>
                                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
                                        <Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
                                            <Button.Content>
                                                <Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
                                                    <Path Data="M0,6 L8,6 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                        Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2"  />
                                                </Grid>
                                            </Button.Content>
                                        </Button>
                                        <Grid Margin="1,0,1,0">
                                            <Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
                                                <Button.Content>
                                                    <Grid Width="30" Height="25" UseLayoutRounding="True" RenderTransform="1,0,0,1,.5,.5">
                                                        <Path Data="M2,0 L8,0 L8,6 M0,3 L6,3 M0,2 L6,2 L6,8 L0,8 Z" Width="8" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                            Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1"  />
                                                    </Grid>
                                                </Button.Content>
                                            </Button>
                                            <Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
                                                <Button.Content>
                                                    <Grid Width="31" Height="25">
                                                        <Path Data="M0,1 L9,1 L9,8 L0,8 Z" Width="9" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                            Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2"  />
                                                    </Grid>
                                                </Button.Content>
                                            </Button>
                                        </Grid>
                                        <Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close"  Style="{StaticResource WindowButtonStyle}">
                                            <Button.Content>
                                                <Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
                                                    <Path Data="M0,0 L8,7 M8,0 L0,7 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                        Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1.5"  />
                                                </Grid>
                                            </Button.Content>
                                        </Button>
                                    </StackPanel>
                                    <TextBlock x:Name="WindowTitleTextBlock" Grid.Row="0" Text="{TemplateBinding Title}" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"  Margin="8 -1 0 0"  FontSize="16"  Foreground="{TemplateBinding Foreground}"/>
                                    <Grid Grid.Row="2">
                                        <Path x:Name="ResizeGrip" Visibility="Collapsed" Width="12" Height="12" Margin="1" HorizontalAlignment="Right"
                                        Stroke="{StaticResource BlueColorBrush}" StrokeThickness="1" Stretch="None" Data="F1 M1,10 L3,10 M5,10 L7,10 M9,10 L11,10 M2,9 L2,11 M6,9 L6,11 M10,9 L10,11 M5,6 L7,6 M9,6 L11,6 M6,5 L6,7 M10,5 L10,7 M9,2 L11,2 M10,1 L10,3" />
                                    </Grid>
                                </Grid>
                            </AdornerDecorator>
                        </Border>
                        <Border BorderBrush="{StaticResource BlueColorBrush}" BorderThickness="1" Visibility="{Binding IsActive, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Converter={StaticResource bool2VisibilityConverter}}" />
                    </Grid>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="WindowState" Value="Maximized">
                        <Setter TargetName="Maximize" Property="Visibility" Value="Collapsed" />
                        <Setter TargetName="Restore" Property="Visibility" Value="Visible" />
                        <Setter TargetName="LayoutRoot" Property="Margin" Value="7" />
                    </Trigger>
                    <Trigger Property="WindowState" Value="Normal">
                        <Setter TargetName="Maximize" Property="Visibility" Value="Visible" />
                        <Setter TargetName="Restore" Property="Visibility" Value="Collapsed" />
                    </Trigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="ResizeMode" Value="CanResizeWithGrip" />
                            <Condition Property="WindowState" Value="Normal" />
                        </MultiTrigger.Conditions>
                        <Setter TargetName="ResizeGrip" Property="Visibility" Value="Visible" />
                    </MultiTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="WindowChrome.WindowChrome">
        <Setter.Value>
            <WindowChrome CornerRadius="0" GlassFrameThickness="1" UseAeroCaptionButtons="False" />
        </Setter.Value>
    </Setter>
</Style>

setHintTextColor() in EditText

Use this to change the hint color. -

editText.setHintTextColor(getResources().getColor(R.color.white));

Solution for your problem -

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3){
        //do something
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        //do something
    }

    @Override
    public void afterTextChanged(Editable arg0) {
        if(arg0.toString().length() <= 0) //check if length is equal to zero
            tv.setHintTextColor(getResources().getColor(R.color.white));
    }
});

How to move git repository with all branches from bitbucket to github?

In case you want to move your local git repository to another upstream you can also do this:

to get the current remote url:

git remote get-url origin

will show something like: https://bitbucket.com/git/myrepo

to set new remote repository:

git remote set-url origin [email protected]:folder/myrepo.git

now push contents of current (develop) branch:

git push --set-upstream origin develop

You now have a full copy of the branch in the new remote.

optionally return to original git-remote for this local folder:

git remote set-url origin https://bitbucket.com/git/myrepo

Gives the benefit you can now get your new git-repository from github in another folder so that you have two local folders both pointing to the different remotes, the previous (bitbucket) and the new one both available.

Twitter Bootstrap Button Text Word Wrap

FWIW, in Boostrap 4.4, you can add .text-wrap style to things like buttons:

   <a href="#" class="btn btn-primary text-wrap">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>

https://getbootstrap.com/docs/4.4/utilities/text/#text-wrapping-and-overflow

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

"The Controls collection cannot be modified because the control contains code blocks"

In my case I got this error because I was wrongly setting InnerText to a div with html inside it.

Example:

SuccessMessagesContainer.InnerText = "";

   <div class="SuccessMessages ui-state-success" style="height: 25px; display: none;" id="SuccessMessagesContainer" runat="server">
      <table>
         <tr>
            <td style="width: 80px; vertical-align: middle; height: 18px; text-align: center;">
               <img src="<%=Image_success_icn %>" style="margin: 0 auto; height: 18px;
                  width: 18px;" />
            </td>
            <td id="SuccessMessage" style="vertical-align: middle;" class="SuccessMessage" runat="server" >
            </td>
         </tr>
      </table>
   </div>

Object creation on the stack/heap?

Actually, neither statement says anything about heap or stack. The code

Object o;

creates one of the following, depending on its context:

  • a local variable with automatic storage,
  • a static variable at namespace or file scope,
  • a member variable that designates the subobject of another object.

This means that the storage location is determined by the context in which the object is defined. In addition, the C++ standard does not talk about stack vs heap storage. Instead, it talks about storage duration, which can be either automatic, dynamic, static or thread-local. However, most implementations implement automatic storage via the call stack, and dynamic storage via the heap.

Local variables, which have automatic storage, are thus created on the stack. Static (and thread-local) objects are generally allocated in their own memory regions, neither on the stack nor on the heap. And member variables are allocated wherever the object they belong to is allocated. They have their containing object’s storage duration.

To illustrate this with an example:

struct Foo {
    Object o;
};

Foo foo;

int main() {
    Foo f;
    Foo* p = new Foo;
    Foo* pf = &f;
}

Now where is the object Foo::o (that is, the subobject o of an object of class Foo) created? It depends:

  • foo.o has static storage because foo has static storage, and therefore lives neither on the stack nor on the heap.
  • f.o has automatic storage since f has automatic storage (= it lives on the stack).
  • p->o has dynamic storage since *p has dynamic storage (= it lives on the heap).
  • pf->o is the same object as f.o because pf points to f.

In fact, both p and pf in the above have automatic storage. A pointer’s storage is indistinguishable from any other object’s, it is determined by context. Furthermore, the initialising expression has no effect on the pointer storage.

The pointee (= what the pointer points to) is a completely different matter, and could refer to any kind of storage: *p is dynamic, whereas *pf is automatic.

sqlite3.OperationalError: unable to open database file

If this happens randomly after correctly being able to access your database (and no settings have changed), it could be a result of a corrupted database.

I got this error after trying to write to my database from two processes at the same time and it must have corrupted my db.sqlite3 file.

My solution was to revert back to a previous commit before the corruption happened.

select2 - hiding the search box

//Disable a search on particular selector
$(".my_selector").select2({
    placeholder: "ÁREAS(todas)",
    tags: true,
    width:'100%',
    containerCssClass: "area_disable_search_input" // I add new class 
});

//readonly prop to selector class
$(".area_disable_search_input input").prop("readonly", true);

MySQL Update Inner Join tables query

The SET clause should come after the table specification.

UPDATE business AS b
INNER JOIN business_geocode g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
  b.mapy = g.longitude
WHERE  (b.mapx = '' or b.mapx = 0) and
  g.latitude > 0

How to convert Java String into byte[]?

Simply:

String abc="abcdefghight";

byte[] b = abc.getBytes();

Target class controller does not exist - Laravel 8

You are using Laravel 8. In a fresh install of Laravel 8, there is no namespace prefix being applied to your route groups that your routes are loaded into.

"In previous releases of Laravel, the RouteServiceProvider contained a $namespace property. This property's value would automatically be prefixed onto controller route definitions and calls to the action helper / URL::action method. In Laravel 8.x, this property is null by default. This means that no automatic namespace prefixing will be done by Laravel." Laravel 8.x Docs - Release Notes

You would have to use the Fully Qualified Class Name for your Controllers when referring to them in your routes when not using the namespace prefixing.

use App\Http\Controllers\UserController;

Route::get('/users', [UserController::class, 'index']);
// or
Route::get('/users', 'App\Http\Controllers\UserController@index');

If you prefer the old way:

App\Providers\RouteServiceProvider:

public function boot()
{
    ...

    Route::prefix('api')
        ->middleware('api')
        ->namespace('App\Http\Controllers') // <---------
        ->group(base_path('routes/api.php'));

    ...
}

Do this for any route groups you want a declared namespace for.

The $namespace property:

Though there is a mention of a $namespace property to be set on your RouteServiceProvider in the Release notes and commented in your RouteServiceProvider this does not have any effect on your routes. It is currently only for adding a namespace prefix for generating URLs to actions. So you can set this variable, but it by itself won't add these namespace prefixes, you would still have to make sure you would be using this variable when adding the namespace to the route groups.

This information is now in the Upgrade Guide

Laravel 8.x Docs - Upgrade Guide - Routing

With what the Upgrade Guide is showing the important part is that you are defining a namespace on your routes groups. Setting the $namespace variable by itself only helps in generating URLs to actions.

Again, and I can't stress this enough, the important part is setting the namespace for the route groups, which they just happen to be doing by referencing the member variable $namespace directly in the example.

Update:

If you have installed a fresh copy of Laravel 8 since version 8.0.2 of laravel/laravel you can uncomment the protected $namespace member variable in the RouteServiceProvider to go back to the old way, as the route groups are setup to use this member variable for the namespace for the groups.

// protected $namespace = 'App\\Http\\Controllers';

The only reason uncommenting that would add the namespace prefix to the Controllers assigned to the routes is because the route groups are setup to use this variable as the namespace:

...
->namespace($this->namespace)
...

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

Some old gradle tools cannot copy .so files into build folder by somehow, manually copying these files into build folder as below can solve the problem:

build/intermediates/rs/{build config}/{support architecture}/

build config: beta/production/sit/uat

support architecture: armeabi/armeabi-v7a/mips/x86

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

How to correctly represent a whitespace character

Which whitespace character? The most common is the normal space, which is between each word in my sentences. This is just " ".

Dynamic creation of table with DOM

You need to create new TextNodes as well as td nodes for each column, not reuse them among all of the columns as your code is doing.

Edit: Revise your code like so:

for (var i = 1; i < 4; i++)
{
   tr[i] = document.createElement('tr');   
      var td1 = document.createElement('td');
      var td2 = document.createElement('td');
      td1.appendChild(document.createTextNode('Text1'));
      td2.appendChild(document.createTextNode('Text2'));
      tr[i].appendChild(td1);
      tr[i].appendChild(td2);
  table.appendChild(tr[i]);
}

How do I copy an object in Java?

Create a copy constructor:

class DummyBean {
  private String dummy;

  public DummyBean(DummyBean another) {
    this.dummy = another.dummy; // you can access  
  }
}

Every object has also a clone method which can be used to copy the object, but don't use it. It's way too easy to create a class and do improper clone method. If you are going to do that, read at least what Joshua Bloch has to say about it in Effective Java.

Forgot Oracle username and password, how to retrieve?

The usernames are shown in the dba_users's username column, there is a script you can run called:

alter user username identified by password

You can get more information here - https://community.oracle.com/thread/632617?tstart=0

How to randomly select rows in SQL?

This is an old question, but attempting to apply a new field (either NEWID() or ORDER BY rand()) to a table with a large number of rows would be prohibitively expensive. If you have incremental, unique IDs (and do not have any holes) it will be more efficient to calculate the X # of IDs to be selected instead of applying a GUID or similar to every single row and then taking the top X # of.

DECLARE @minValue int;
DECLARE @maxValue int;
SELECT @minValue = min(id), @maxValue = max(id) from [TABLE];

DECLARE @randomId1 int, @randomId2 int, @randomId3 int, @randomId4 int, @randomId5 int
SET @randomId1 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId2 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId3 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId4 = ((@maxValue + 1) - @minValue) * Rand() + @minValue
SET @randomId5 = ((@maxValue + 1) - @minValue) * Rand() + @minValue

--select @maxValue as MaxValue, @minValue as MinValue
--  , @randomId1 as SelectedId1
--  , @randomId2 as SelectedId2
--  , @randomId3 as SelectedId3
--  , @randomId4 as SelectedId4
--  , @randomId5 as SelectedId5

select * from [TABLE] el
where el.id in (@randomId1, @randomId2, @randomId3, @randomId4, @randomId5)

If you wanted to select many more rows I would look into populating a #tempTable with an ID and a bunch of rand() values then using each rand() value to scale to the min-max values. That way you do not have to define all of the @randomId1...n parameters. I've included an example below using a CTE to populate the initial table.

DECLARE @NumItems int = 100;

DECLARE @minValue int;
DECLARE @maxValue int;
SELECT @minValue = min(id), @maxValue = max(id) from [TABLE];
DECLARE @range int = @maxValue+1 - @minValue;

with cte (n) as (
   select 1 union all
   select n+1 from cte
   where n < @NumItems
)
select cast( @range * rand(cast(newid() as varbinary(100))) + @minValue as int) tp
into #Nt
from cte;

select * from #Nt ntt
inner join [TABLE] i on i.id = ntt.tp;

drop table #Nt;

Change the maximum upload file size

To locate the ini file, first run

php -i | grep -i "loaded configuration file"

Then open the file and change

upload_max_filesize = 2M
post_max_size = 2M

replacing the 2M with the size you want, for instance 100M.

I've got a blog post about with a little more info too http://www.seanbehan.com/how-to-increase-or-change-the-file-upload-size-in-the-php-ini-file-for-wordpress

When is the init() function run?

init will be called everywhere uses its package(no matter blank import or import), but only one time.

this is a package:

package demo

import (
    "some/logs"
)

var count int

func init() {
    logs.Debug(count)
}

// Do do
func Do() {
    logs.Debug("dd")
}

any package(main package or any test package) import it as blank :

_ "printfcoder.com/we/models/demo"

or import it using it func:

"printfcoder.com/we/models/demo"

func someFunc(){
   demo.Do()
}

the init will log 0 only one time. the first package using it, its init func will run before the package's init. So:

A calls B, B calls C, all of them have init func, the C's init will be run first before B's, B's before A's.

How to write file in UTF-8 format?

  1. Open your files in windows notebook
  2. Change the encoding to be an UTF-8 encoding
  3. Save your file
  4. Try again! :O)

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

How do Python's any and all functions work?

I know this is old, but I thought it might be helpful to show what these functions look like in code. This really illustrates the logic, better than text or a table IMO. In reality they are implemented in C rather than pure Python, but these are equivalent.

def any(iterable):
    for item in iterable:
        if item:
            return True
    return False

def all(iterable):
    for item in iterable:
        if not item:
            return False
    return True

In particular, you can see that the result for empty iterables is just the natural result, not a special case. You can also see the short-circuiting behaviour; it would actually be more work for there not to be short-circuiting.

When Guido van Rossum (the creator of Python) first proposed adding any() and all(), he explained them by just posting exactly the above snippets of code.

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

How to draw vertical lines on a given plot in matplotlib

If someone wants to add a legend and/or colors to some vertical lines, then use this:


import matplotlib.pyplot as plt

# x coordinates for the lines
xcoords = [0.1, 0.3, 0.5]
# colors for the lines
colors = ['r','k','b']

for xc,c in zip(xcoords,colors):
    plt.axvline(x=xc, label='line at x = {}'.format(xc), c=c)

plt.legend()
plt.show()

Results:

my amazing plot seralouk

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

How to get distinct values from an array of objects in JavaScript?

If you would like to filter out duplicate values from an array on a known unique object property, you could use the following snippet:

let arr = [
  { "name": "Joe", "age": 17 },
  { "name": "Bob", "age": 17 },
  { "name": "Carl", "age": 35 },
  { "name": "Carl", "age": 35 }
];

let uniqueValues = [...arr.reduce((map, val) => {
    if (!map.has(val.name)) {
        map.set(val.name, val);
    }
    return map;
}, new Map()).values()]

How can I tell how many objects I've stored in an S3 bucket?

3Hub is discontinued. There's a better solution, you can use Transmit (Mac only), then you just connect to your bucket and choose Show Item Count from the View menu.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

I know its very late but I think it may help someone in resolving his issue.

In my case It was occurring because compileSdkVersion and targetSdkVersion was set to 29 while when I check my SDK Manager, It was showing that package is partially installed. Whereas SDK version 28 was completely installed. I changed my compileSdkVersion and targetSdkVersion to 28 along with support libraries.

Earlier: compileSdkVersion 29 targetSdkVersion 29 implementation 'com.android.support:appcompat-v7:29.+' implementation 'com.android.support:design:29.+'

After Modification: compileSdkVersion 28 targetSdkVersion 28 implementation 'com.android.support:appcompat-v7:28.+' implementation 'com.android.support:design:28.+'

It worked like a charm after applying these changes.

Using multiple IF statements in a batch file

is there a special guideline that should be followed

There is no "standard" way to do batch files, because the vast majority of their authors and maintainers either don't understand programming concepts, or they think they don't apply to batch files.

But I am a programmer. I'm used to compiling, and I'm used to debuggers. Batch files aren't compiled, and you can't run them through a debugger, so they make me nervous. I suggest you be extra strict on what you write, so you can be very sure it will do what you think it does.

There are some coding standards that say: If you write an if statement, you must use braces, even if you don't have an else clause. This saves you from subtle, hard-to-debug problems, and is unambiguously readable. I see no reason you couldn't apply this reasoning to batch files.

Let's take a look at your code.

IF EXIST somefile.txt IF EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

And the IF syntax, from the command, HELP IF:

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXISTS filename command

...

IF EXIST filename (
  command
) ELSE (
  other command
)

So you are chaining IF's as commands.

If you use the common coding-standard rule I mentioned above, you would always want to use parens. Here is how you would do so for your example code:

IF EXIST "somefile.txt" (
  IF EXIST "someotherfile.txt" (
    SET var="somefile.txt,someotherfile.txt"
  )
)

Make sure you cleanly format, and do some form of indentation. You do it in code, and you should do it in your batch scripts.

Also, you should also get in the habit of always quoting your file names, and getting the quoting right. There is some verbiage under HELP FOR and HELP SET that will help you with removing extra quotes when re-quoting strings.

Edit

From your comments, and re-reading your original question, it seems like you want to build a comma separated list of files that exist. For this case, you could simply use a bunch of if/else statements, but that would result in a bunch of duplicated logic, and would not be at all clean if you had more than two files.

A better way is to write a sub-routine that checks for a single file's existence, and appends to a variable if the file specified exists. Then just call that subroutine for each file you want to check for:

@ECHO OFF
SETLOCAL

REM Todo: Set global script variables here
CALL :MainScript
GOTO :EOF

REM MainScript()
:MainScript
  SETLOCAL

  CALL :AddIfExists "somefile.txt" "%files%" "files"
  CALL :AddIfExists "someotherfile.txt" "%files%" "files"

  ECHO.Files: %files%

  ENDLOCAL
GOTO :EOF

REM AddIfExists(filename, existingFilenames, returnVariableName)
:AddIfExists
  SETLOCAL

  IF EXIST "%~1" (
    SET "result=%~1"
  ) ELSE (
    SET "result="
  )

  (
    REM Cleanup, and return result - concatenate if necessary
    ENDLOCAL

    IF "%~2"=="" (
      SET "%~3=%result%"
    ) ELSE (
      SET "%~3=%~2,%result%"
    )
  )
GOTO :EOF

Comparing two files in linux terminal

Sort them and use comm:

comm -23 <(sort a.txt) <(sort b.txt)

comm compares (sorted) input files and by default outputs three columns: lines that are unique to a, lines that are unique to b, and lines that are present in both. By specifying -1, -2 and/or -3 you can suppress the corresponding output. Therefore comm -23 a b lists only the entries that are unique to a. I use the <(...) syntax to sort the files on the fly, if they are already sorted you don't need this.

How can I verify a Google authentication API access token?

I need to somehow query Google and ask: Is this access token valid for [email protected]?

No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.

The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.

So you need be from same domain as 'public interface'.

And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.

How to create Select List for Country and States/province in MVC

Designing You Model:

Public class ModelName
{
    ...// Properties
    public IEnumerable<SelectListItem> ListName { get; set; }
}

Prepare and bind List to Model in Controller :

    public ActionResult Index(ModelName model)
    {
        var items = // Your List of data
        model.ListName = items.Select(x=> new SelectListItem() {
                    Text = x.prop,
                    Value = x.prop2
               });
    }

In You View :

@Html.DropDownListFor(m => Model.prop2,Model.ListName)

Keep values selected after form submission

<select name="name">
   <option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>
   <option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option>
</select>

CSS: How to align vertically a "label" and "input" inside a "div"?

I'm aware this question was asked over two years ago, but for any recent viewers, here's an alternative solution, which has a few advantages over Marc-François's solution:

div {
    height: 50px;
    border: 1px solid blue;
    line-height: 50px;
}

Here we simply only add a line-height equal to that of the height of the div. The advantage being you can now change the display property of the div as you see fit, to inline-block for instance, and it's contents will remain vertically centered. The accepted solution requires you treat the div as a table cell. This should work perfectly, cross-browser.

The only other advantage being it's just one more CSS rule instead of two :)

Cheers!

TypeScript: Property does not exist on type '{}'

When you write the following line of code in TypeScript:

var SUCSS = {};

The type of SUCSS is inferred from the assignment (i.e. it is an empty object type).

You then go on to add a property to this type a few lines later:

SUCSS.fadeDiv = //...

And the compiler warns you that there is no property named fadeDiv on the SUCSS object (this kind of warning often helps you to catch a typo).

You can either... fix it by specifying the type of SUCSS (although this will prevent you from assigning {}, which doesn't satisfy the type you want):

var SUCSS : {fadeDiv: () => void;};

Or by assigning the full value in the first place and let TypeScript infer the types:

var SUCSS = {
    fadeDiv: function () {
        // Simplified version
        alert('Called my func');
    }
};

Convert an enum to List<string>

I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:

  public enum CancelReasonsEnum
{
    [Description("In rush")]
    InRush,
    [Description("Need more coffee")]
    NeedMoreCoffee,
    [Description("Call me back in 5 minutes!")]
    In5Minutes
}

In a helper class (HelperMethods) I created the following method:

 public static List<string> GetListOfDescription<T>() where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
    }

When you call this helper you will get the list of item descriptions.

 List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();

ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.

 public static string GetDescription(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            FieldInfo field = type.GetField(name);
            if (field != null)
            {
                DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return null;
        /* how to use
            MyEnum x = MyEnum.NeedMoreCoffee;
            string description = x.GetDescription();
        */

    }

d3.select("#element") not working when code above the html element

Please try this approach. It worked for me.

<head> 
<script  type="text/javascript" src='./d3.v4.min.js'></script>
</head> 

<body>
    <div id="jschart41448" style="color:red">
        Hi red
    </div>

    <div id="jschart41449" style="color:blueviolet">
        Hi blueviolet
    </div>

 <script type="text/javascript"   >
            d3.select("#jschart41448").style('color', 'green' , null);
            d3.select("#jschart41449").style('color', 'yellow', null);
</script>
</body>

What is a Java String's default initial value?

There are three types of variables:

  • Instance variables: are always initialized
  • Static variables: are always initialized
  • Local variables: must be initialized before use

The default values for instance and static variables are the same and depends on the type:

  • Object type (String, Integer, Boolean and others): initialized with null
  • Primitive types:
    • byte, short, int, long: 0
    • float, double: 0.0
    • boolean: false
    • char: '\u0000'

An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.

Once the array is created all of its elements are assiged with the default type value. For example:

private boolean[] list; // default value is null

private Boolean[] list; // default value is null

once is initialized:

private boolean[] list = new boolean[10]; // all ten elements are assigned to false

private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)

Making Enter key on an HTML form submit instead of activating button

I just hit a problem with this. Mine was a fall off from changing the input to a button and I'd had a badly written /> tag terminator:

So I had:

<button name="submit_login" type="submit" class="login" />Login</button>

And have just amended it to:

<button name="submit_login" type="submit" class="login">Login</button>

Now works like a charm, always the annoying small things... HTH

How do I generate a stream from a string?

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

public static class StringExtensions {

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

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

Decimal separator comma (',') with numberDecimal inputType in EditText

I decided to change comma to dot only while editing. Here is my tricky and relative simple workaround:

    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            EditText editText = (EditText) v; 
            String text = editText.getText().toString();
            if (hasFocus) {
                editText.setText(text.replace(",", "."));
            } else {
                if (!text.isEmpty()) {
                    Double doubleValue = Double.valueOf(text.replace(",", "."));
                    editText.setText(someDecimalFormatter.format(doubleValue));
                }
            }
        }
    });

someDecimalFormatter will use comma or dot depends on Locale

What is SELF JOIN and when would you use it?

You'd use a self-join on a table that "refers" to itself - e.g. a table of employees where managerid is a foreign-key to employeeid on that same table.

Example:

SELECT E.name, ME.name AS manager
FROM dbo.Employees E
LEFT JOIN dbo.Employees ME
ON ME.employeeid = E.managerid

Vuex - Computed property "name" was assigned to but it has no setter

I was facing exact same error

Computed property "callRingtatus" was assigned to but it has no setter

here is a sample code according to my scenario

computed: {

callRingtatus(){
            return this.$store.getters['chat/callState']===2
      }

}

I change the above code into the following way

computed: {

callRingtatus(){
       return this.$store.state.chat.callState===2
    }
}

fetch values from vuex store state instead of getters inside the computed hook

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

Incidentally, .ogv files are video, so "video/ogg", .ogg files are Vorbis audio, so "audio/ogg" and .oga files are general Ogg audio, so also "audio/ogg". Checked in Firefox and work. "application/ogg" is deprecated for all audio or video uses. See http://www.rfc-editor.org/rfc/rfc5334.txt