Programs & Examples On #Metapost

Anything related to MetaPost language and associated tools. MetaPost is a picture-drawing language used to generate figures for documents to be printed on PostScript printers, either directly or embedded in (La)TeX documents.

ssh connection refused on Raspberry Pi

I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.

Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.

How can I implement prepend and append with regular JavaScript?

Perhaps you're asking about the DOM methods appendChild and insertBefore.

parentNode.insertBefore(newChild, refChild)

Inserts the node newChild as a child of parentNode before the existing child node refChild. (Returns newChild.)

If refChild is null, newChild is added at the end of the list of children. Equivalently, and more readably, use parentNode.appendChild(newChild).

Changing iframe src with Javascript

You can solve it by making the iframe in javascript

_x000D_
_x000D_
  document.write(" <iframe  id='frame' name='frame' src='" + srcstring + "' width='600'  height='315'   allowfullscreen></iframe>");
_x000D_
_x000D_
_x000D_

Create an array with same element repeated multiple times

Use this function:

function repeatElement(element, count) {
    return Array(count).fill(element)
}
>>> repeatElement('#', 5).join('')
"#####"

Or for a more compact version:

const repeatElement = (element, count) =>
    Array(count).fill(element)
>>> repeatElement('#', 5).join('')
"#####"

Or for a curry-able version:

const repeatElement = element => count =>
    Array(count).fill(element)
>>> repeatElement('#')(5).join('')
"#####"

You can use this function with a list:

const repeatElement = (element, count) =>
    Array(count).fill(element)

>>> ['a', 'b', ...repeatElement('c', 5)]
['a', 'b', 'c', 'c', 'c', 'c', 'c']

Spring Boot default H2 jdbc connection (and H2 console)

I found that with spring boot 2.0.2.RELEASE, configuring spring-boot-starter-data-jpa and com.h2database in the POM file is not just enough to have H2 console working. You must configure spring-boot-devtools as below. Optionally you could follow the instruction from Aaron Zeckoski in this post

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
 </dependency>

How to upload a file and JSON data in Postman?

In postman, set method type to POST.

Then select Body -> form-data -> Enter your parameter name (file according to your code)

and on right side next to value column, there will be dropdown "text, file", select File. choose your image file and post it.

For rest of "text" based parameters, you can post it like normally you do with postman. Just enter parameter name and select "text" from that right side dropdown menu and enter any value for it, hit send button. Your controller method should get called.

How to show PIL images on the screen?

I tested this and it works fine for me:

from PIL import Image
im = Image.open('image.jpg')
im.show()

CSS Animation and Display None

CSS (or jQuery, for that matter) can't animate between display: none; and display: block;. Worse yet: it can't animate between height: 0 and height: auto. So you need to hard code the height (if you can't hard code the values then you need to use javascript, but this is an entirely different question);

#main-image{
    height: 0;
    overflow: hidden;
    background: red;
   -prefix-animation: slide 1s ease 3.5s forwards;
}

@-prefix-keyframes slide {
  from {height: 0;}
  to {height: 300px;}
}

You mention that you're using Animate.css, which I'm not familiar with, so this is a vanilla CSS.

You can see a demo here: http://jsfiddle.net/duopixel/qD5XX/

Get most recent row for given ID

Building on @xQbert's answer's, you can avoid the subquery AND make it generic enough to filter by any ID

SELECT id, signin, signout
FROM dTable
INNER JOIN(
  SELECT id, MAX(signin) AS signin
  FROM dTable
  GROUP BY id
) AS t1 USING(id, signin)

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Amazon S3 exception: "The specified key does not exist"

I encountered this issue in a NodeJS Lambda function that was triggered by a file upload to S3.

My mistake was that I was not decoding the object key, which contained a colon. Corrected my code as follows:

let key = decodeURIComponent(event.Records[0].s3.object.key);

What is __declspec and when do I need to use it?

Another example to illustrate the __declspec keyword:

When you are writing a Windows Kernel Driver, sometimes you want to write your own prolog/epilog code sequences using inline assembler code, so you could declare your function with the naked attribute.

__declspec( naked ) int func( formal_parameters ) {}

Or

#define Naked __declspec( naked )
Naked int func( formal_parameters ) {}

Please refer to naked (C++)

Remove all whitespace from C# string with regex

Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.

                       new string
                           (stringToRemoveWhiteSpaces
                                .Where
                                (
                                    c => !char.IsWhiteSpace(c)
                                )
                                .ToArray<char>()
                           )

OR

                       new string
                           (stringToReplaceWhiteSpacesWithSpace
                                .Select
                                (
                                    c => char.IsWhiteSpace(c) ? ' ' : c
                                )
                                .ToArray<char>()
                           )

What is a simple command line program or script to backup SQL server databases?

You could use a VB Script I wrote exactly for this purpose: https://github.com/ezrarieben/mssql-backup-vbs/

Schedule a task in the "Task Scheduler" to execute the script as you like and it'll backup the entire DB to a BAK file and save it wherever you specify.

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

You can press I twice to interrupt the kernel.

This only works if you're in Command mode. If not already enabled, press Esc to enable it.

node.js - how to write an array to file

We can simply write the array data to the filesystem but this will raise one error in which ',' will be appended to the end of the file. To handle this below code can be used:

var fs = require('fs');

var file = fs.createWriteStream('hello.txt');
file.on('error', function(err) { Console.log(err) });
data.forEach(value => file.write(`${value}\r\n`));
file.end();

\r\n

is used for the new Line.

\n

won't help. Please refer this

Android Studio not showing modules in project structure

Please go to Module settings and choose Modules from Project Settings then you need to Select src and gen folders and marked them as Source folders by right-click on them and select Source

Submit form using <a> tag

Clean and simple:

  <form action="/myaction" method="post" target="_blank">
    <!-- other elements -->
    <a href="#" onclick="this.parentNode.submit();">Submit</a>
 </form>

In case of opening form action url in a new tab (target="_blank"):

  <form action="/myaction" method="post" target="_blank">
    <!-- other elements -->
    <a href="#" onclick="this.parentNode.submit();">Submit</a>
 </form>

comparing elements of the same array in java

Try this or purpose will solve with lesser no of steps

for (int i = 0; i < a.length; i++) 
{
    for (int k = i+1; k < a.length; k++) 
    {
        if (a[i] != a[k]) 
         {
            System.out.println(a[i]+"not the same with"+a[k]+"\n");
        }
    }
}

MySQL Cannot Add Foreign Key Constraint

Try to use the same type of your primary keys - int(11) - on the foreign keys - smallint(5) - as well.

Hope it helps!

How to convert datetime format to date format in crystal report using C#?

Sometimes the field is not recognized by crystal reports as DATE, so you can add a formula with function: Date({YourField}), And add it to the report, now when you open the format object dialog you will find the date formatting options.

Python: Making a beep noise

Linux.

$ apt-get install beep

$ python
>>> os.system("beep -f 555 -l 460")

OR

$ beep -f 659 -l 460 -n -f 784 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 880 -l 230 -n -f 659 -l 230 -n -f 587 -l 230 -n -f 659 -l 460 -n -f 988 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 1047-l 230 -n -f 988 -l 230 -n -f 784 -l 230 -n -f 659 -l 230 -n -f 988 -l 230 -n -f 1318 -l 230 -n -f 659 -l 110 -n -f 587 -l 230 -n -f 587 -l 110 -n -f 494 -l 230 -n -f 740 -l 230 -n -f 659 -l 460

Best Way to do Columns in HTML/CSS

If you want to do multiple (3+) columns here is a great snippet that works perfectly and validates as valid HTML5:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Multiple Colums</title>

        <!-- Styles -->
        <style>
            .flex-center {
                width: 100%;
                align-items: center;/*These two properties center vetically*/
                height: 100vh;/*These two properties center vetically*/
                display: flex;/*This is the attribute that separates into columns*/
                justify-content: center;
                text-align: center;
                position: relative;
            }
            .spaceOut {
                margin-left: 25px;
                margin-right: 25px;
            }
        </style>

    </head>
    <body>
        <section class="flex-center">
            <h4>Tableless Columns Example</h4><br />
            <div class="spaceOut">
                Column 1<br />
            </div>
            <div class="spaceOut">
                Column 2<br />
            </div>
            <div class="spaceOut">
                Column 3<br />
            </div>      
            <div class="spaceOut">
                Column 4<br />
            </div>
            <div class="spaceOut">
                Column 5<br />
            </div>
        </section>
    </body>
</html>

Simple file write function in C++

Your main doesn't know about writeFile() and can't call it.

Move writefile to be before main, or declare a function prototype int writeFile(); before main.

How can I override Bootstrap CSS styles?

To reset the styles defined for legend in bootstrap, you can do following in your css file:

legend {
  all: unset;
}

Ref: https://css-tricks.com/almanac/properties/a/all/

The all property in CSS resets all of the selected element's properties, except the direction and unicode-bidi properties that control text direction.

Possible values are: initial, inherit & unset.

Side note: clear property is used in relation with float (https://css-tricks.com/almanac/properties/c/clear/)

Python object deleting itself

I can't tell you how this is possible with classes, but functions can delete themselves.

def kill_self(exit_msg = 'killed'):
    global kill_self
    del kill_self
    return exit_msg

And see the output:

 >>> kill_self
<function kill_self at 0x02A2C780>
>>> kill_self()
'killed'
>>> kill_self
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    kill_self
NameError: name 'kill_self' is not defined

I don't think that deleting an individual instance of a class without knowing the name of it is possible.

NOTE: If you assign another name to the function, the other name will still reference the old one, but will cause errors once you attempt to run it:

>>> x = kill_self
>>> kill_self()
>>> kill_self
NameError: name 'kill_self' is not defined
>>> x
<function kill_self at 0x...>
>>> x()
NameError: global name 'kill_self' is not defined

How can I backup a remote SQL Server database to a local drive?

For 2019, I would recommend using mssql-scripter if you want an actual local backup. Yes it's scripts but you can adjust it to include whatever you want, which can include all of the data. I wrote a bash script to do automated daily backups using this on a linux machine. Checkout my gist:

https://gist.github.com/tjmoses/45ee6b3046be280c9daa23b0f610f407

pytest cannot import module while python can

I had a similar issue, exact same error, but different cause. I was running the test code just fine, but against an old version of the module. In the previous version of my code one class existed, while the other did not. After updating my code, I should have run the following to install it.

sudo pip install ./ --upgrade

Upon installing the updated module running pytest produced the correct results (because i was using the correct code base).

Dynamically changing font size of UILabel

This solution works for multiline:

After following several articles, and requiring a function that would automatically scale the text and adjust the line count to best fit within the given label size, I wrote a function myself. (ie. a short string would fit nicely on one line and use a large amount of the label frame, whereas a long strong would automatically split onto 2 or 3 lines and adjust the size accordingly)

Feel free to re-use it and tweak as required. Make sure you call it after viewDidLayoutSubviews has finished so that the initial label frame has been set.

+ (void)setFontForLabel:(UILabel *)label withMaximumFontSize:(float)maxFontSize andMaximumLines:(int)maxLines {
    int numLines = 1;
    float fontSize = maxFontSize;
    CGSize textSize; // The size of the text
    CGSize frameSize; // The size of the frame of the label
    CGSize unrestrictedFrameSize; // The size the text would be if it were not restricted by the label height
    CGRect originalLabelFrame = label.frame;

    frameSize = label.frame.size;
    textSize = [label.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize: fontSize]}];

    // Work out the number of lines that will need to fit the text in snug
    while (((textSize.width / numLines) / (textSize.height * numLines) > frameSize.width / frameSize.height) && (numLines < maxLines)) {
        numLines++;
    }

    label.numberOfLines = numLines;

    // Get the current text size
    label.font = [UIFont systemFontOfSize:fontSize];
    textSize = [label.text boundingRectWithSize:CGSizeMake(frameSize.width, CGFLOAT_MAX)
                                        options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                     attributes:@{NSFontAttributeName : label.font}
                                        context:nil].size;

    // Adjust the frame size so that it can fit text on more lines
    // so that we do not end up with truncated text
    label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width, label.frame.size.width);

    // Get the size of the text as it would fit into the extended label size
    unrestrictedFrameSize = [label textRectForBounds:CGRectMake(0, 0, label.bounds.size.width, CGFLOAT_MAX) limitedToNumberOfLines:numLines].size;

    // Keep reducing the font size until it fits
    while (textSize.width > unrestrictedFrameSize.width || textSize.height > frameSize.height) {
        fontSize--;
        label.font = [UIFont systemFontOfSize:fontSize];
        textSize = [label.text boundingRectWithSize:CGSizeMake(frameSize.width, CGFLOAT_MAX)
                                            options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                         attributes:@{NSFontAttributeName : label.font}
                                            context:nil].size;
        unrestrictedFrameSize = [label textRectForBounds:CGRectMake(0, 0, label.bounds.size.width, CGFLOAT_MAX) limitedToNumberOfLines:numLines].size;
    }

    // Set the label frame size back to original
    label.frame = originalLabelFrame;
}

Replacing &nbsp; from javascript dom text node

If you only need to replace &nbsp; then you can use a far simpler regex:

var textWithNBSpaceReplaced = originalText.replace(/&nbsp;/g, ' ');

Also, there is a typo in your div example, it says &nnbsp; instead of &nbsp;.

Delete everything in a MongoDB database

  1. List out all available dbs show dbs
  2. Choose the necessary db use
  3. Drop the database db.dropDatabase() //Few additional commands
  4. List all collections available in a db show collections
  5. Remove a specification collection db.collection.drop()

Hope that helps

Debug JavaScript in Eclipse

I'm not a 100% sure but I think Aptana let's you do that.

can not find module "@angular/material"

import {MatButtonModule} from '@angular/material/button';

Converts scss to css

You can use sass /sassFile.scss /cssFile.css

Attention: Before using sass command you must install ruby and then install sass.

For installing sass, after ruby installation type gem install sass in your Terminal

Hint: sass compile SCSS files

How do I convert a dictionary to a JSON String in C#?

Sorry if the syntax is the tiniest bit off, but the code I'm getting this from was originally in VB :)

using System.Web.Script.Serialization;

...

Dictionary<int,List<int>> MyObj = new Dictionary<int,List<int>>();

//Populate it here...

string myJsonString = (new JavaScriptSerializer()).Serialize(MyObj);

restart mysql server on windows 7

First try:

net stop MySQL   
net start MySQL

If that does not work, try using the windows interface:

Start > Control Panel > System and Security > Administrative Tools > Services

Look for your version of MySQL (In my case - MySQL55), highlight and click the green start arrow. The status should change to "Started"

What is the meaning of the word logits in TensorFlow?

Here is a concise answer for future readers. Tensorflow's logit is defined as the output of a neuron without applying activation function:

logit = w*x + b,

x: input, w: weight, b: bias. That's it.


The following is irrelevant to this question.

For historical lectures, read other answers. Hats off to Tensorflow's "creatively" confusing naming convention. In PyTorch, there is only one CrossEntropyLoss and it accepts un-activated outputs. Convolutions, matrix multiplications and activations are same level operations. The design is much more modular and less confusing. This is one of the reasons why I switched from Tensorflow to PyTorch.

What does "TypeError 'xxx' object is not callable" means?

I came across this error message through a silly mistake. A classic example of Python giving you plenty of room to make a fool of yourself. Observe:

class DOH(object):
def __init__(self, property=None):
    self.property=property

def property():
    return property

x = DOH(1)
print(x.property())

Results

$ python3 t.py
Traceback (most recent call last):
  File "t.py", line 9, in <module>
    print(x.property())
TypeError: 'int' object is not callable

The problem here of course is that the function is overwritten with a property.

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

As there might be a number of operations to do on an ObservableCollection for example Clear first then AddRange and then insert "All" item for a ComboBox I ended up with folowing solution:

public static class LinqExtensions
{
    public static ICollection<T> AddRange<T>(this ICollection<T> source, IEnumerable<T> addSource)
    {
        foreach(T item in addSource)
        {
            source.Add(item);
        }

        return source;
    }
}

public class ExtendedObservableCollection<T>: ObservableCollection<T>
{
    public void Execute(Action<IList<T>> itemsAction)
    {
        itemsAction(Items);
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

And example how to use it:

MyDogs.Execute(items =>
{
    items.Clear();
    items.AddRange(Context.Dogs);
    items.Insert(0, new Dog { Id = 0, Name = "All Dogs" });
});

The Reset notification will be called only once after Execute is finished processing the underlying list.

Pandas: how to change all the values of a column?

Or if one want to use lambda function in the apply function:

data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))

How to read numbers from file in Python?

Not sure why do you need w,h. If these values are actually required and mean that only specified number of rows and cols should be read than you can try the following:

output = []
with open(r'c:\file.txt', 'r') as f:
    w, h  = map(int, f.readline().split())
    tmp = []
    for i, line in enumerate(f):
        if i == h:
            break
        tmp.append(map(int, line.split()[:w]))
    output.append(tmp)

Error : Index was outside the bounds of the array.

You have declared an array that can store 8 elements not 9.

this.posStatus = new int[8]; 

It means postStatus will contain 8 elements from index 0 to 7.

How to add a scrollbar to an HTML5 table?

@jogesh_pi answer is a good solution, i've created a example here http://jsfiddle.net/pqgaS/5/, check it, hope this help

<div id="listtableWrapperScroll">
    <table id="listtable">
        <tr>
            <td>Data Data</td>
            <td>Data Data</td>
            <td>Data Data</td>                
        </tr>
    </table>
</div>

#listtableWrapperScroll{
    height:100px;
    width:460px;
    overflow-y:scroll;
    border:1px solid #777777;
    background:#FFFFF2;
}
#listtableWrapperScroll #listtable{
    width:440px;       
}
#listtableWrapperScroll #listtable tr td{
    border-bottom:1px dashed #444;
}

curl_exec() always returns false

This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen from the copied link was in a different encoding and hence the curl_exec() was always returning false because it was unable to communicate with the server.

It took me a couple hours to finally understand the diference in the characters bellow:

https://www.e-example.com/api
https://www.e-example.com/api

Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api.

It may seem to you that they are equal but if you check the encoding of the hyphens here you'll see that the first hyphen is a unicode characters U+2010 and the other is a U+002D.

Hope this helps someone.

How to count the number of occurrences of an element in a List

I didn't want to make this case more difficult and made it with two iterators I have a HashMap with LastName -> FirstName. And my method should delete items with dulicate FirstName.

public static void removeTheFirstNameDuplicates(HashMap<String, String> map)
{

    Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
    Iterator<Map.Entry<String, String>> iter2 = map.entrySet().iterator();
    while(iter.hasNext())
    {
        Map.Entry<String, String> pair = iter.next();
        String name = pair.getValue();
        int i = 0;

        while(iter2.hasNext())
        {

            Map.Entry<String, String> nextPair = iter2.next();
            if (nextPair.getValue().equals(name))
                i++;
        }

        if (i > 1)
            iter.remove();

    }

}

How to install libusb in Ubuntu

First,

sudo apt-get install libusb-1.0-0-dev

updatedb && locate libusb.h.

Second, replace <libusb.h> with <libusb-1.0/libusb.h>.

update:

don't need to change any file.just add this to your Makefile.

`pkg-config libusb-1.0 --libs --cflags`

its result is that -I/usr/include/libusb-1.0 -lusb-1.0

Running Selenium Webdriver with a proxy in Python

If anyone is looking for a solution here's how :

from selenium import webdriver
PROXY = "YOUR_PROXY_ADDRESS_HERE"
webdriver.DesiredCapabilities.FIREFOX['proxy']={
    "httpProxy":PROXY,
    "ftpProxy":PROXY,
    "sslProxy":PROXY,
    "noProxy":None,
    "proxyType":"MANUAL",
    "autodetect":False
}
driver = webdriver.Firefox()
driver.get('http://www.whatsmyip.org/')

Validating URL in Java

Thanks. Opening the URL connection by passing the Proxy as suggested by NickDK works fine.

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

System properties however doesn't work as I had mentioned earlier.

Thanks again.

Regards, Keya

How to prevent default event handling in an onclick method?

You can catch the event and then block it with preventDefault() -- works with pure Javascript

document.getElementById("xyz").addEventListener('click', function(event){
    event.preventDefault();
    console.log(this.getAttribute("href"));
    /* Do some other things*/
});

Equivalent of Clean & build in Android Studio?

reed these links

http://tools.android.com/tech-docs/new-build-system/version-compatibility https://developer.android.com/studio/releases/gradle-plugin.html

in android studio version 2+, use this in gradle config

android{
..

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
        incremental = false;
}
...

}

after 3 days of search and test :(, this solve "rebuild for any run"

Getting number of elements in an iterator in Python

A quick benchmark:

import collections
import itertools

def count_iter_items(iterable):
    counter = itertools.count()
    collections.deque(itertools.izip(iterable, counter), maxlen=0)
    return next(counter)

def count_lencheck(iterable):
    if hasattr(iterable, '__len__'):
        return len(iterable)

    d = collections.deque(enumerate(iterable, 1), maxlen=1)
    return d[0][0] if d else 0

def count_sum(iterable):           
    return sum(1 for _ in iterable)

iter = lambda y: (x for x in xrange(y))

%timeit count_iter_items(iter(1000))
%timeit count_lencheck(iter(1000))
%timeit count_sum(iter(1000))

The results:

10000 loops, best of 3: 37.2 µs per loop
10000 loops, best of 3: 47.6 µs per loop
10000 loops, best of 3: 61 µs per loop

I.e. the simple count_iter_items is the way to go.

Adjusting this for python3:

61.9 µs ± 275 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
74.4 µs ± 190 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
82.6 µs ± 164 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Any reason to prefer getClass() over instanceof when generating .equals()?

instanceof works for instences of the same class or its subclasses

You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

ArryaList and RoleList are both instanceof List

While

getClass() == o.getClass() will be true only if both objects ( this and o ) belongs to exactly the same class.

So depending on what you need to compare you could use one or the other.

If your logic is: "One objects is equals to other only if they are both the same class" you should go for the "equals", which I think is most of the cases.

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

Spark - SELECT WHERE or filtering?

As Yaron mentioned, there isn't any difference between where and filter.

filter is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.

filter overloaded method

We can use explain() to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name and person_country columns. All of the following code snippets will return the same Physical Plan below:

df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()

These all return this Physical Plan:

== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
   +- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>

The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.

Pattern matching using a wildcard

You can also use package data.table and it's Like function, details given below How to select R data.table rows based on substring match (a la SQL like)

Display the binary representation of a number in C?

Yes (write your own), something like the following complete function.

#include <stdio.h> /* only needed for the printf() in main(). */
#include <string.h>

/* Create a string of binary digits based on the input value.
   Input:
       val:  value to convert.
       buff: buffer to write to must be >= sz+1 chars.
       sz:   size of buffer.
   Returns address of string or NULL if not enough space provided.
*/
static char *binrep (unsigned int val, char *buff, int sz) {
    char *pbuff = buff;

    /* Must be able to store one character at least. */
    if (sz < 1) return NULL;

    /* Special case for zero to ensure some output. */
    if (val == 0) {
        *pbuff++ = '0';
        *pbuff = '\0';
        return buff;
    }

    /* Work from the end of the buffer back. */
    pbuff += sz;
    *pbuff-- = '\0';

    /* For each bit (going backwards) store character. */
    while (val != 0) {
        if (sz-- == 0) return NULL;
        *pbuff-- = ((val & 1) == 1) ? '1' : '0';

        /* Get next bit. */
        val >>= 1;
    }
    return pbuff+1;
}

Add this main to the end of it to see it in operation:

#define SZ 32
int main(int argc, char *argv[]) {
    int i;
    int n;
    char buff[SZ+1];

    /* Process all arguments, outputting their binary. */
    for (i = 1; i < argc; i++) {
        n = atoi (argv[i]);
        printf("[%3d] %9d -> %s (from '%s')\n", i, n,
            binrep(n,buff,SZ), argv[i]);
    }

    return 0;
}

Run it with "progname 0 7 12 52 123" to get:

[  1]         0 -> 0 (from '0')
[  2]         7 -> 111 (from '7')
[  3]        12 -> 1100 (from '12')
[  4]        52 -> 110100 (from '52')
[  5]       123 -> 1111011 (from '123')

SQL like search string starts with

You need to use the wildcard % :

SELECT * from games WHERE (lower(title) LIKE 'age of empires III%');

Pylint, PyChecker or PyFlakes?

pep8 was recently added to PyPi.

  • pep8 - Python style guide checker
  • pep8 is a tool to check your Python code against some of the style conventions in PEP 8.

It is now super easy to check your code against pep8.

See http://pypi.python.org/pypi/pep8

Relative frequencies / proportions with dplyr

For the sake of completeness of this popular question, since version 1.0.0 of dplyr, parameter .groups controls the grouping structure of the summarise function after group_by summarise help.

With .groups = "drop_last", summarise drops the last level of grouping. This was the only result obtained before version 1.0.0.

library(dplyr)
library(scales)

original <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n()) %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)

original
#> # A tibble: 4 x 4
#> # Groups:   am [2]
#>      am  gear     n rel.freq
#>   <dbl> <dbl> <int> <chr>   
#> 1     0     3    15 78.9%   
#> 2     0     4     4 21.1%   
#> 3     1     4     8 61.5%   
#> 4     1     5     5 38.5%

new_drop_last <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n(), .groups = "drop_last") %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))

dplyr::all_equal(original, new_drop_last)
#> [1] TRUE

With .groups = "drop", all levels of grouping are dropped. The result is turned into an independent tibble with no trace of the previous group_by

# .groups = "drop"
new_drop <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n(), .groups = "drop") %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))

new_drop
#> # A tibble: 4 x 4
#>      am  gear     n rel.freq
#>   <dbl> <dbl> <int> <chr>   
#> 1     0     3    15 46.9%   
#> 2     0     4     4 12.5%   
#> 3     1     4     8 25.0%   
#> 4     1     5     5 15.6%

If .groups = "keep", same grouping structure as .data (mtcars, in this case). summarise does not peel off any variable used in the group_by.

Finally, with .groups = "rowwise", each row is it's own group. It is equivalent to "keep" in this situation

# .groups = "keep"
new_keep <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n(), .groups = "keep") %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))

new_keep
#> # A tibble: 4 x 4
#> # Groups:   am, gear [4]
#>      am  gear     n rel.freq
#>   <dbl> <dbl> <int> <chr>   
#> 1     0     3    15 100.0%  
#> 2     0     4     4 100.0%  
#> 3     1     4     8 100.0%  
#> 4     1     5     5 100.0%

# .groups = "rowwise"
new_rowwise <- mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n(), .groups = "rowwise") %>%
  mutate(rel.freq =  scales::percent(n/sum(n), accuracy = 0.1))

dplyr::all_equal(new_keep, new_rowwise)
#> [1] TRUE

Another point that can be of interest is that sometimes, after applying group_by and summarise, a summary line can help.

# create a subtotal line to help readability
subtotal_am <- mtcars %>%
  group_by (am) %>% 
  summarise (n=n()) %>%
  mutate(gear = NA, rel.freq = 1)
#> `summarise()` ungrouping output (override with `.groups` argument)

mtcars %>% group_by (am, gear) %>%
  summarise (n=n()) %>% 
  mutate(rel.freq = n/sum(n)) %>%
  bind_rows(subtotal_am) %>%
  arrange(am, gear) %>%
  mutate(rel.freq =  scales::percent(rel.freq, accuracy = 0.1))
#> `summarise()` regrouping output by 'am' (override with `.groups` argument)
#> # A tibble: 6 x 4
#> # Groups:   am [2]
#>      am  gear     n rel.freq
#>   <dbl> <dbl> <int> <chr>   
#> 1     0     3    15 78.9%   
#> 2     0     4     4 21.1%   
#> 3     0    NA    19 100.0%  
#> 4     1     4     8 61.5%   
#> 5     1     5     5 38.5%   
#> 6     1    NA    13 100.0%

Created on 2020-11-09 by the reprex package (v0.3.0)

Hope you find this answer useful.

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

OK, I've worked out what's going on. Leonidas is right, it's not just the hash that gets encrypted (in the case of the Cipher class method), it's the ID of the hash algorithm concatenated with the digest:

  DigestInfo ::= SEQUENCE {
      digestAlgorithm AlgorithmIdentifier,
      digest OCTET STRING
  }

Which is why the encryption by the Cipher and Signature are different.

Launch Image does not show up in my iOS App

My solution was to create all the launch images. enter image description here

Then I set the Launch Images Source to the LaunchImage asset, and leave launch screen file blank.

Finally if the project does not have a Launch Screen.xib, then add that file and leave it as is. enter image description here

Python 'If not' syntax

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

Getting msbuild.exe without installing Visual Studio

It used to be installed with the .NET framework. MsBuild v12.0 (2013) is now bundled as a stand-alone utility and has it's own installer.

http://www.microsoft.com/en-us/download/confirmation.aspx?id=40760

To reference the location of MsBuild.exe from within an MsBuild script, use the default $(MsBuildToolsPath) property.

Uncaught (in promise) TypeError: Failed to fetch and Cors error

In my case, the problem was the protocol. I was trying to call a script url with http instead of https.

How to get full REST request body using Jersey?

Since you're transferring data in xml, you could also (un)marshal directly from/to pojos.

There's an example (and more info) in the jersey user guide, which I copy here:

POJO with JAXB annotations:

@XmlRootElement
public class Planet {
    public int id;
    public String name;
    public double radius;
}

Resource:

@Path("planet")
public class Resource {

    @GET
    @Produces(MediaType.APPLICATION_XML)
    public Planet getPlanet() {
        Planet p = new Planet();
        p.id = 1;
        p.name = "Earth";
        p.radius = 1.0;

        return p;
    }

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    public void setPlanet(Planet p) {
        System.out.println("setPlanet " + p.name);
    }

}      

The xml that gets produced/consumed:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<planet>
    <id>1</id>
    <name>Earth</name>
    <radius>1.0</radius>
</planet>

NULL vs nullptr (Why was it replaced?)

You can find a good explanation of why it was replaced by reading A name for the null pointer: nullptr, to quote the paper:

This problem falls into the following categories:

  • Improve support for library building, by providing a way for users to write less ambiguous code, so that over time library writers will not need to worry about overloading on integral and pointer types.

  • Improve support for generic programming, by making it easier to express both integer 0 and nullptr unambiguously.

  • Make C++ easier to teach and learn.

Addition for BigDecimal

BigDecimal no = new BigDecimal(10); //you can add like this also
no = no.add(new BigDecimal(10));
System.out.println(no);

20

Remove CSS class from element with JavaScript (no jQuery)

document.getElementById("MyID").className =
    document.getElementById("MyID").className.replace(/\bMyClass\b/,'');

where MyID is the ID of the element and MyClass is the name of the class you wish to remove.


UPDATE: To support class names containing dash character, such as "My-Class", use

document.getElementById("MyID").className =
  document.getElementById("MyID").className
    .replace(new RegExp('(?:^|\\s)'+ 'My-Class' + '(?:\\s|$)'), ' ');

7-Zip command to create and extract a password-protected ZIP file on Windows?

From http://www.dotnetperls.com:

7z a secure.7z * -pSECRET

Where:

7z        : name and path of 7-Zip executable
a         : add to archive
secure.7z : name of destination archive
*         : add all files from current directory to destination archive
-pSECRET  : specify the password "SECRET"

To open :

7z x secure.7z

Then provide the SECRET password

Note: If the password contains spaces or special characters, then enclose it with single quotes

7z a secure.7z * -p"pa$$word @|"

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

For python2 you can also do this

'%(author)s in %(publication)s'%{'author':unicode(self.author),
                                  'publication':unicode(self.publication)}

which is handy if you have a lot of arguments to substitute (particularly if you are doing internationalisation)

Python2.6 onwards supports .format()

'{author} in {publication}'.format(author=self.author,
                                   publication=self.publication)

Increase max_execution_time in PHP?

Is very easy, this work for me:

PHP:

set_time_limit(300); // Time in seconds, max_execution_time

Here is the PHP documentation

Any way to select without causing locking in MySQL?

another way to enable dirty read in mysql is add hint: LOCK IN SHARE MODE

SELECT * FROM TABLE_NAME LOCK IN SHARE MODE; 

Media query to detect if device is touchscreen

In 2017, CSS media query from second answer still doesn't work on Firefox. I found a soluton for that: -moz-touch-enabled


So, here is cross-browser media query:

@media (-moz-touch-enabled: 1), (pointer:coarse) {
    .something {
        its: working;
    }
}

JavaScript hide/show element

I would suggest this to hide elements (as others have suggested):

document.getElementById(id).style.display = 'none';

But to make elements visible, I'd suggest this (instead of display = 'block'):

document.getElementById(id).style.display = '';

The reason is that using display = 'block' is causing additional margin/whitespace next to the element being made visible in both IE (11) and Chrome (Version 43.0.2357.130 m) on the page I'm working on.

When you first load a page in Chrome, an element without a style attribute will appear like this in the DOM inspector:

element.style {
}

Hiding it using the standard JavaScript makes it this, as expected:

element.style {
  display: none;
}

Making it visible again using display = 'block' changes it to this:

element.style {
  display: block;
}

Which is not the same as it originally was. This could very well not make any difference in the majority of cases. But in some cases, it does introduce abnormalities.

Using display = '' does restore it to its original state in the DOM inspector, so it seems like the better approach.

What is the Swift equivalent of isEqualToString in Objective-C?

Use == operator instead of isEqual

Comparing Strings

Swift provides three ways to compare String values: string equality, prefix equality, and suffix equality.

String Equality

Two String values are considered equal if they contain exactly the same characters in the same order:

let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
    println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
.
.
.

For more read official documentation of Swift (search Comparing Strings).

Get an object attribute

You can do the following:

class User(object):
    fullName = "John Doe"

    def __init__(self, name):
        self.SName = name

    def print_names(self):
        print "Names: full name: '%s', name: '%s'" % (self.fullName, self.SName)

user = User('Test Name')

user.fullName # "John Doe"
user.SName # 'Test Name'
user.print_names() # will print you Names: full name: 'John Doe', name: 'Test Name'

E.g any object attributes could be retrieved using istance.

Single Page Application: advantages and disadvantages

In my development I found two distinct advantages for using an SPA. That is not to say that the following can not be achieved in a traditional web app just that I see incremental benefit without introducing additional disadvantages.

  • Potential for less server request as rendering new content isn’t always or even ever an http server request for a new html page. But I say potential because new content could easily require an Ajax call to pull in data but that data could be incrementally lighter than the itself plus markup providing a net benefit.

  • The ability to maintain “State”. In its simplest terms, set a variable on entry to the app and it will be available to other components throughout the user’s experience without passing it around or setting it to a local storage pattern. Intelligently managing this ability however is key to keep the top level scope uncluttered.

Other than requiring JS (which is not a crazy thing to require of web apps) other noted disadvantages are in my opinion either not specific to SPA or can be mitigated through good habits and development patterns.

How to Automatically Start a Download in PHP?

A clean example.

<?php
    header('Content-Type: application/download');
    header('Content-Disposition: attachment; filename="example.txt"');
    header("Content-Length: " . filesize("example.txt"));

    $fp = fopen("example.txt", "r");
    fpassthru($fp);
    fclose($fp);
?>

How to save RecyclerView's scroll position using RecyclerView.State?

I Set variables in onCreate(), save scroll position in onPause() and set scroll position in onResume()

public static int index = -1;
public static int top = -1;
LinearLayoutManager mLayoutManager;

@Override
public void onCreate(Bundle savedInstanceState)
{
    //Set Variables
    super.onCreate(savedInstanceState);
    cRecyclerView = ( RecyclerView )findViewById(R.id.conv_recycler);
    mLayoutManager = new LinearLayoutManager(this);
    cRecyclerView.setHasFixedSize(true);
    cRecyclerView.setLayoutManager(mLayoutManager);

}

@Override
public void onPause()
{
    super.onPause();
    //read current recyclerview position
    index = mLayoutManager.findFirstVisibleItemPosition();
    View v = cRecyclerView.getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - cRecyclerView.getPaddingTop());
}

@Override
public void onResume()
{
    super.onResume();
    //set recyclerview position
    if(index != -1)
    {
        mLayoutManager.scrollToPositionWithOffset( index, top);
    }
}

How to select the rows with maximum values in each group with dplyr?

You can use top_n

df %>% group_by(A, B) %>% top_n(n=1)

This will rank by the last column (value) and return the top n=1 rows.

Currently, you can't change the this default without causing an error (See https://github.com/hadley/dplyr/issues/426)

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

This worked for me, Thanks to ungalcrys

Show keyboard:

editText = (EditText)findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);

Hide keyboard:

InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

How to start an application without waiting in a batch file?

I'm making a guess here, but your start invocation probably looks like this:

start "\Foo\Bar\Path with spaces in it\program.exe"

This will open a new console window, using “\Foo\Bar\Path with spaces in it\program.exe” as its title.

If you use start with something that is (or needs to be) surrounded by quotes, you need to put empty quotes as the first argument:

start "" "\Foo\Bar\Path with spaces in it\program.exe"

This is because start interprets the first quoted argument it finds as the window title for a new console window.

How can I limit the visible options in an HTML <select> dropdown?

It is not possible to limit the number of visible elements in the select dropdown (if you use it as dropdown box and not as list).

But you could use javascript/jQuery to replace this selectbox with something else, which just looks like a dropdown box. Then you can handle the height of dropdown as you want.

jNice would be a jQuery plugin which has such features. But there also exists many alternatives for that.

jQuery add image inside of div tag

var img;
for (var i = 0; i < jQuery('.MulImage').length; i++) {
                var imgsrc = jQuery('.MulImage')[i];
                var CurrentImgSrc = imgsrc.src;
                img = jQuery('<img class="dynamic" style="width:100%;">');
                img.attr('src', CurrentImgSrc);
                jQuery('.YourDivClass').append(img);

            }

How to plot multiple functions on the same figure, in Matplotlib?

To plot multiple graphs on the same figure you will have to do:

from numpy import *
import math
import matplotlib.pyplot as plt

t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b

plt.plot(t, a, 'r') # plotting t, a separately 
plt.plot(t, b, 'b') # plotting t, b separately 
plt.plot(t, c, 'g') # plotting t, c separately 
plt.show()

enter image description here

Why is "cursor:pointer" effect in CSS not working

Also add cursor:hand. Some browsers need that instead.

How to build x86 and/or x64 on Windows from command line with CMAKE?

try use CMAKE_GENERATOR_PLATFORM

e.g.

// x86
cmake -DCMAKE_GENERATOR_PLATFORM=x86 . 

// x64
cmake -DCMAKE_GENERATOR_PLATFORM=x64 . 

how to drop database in sqlite?

If you use SQLiteOpenHelper you can do this

        String myPath = DB_PATH + DB_NAME;
        SQLiteDatabase.deleteDatabase(new File(myPath));

How to listen for changes to a MongoDB collection?

What you are thinking of sounds a lot like triggers. MongoDB does not have any support for triggers, however some people have "rolled their own" using some tricks. The key here is the oplog.

When you run MongoDB in a Replica Set, all of the MongoDB actions are logged to an operations log (known as the oplog). The oplog is basically just a running list of the modifications made to the data. Replicas Sets function by listening to changes on this oplog and then applying the changes locally.

Does this sound familiar?

I cannot detail the whole process here, it is several pages of documentation, but the tools you need are available.

First some write-ups on the oplog - Brief description - Layout of the local collection (which contains the oplog)

You will also want to leverage tailable cursors. These will provide you with a way to listen for changes instead of polling for them. Note that replication uses tailable cursors, so this is a supported feature.

Reading RFID with Android phones

You can use a simple, low-cost USB port reader like this test connects directly to your Android device; it has a utility app and an SDK you can use for app development: https://www.atlasrfidstore.com/sls-rfid-smartmicro-android-micro-usb-reader/

Array versus linked-list

First of all, in C++ linked-lists shouldn't be much more trouble to work with than an array. You can use the std::list or the boost pointer list for linked lists. The key issues with linked lists vs arrays are extra space required for pointers and terrible random access. You should use a linked list if you

  • you don't need random access to the data
  • you will be adding/deleting elements, especially in the middle of the list

php random x digit number

Following is simple method to generate specific length verification code. Length can be specified, by default, it generates 4 digit code.

function get_sms_token($length = 4) {

    return rand(
        ((int) str_pad(1, $length, 0, STR_PAD_RIGHT)),
        ((int) str_pad(9, $length, 9, STR_PAD_RIGHT))
    );
}

echo get_sms_token(6);

Python regex findall

import re
regex = ur"\[P\] (.+?) \[/P\]+?"
line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
person = re.findall(regex, line)
print(person)

yields

['Barack Obama', 'Bill Gates']

The regex ur"[\u005B1P\u005D.+?\u005B\u002FP\u005D]+?" is exactly the same unicode as u'[[1P].+?[/P]]+?' except harder to read.

The first bracketed group [[1P] tells re that any of the characters in the list ['[', '1', 'P'] should match, and similarly with the second bracketed group [/P]].That's not what you want at all. So,

  • Remove the outer enclosing square brackets. (Also remove the stray 1 in front of P.)
  • To protect the literal brackets in [P], escape the brackets with a backslash: \[P\].
  • To return only the words inside the tags, place grouping parentheses around .+?.

Excel how to find values in 1 column exist in the range of values in another

Use the formula by tigeravatar:

=COUNTIF($B$2:$B$5,A2)>0 – tigeravatar Aug 28 '13 at 14:50

as conditional formatting. Highlight column A. Choose conditional formatting by forumula. Enter the formula (above) - this finds values in col B that are also in A. Choose a format (I like to use FILL and a bold color).

To find all of those values, highlight col A. Data > Filter and choose Filter by color.

Regular Expression For Duplicate Words

Try this regular expression:

\b(\w+)\s+\1\b

Here \b is a word boundary and \1 references the captured match of the first group.

How can I invert color using CSS?

Add the same color of the background to the paragraph and then invert with CSS:

_x000D_
_x000D_
div {_x000D_
    background-color: #f00;_x000D_
}_x000D_
_x000D_
p { _x000D_
    color: #f00;_x000D_
    -webkit-filter: invert(100%);_x000D_
    filter: invert(100%);_x000D_
}
_x000D_
<div>_x000D_
    <p>inverted color</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

I know the question asking for Spring boot, but I believe lot of people looking for how to do this in non Spring boot, like me searching almost whole day.

Above Spring 4, there is no need to configure MappingJacksonHttpMessageConverter if you only intend to configure ObjectMapper.

You just need to do:

public class MyObjectMapper extends ObjectMapper {

    private static final long serialVersionUID = 4219938065516862637L;

    public MyObjectMapper() {
        super();
        enable(SerializationFeature.INDENT_OUTPUT);
    }       
}

And in your Spring configuration, create this bean:

@Bean 
public MyObjectMapper myObjectMapper() {        
    return new MyObjectMapper();
}

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.

C compile : collect2: error: ld returned 1 exit status

I got this problem, and tried many ways to solve it. Finally, it turned out that make clean and make again solved it. The reason is: I got the source code together with object files compiled previously with an old gcc version. When my newer gcc version wants to link that old object files, it can't resolve some function in there. It happens to me several times that the source code distributors do not clean up before packing, so a make clean saved the day.

WorksheetFunction.CountA - not working post upgrade to Office 2010

I'm not sure exactly what your problem is, because I cannot get your code to work as written. Two things seem evident:

  1. It appears you are relying on VBA to determine variable types and modify accordingly. This can get confusing if you are not careful, because VBA may assign a variable type you did not intend. In your code, a type of Range should be assigned to myRange. Since a Range type is an object in VBA it needs to be Set, like this: Set myRange = Range("A:A")
  2. Your use of the worksheet function CountA() should be called with .WorksheetFunction

If you are not doing it already, consider using the Option Explicit option at the top of your module, and typing your variables with Dim statements, as I have done below.

The following code works for me in 2010. Hopefully it works for you too:

Dim myRange As Range
Dim NumRows As Integer

Set myRange = Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange)

Good Luck.

Postgres manually alter sequence

The parentheses are misplaced:

SELECT setval('payments_id_seq', 21, true);  # next value will be 22

Otherwise you're calling setval with a single argument, while it requires two or three.

How to clear a textbox using javascript

It sounds like you're trying to use a "watermark" (a default value that clears itself when the user focuses on the box). Make sure to check the value before clearing it, otherwise you might remove something they have typed in! Try this:

<input type="text" value="A new value" onfocus="if(this.value=='A new value') this.value='';">

That will ensure it only clears when the value is "A new value".

Is there any method to get the URL without query string?

If you also want to remove hash, try this one: window.location.href.split(/[?#]/)[0]

Are there any free Xml Diff/Merge tools available?

A7Soft provide XML comparison tools freeware and shareware:

http://www.a7soft.com

How to create local notifications?

Here is sample code for LocalNotification that worked for my project.

Objective-C:

This code block in AppDelegate file :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
        // Override point for customization after application launch.
        return YES;
    }

    // This code block is invoked when application is in foreground (active-mode) 
 -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

        UIAlertView *notificationAlert = [[UIAlertView alloc] initWithTitle:@"Notification"    message:@"This local notification" 
        delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

        [notificationAlert show];
       // NSLog(@"didReceiveLocalNotification");
    }

This code block in .m file of any ViewController:

-(IBAction)startLocalNotification {  // Bind this method to UIButton action
    NSLog(@"startLocalNotification");

    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7];
    notification.alertBody = @"This is local notification!";
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.soundName = UILocalNotificationDefaultSoundName;
    notification.applicationIconBadgeNumber = 10;

    [[UIApplication sharedApplication] scheduleLocalNotification:notification];    
}

The above code display an AlertView after time interval of 7 seconds when pressed on button that binds startLocalNotification If application is in background then it displays BadgeNumber as 10 and with default notification sound.

This code works fine for iOS 7.x and below but for iOS 8 it will prompt following error on console:

Attempting to schedule a local notification with an alert but haven't received permission from the user to display alerts

This means you need register for local notification. This can be achieved using:

if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){

    [application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}

You can also refer blog for local notification.

Swift:

You AppDelegate.swift file should look like this:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {    
    // Override point for customization after application launch.
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert, categories: nil))

    return true
}

The swift file (say ViewController.swift) in which you want to create local notification should contain below code:

//MARK: - Button functions
func buttonIsPressed(sender: UIButton) {
    println("buttonIsPressed function called \(UIButton.description())")

    var localNotification = UILocalNotification()
    localNotification.fireDate = NSDate(timeIntervalSinceNow: 3)
    localNotification.alertBody = "This is local notification from Swift 2.0"
    localNotification.timeZone = NSTimeZone.localTimeZone()
    localNotification.repeatInterval = NSCalendarUnit.CalendarUnitMinute
    localNotification.userInfo = ["Important":"Data"];
    localNotification.soundName = UILocalNotificationDefaultSoundName
    localNotification.applicationIconBadgeNumber = 5
    localNotification.category = "Message"

    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}


//MARK: - viewDidLoad

class ViewController: UIViewController {

    var objButton : UIButton!
    . . .

    override func viewDidLoad() {
        super.viewDidLoad()

        . . .

        objButton = UIButton.buttonWithType(.Custom) as? UIButton
        objButton.frame = CGRectMake(30, 100, 150, 40)
        objButton.setTitle("Click Me", forState: .Normal)
        objButton.setTitle("Button pressed", forState: .Highlighted)

        objButton.addTarget(self, action: "buttonIsPressed:", forControlEvents: .TouchDown)

        . . .
    }

    . . .
}

The way you use to work with Local Notification in iOS 9 and below is completely different in iOS 10.

Below screen grab from Apple release notes depicts this.

Screenshot

You can refer apple reference document for UserNotification.

Below is code for local notification:

Objective-C:

  1. In App-delegate.h file use @import UserNotifications;

  2. App-delegate should conform to UNUserNotificationCenterDelegate protocol

  3. In didFinishLaunchingOptions use below code:

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
           completionHandler:^(BOOL granted, NSError * _Nullable error) {
                  if (!error) {
                      NSLog(@"request authorization succeeded!");
                      [self showAlert];
                  }
    }];
    
    -(void)showAlert {
        UIAlertController *objAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"show an alert!" preferredStyle:UIAlertControllerStyleAlert];
    
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK"
          style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            NSLog(@"Ok clicked!");
        }];
    
        [objAlertController addAction:cancelAction];
    
    
        [[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YES completion:^{            
        }];
    
    }
    
  4. Now create a button in any view controller and in IBAction use below code :

    UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
    
    objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@“Notification!” arguments:nil];
    
    objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@“This is local notification message!“arguments:nil];
    
    objNotificationContent.sound = [UNNotificationSound defaultSound];
    
    // 4. update application icon badge number
    objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
    
    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger =  [UNTimeIntervalNotificationTrigger                                             triggerWithTimeInterval:10.f repeats:NO];       
    
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@“ten”                                                                            content:objNotificationContent trigger:trigger];
    
    // 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@“Local Notification succeeded“);
        } else {
            NSLog(@“Local Notification failed“);
        }
    }];
    

Swift 3:

  1. In AppDelegate.swift file use import UserNotifications
  2. Appdelegate should conform to UNUserNotificationCenterDelegate protocol
  3. In didFinishLaunchingWithOptions use below code

    // Override point for customization after application launch.
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
        if error != nil {
            print("Request authorization failed!")
        } else {
            print("Request authorization succeeded!")
            self.showAlert()
        }
    }
    
    
    func showAlert() {
        let objAlert = UIAlertController(title: "Alert", message: "Request authorization succeeded", preferredStyle: UIAlertControllerStyle.alert)
    
        objAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        //self.presentViewController(objAlert, animated: true, completion: nil)
    
        UIApplication.shared().keyWindow?.rootViewController?.present(objAlert, animated: true, completion: nil)
    }
    
  4. Now create a button in any view controller and in IBAction use below code :

    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "notify-test"
    
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger)
    
    let center = UNUserNotificationCenter.current()
    center.add(request)
    

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

Put all the commands on to a script and it can be run like

ssh <remote-user>@<remote-host> "bash -s" <./remote-commands.sh

Bundler: Command not found

You need to add the ruby gem executable directory to your path

export PATH=$PATH:/opt/ruby-enterprise-1.8.7-2010.02/bin

How do you embed binary data in XML?

Any binary-to-text encoding will do the trick. I use something like that

<data encoding="yEnc>
<![CDATA[ encoded binary data ]]>
</data>

Export a list into a CSV or TXT file in R

So essentially you have a list of lists, with mylist being the name of the main list and the first element being $f10010_1 which is printed out (and which contains 4 more lists).

I think the easiest way to do this is to use lapply with the addition of dataframe (assuming that each list inside each element of the main list (like the lists in $f10010_1) has the same length):

lapply(mylist, function(x) write.table( data.frame(x), 'test.csv'  , append= T, sep=',' ))

The above will convert $f10010_1 into a dataframe then do the same with every other element and append one below the other in 'test.csv'

You can also type ?write.table on your console to check what other arguments you need to pass when you write the table to a csv file e.g. whether you need row names or column names etc.

Most efficient way to map function over numpy array

squares = squarer(x)

Arithmetic operations on arrays are automatically applied elementwise, with efficient C-level loops that avoid all the interpreter overhead that would apply to a Python-level loop or comprehension.

Most of the functions you'd want to apply to a NumPy array elementwise will just work, though some may need changes. For example, if doesn't work elementwise. You'd want to convert those to use constructs like numpy.where:

def using_if(x):
    if x < 5:
        return x
    else:
        return x**2

becomes

def using_where(x):
    return numpy.where(x < 5, x, x**2)

How can you tell if a value is not numeric in Oracle?

The best answer I found on internet:

SELECT case when trim(TRANSLATE(col1, '0123456789-,.', ' ')) is null
            then 'numeric'
            else 'alpha'
       end
FROM tab1;

Node package ( Grunt ) installed but not available

The right way to install grunt is by running this command:

npm install grunt -g

(Prepend "sudo" to the command above if you get a EACCESS error message)

-g will make npm install the package globally, so you will be able to use it whenever you want in your current machine.

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

Can I recover a branch after its deletion in Git?

If you removed the branch and forgot it's commit id you can do this command:

git log --graph --decorate $(git rev-list -g --all)

After this you'll be able to see all commits. Then you can do git checkout to this id and under this commit create a new branch.

How to search by key=>value in a multidimensional array in PHP

Came back to post this update for anyone needing an optimisation tip on these answers, particulary John Kugelman's great answer up above.

His posted function work fine but I had to optimize this scenario for handling a 12 000 row resultset. The function was taking an eternal 8 secs to go through all records, waaaaaay too long.

I simply needed the function to STOP searching and return when match was found. Ie, if searching for a customer_id, we know we only have one in the resultset and once we find the customer_id in the multidimensional array, we want to return.

Here is the speed-optimised ( and much simplified ) version of this function, for anyone in need. Unlike other version, it can only handle only one depth of array, does not recurse and does away with merging multiple results.

// search array for specific key = value
public function searchSubArray(Array $array, $key, $value) {   
    foreach ($array as $subarray){  
        if (isset($subarray[$key]) && $subarray[$key] == $value)
          return $subarray;       
    } 
}

This brought down the the task to match the 12 000 records to a 1.5 secs. Still very costly but much more reasonable.

How to force Sequential Javascript Execution?

Put your code in a string, iterate, eval, setTimeout and recursion to continue with the remaining lines. No doubt I'll refine this or just throw it out if it doesn't hit the mark. My intention is to use it to simulate really, really basic user testing.

The recursion and setTimeout make it sequential.

Thoughts?

var line_pos = 0;
var string =`
    console.log('123');
    console.log('line pos is '+ line_pos);
SLEEP
    console.log('waited');
    console.log('line pos is '+ line_pos);
SLEEP
SLEEP
    console.log('Did i finish?');
`;

var lines = string.split("\n");
var r = function(line_pos){
    for (i = p; i < lines.length; i++) { 
        if(lines[i] == 'SLEEP'){
            setTimeout(function(){r(line_pos+1)},1500);
            return;
        }
        eval (lines[line_pos]);
    }
    console.log('COMPLETED READING LINES');
    return;
}
console.log('STARTED READING LINES');
r.call(this,line_pos);

OUTPUT

STARTED READING LINES
123
124
1 p is 0
undefined
waited
p is 5
125
Did i finish?
COMPLETED READING LINES

Is there a simple, elegant way to define singletons?

The Python documentation does cover this:

class Singleton(object):
    def __new__(cls, *args, **kwds):
        it = cls.__dict__.get("__it__")
        if it is not None:
            return it
        cls.__it__ = it = object.__new__(cls)
        it.init(*args, **kwds)
        return it
    def init(self, *args, **kwds):
        pass

I would probably rewrite it to look more like this:

class Singleton(object):
    """Use to create a singleton"""
    def __new__(cls, *args, **kwds):
        """
        >>> s = Singleton()
        >>> p = Singleton()
        >>> id(s) == id(p)
        True
        """
        self = "__self__"
        if not hasattr(cls, self):
            instance = object.__new__(cls)
            instance.init(*args, **kwds)
            setattr(cls, self, instance)
        return getattr(cls, self)

    def init(self, *args, **kwds):
        pass

It should be relatively clean to extend this:

class Bus(Singleton):
    def init(self, label=None, *args, **kwds):
        self.label = label
        self.channels = [Channel("system"), Channel("app")]
        ...

SQL select * from column where year = 2010

NB: Should you want the year to be based on some reference date, the code below calculates the dates for the between statement:

declare @referenceTime datetime = getutcdate()
select *
from myTable
where SomeDate 
    between dateadd(year, year(@referenceTime) - 1900, '01-01-1900')                        --1st Jan this year (midnight)
    and dateadd(millisecond, -3, dateadd(year, year(@referenceTime) - 1900, '01-01-1901'))  --31st Dec end of this year (just before midnight of the new year)

Similarly, if you're using a year value, swapping year(@referenceDate) for your reference year's value will work

declare @referenceYear int = 2010
select *
from myTable
where SomeDate 
    between dateadd(year,@referenceYear - 1900, '01-01-1900')                       --1st Jan this year (midnight)
    and dateadd(millisecond, -3, dateadd(year,@referenceYear - 1900, '01-01-1901')) --31st Dec end of this year (just before midnight of the new year)

Text file in VBA: Open/Find Replace/SaveAs/Close File

Just add this line

sFileName = "C:\someotherfilelocation"

right before this line

Open sFileName For Output As iFileNum

The idea is to open and write to a different file than the one you read earlier (C:\filelocation).

If you want to get fancy and show a real "Save As" dialog box, you could do this instead:

sFileName = Application.GetSaveAsFilename()

Copy the entire contents of a directory in C#

Use this class.

public static class Extensions
{
    public static void CopyTo(this DirectoryInfo source, DirectoryInfo target, bool overwiteFiles = true)
    {
        if (!source.Exists) return;
        if (!target.Exists) target.Create();

        Parallel.ForEach(source.GetDirectories(), (sourceChildDirectory) => 
            CopyTo(sourceChildDirectory, new DirectoryInfo(Path.Combine(target.FullName, sourceChildDirectory.Name))));

        foreach (var sourceFile in source.GetFiles())
            sourceFile.CopyTo(Path.Combine(target.FullName, sourceFile.Name), overwiteFiles);
    }
    public static void CopyTo(this DirectoryInfo source, string target, bool overwiteFiles = true)
    {
        CopyTo(source, new DirectoryInfo(target), overwiteFiles);
    }
}

What is the right way to populate a DropDownList from a database?

I hope I am not overstating the obvious, but why not do it directly in the ASP side? Unless you are dynamically altering the SQL based on certain conditions in your program, you should avoid codebehind as much as possible.

You could do the above all in ASP directly without code using the SqlDataSource control and a property in your dropdownlist.

<asp:GridView ID="gvSubjects" runat="server" DataKeyNames="SubjectID" OnRowDataBound="GridView_RowDataBound" OnDataBound="GridView_DataBound">
    <Columns>
        <asp:TemplateField HeaderText="Subjects">
            <ItemTemplate>
                <asp:DropDownList ID="ddlSubjects" runat="server" DataSourceID="sdsSubjects" DataTextField="SubjectName" DataValueField="SubjectID">
                </asp:DropDownList>
                <asp:SqlDataSource ID="sdsSubjects" runat="server"
                    SelectCommand="SELECT SubjectID,SubjectName FROM Students.dbo.Subjects"></asp:SqlDataSource>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

How to set image in imageview in android?

you can directly give the Image name in your setimage as iv.setImageResource(R.drawable.apple); that should be it.

.autocomplete is not a function Error

You are calling the function before the page loads jQuery. It is always advisable to use jQuery inside

$(document).ready(function(){ //Your code here });

In your case:

$(document).ready(function(){
   $(function(){
      $( "#searcharea" ).autocomplete({
         source: "suggestions.php"
      });
      $( "#searchcat" ).autocomplete({
         source: "suggestions1.php"
      });
   });
});

How to Display Selected Item in Bootstrap Button Dropdown Title

Here is my version of this which I hope can save some of your time :)

enter image description here jQuery PART:

$(".dropdown-menu").on('click', 'li a', function(){
  var selText = $(this).children("h4").html();


 $(this).parent('li').siblings().removeClass('active');
    $('#vl').val($(this).attr('data-value'));
  $(this).parents('.btn-group').find('.selection').html(selText);
  $(this).parents('li').addClass("active");
});

HTML PART:

<div class="container">
  <div class="btn-group">
    <a class="btn btn-default dropdown-toggle btn-blog " data-toggle="dropdown" href="#" id="dropdownMenu1" style="width:200px;"><span class="selection pull-left">Select an option </span> 
      <span class="pull-right glyphiconglyphicon-chevron-down caret" style="float:right;margin-top:10px;"></span></a>

     <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
       <li><a href="#" class="" data-value=1><p> HER Can you write extra text or <b>HTLM</b></p> <h4> <span class="glyphicon glyphicon-plane"></span>  <span> Your Option 1</span> </h4></a>  </li>
       <li><a href="#" class="" data-value=2><p> HER Can you write extra text or <i>HTLM</i> or some long long long long long long long long long long text </p><h4> <span class="glyphicon glyphicon-briefcase"></span> <span>Your Option 2</span>  </h4></a>
      </li>
      <li class="divider"></li>
   <li><a href="#" class="" data-value=3><p> HER Can you write extra text or <b>HTLM</b> or some </p><h4> <span class="glyphicon glyphicon-heart text-danger"></span> <span>Your Option 3</span>  </h4></a>
      </li>
    </ul>
  </div>
  <input type="text" id="vl" />
</div>  

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

After falling victim to this problem on centOS after updating php to php5.6 I found a solution that worked for me.

Get the correct directory for your certs to be placed by default with this

php -r 'print_r(openssl_get_cert_locations()["default_cert_file"]);'

Then use this to get the cert and put it in the default location found from the code above

wget http://curl.haxx.se/ca/cacert.pem -O <default location>

How to add leading zeros for for-loop in shell?

why not printf '%02d' $num? See help printf for this internal bash command.

How to remove gaps between subplots in matplotlib?

With recent matplotlib versions you might want to try Constrained Layout. This does not work with plt.subplot() however, so you need to use plt.subplots() instead:

fig, axs = plt.subplots(4, 4, constrained_layout=True)

How to force the browser to reload cached CSS and JavaScript files

A simple solution for static files (just for development purposes) that adds a random version number to the script URI, using script tag injections

<script>
    var script = document.createElement('script');
    script.src = "js/app.js?v=" + Math.random();
    document.getElementsByTagName('head')[0].appendChild(script);
</script>

How to get progress from XMLHttpRequest

For the total uploaded there doesn't seem to be a way to handle that, but there's something similar to what you want for download. Once readyState is 3, you can periodically query responseText to get all the content downloaded so far as a String (this doesn't work in IE), up until all of it is available at which point it will transition to readyState 4. The total bytes downloaded at any given time will be equal to the total bytes in the string stored in responseText.

For a all or nothing approach to the upload question, since you have to pass a string for upload (and it's possible to determine the total bytes of that) the total bytes sent for readyState 0 and 1 will be 0, and the total for readyState 2 will be the total bytes in the string you passed in. The total bytes both sent and received in readyState 3 and 4 will be the sum of the bytes in the original string plus the total bytes in responseText.

Check if a file exists with wildcard in shell script

If your shell has a nullglob option and it's turned on, a wildcard pattern that matches no files will be removed from the command line altogether. This will make ls see no pathname arguments, list the contents of the current directory and succeed, which is wrong. GNU stat, which always fails if given no arguments or an argument naming a nonexistent file, would be more robust. Also, the &> redirection operator is a bashism.

if stat --printf='' /path/to/your/files* 2>/dev/null
then
    echo found
else
    echo not found
fi

Better still is GNU find, which can handle a wildcard search internally and exit as soon as at it finds one matching file, rather than waste time processing a potentially huge list of them expanded by the shell; this also avoids the risk that the shell might overflow its command line buffer.

if test -n "$(find /dir/to/search -maxdepth 1 -name 'files*' -print -quit)"
then
    echo found
else
    echo not found
fi

Non-GNU versions of find might not have the -maxdepth option used here to make find search only the /dir/to/search instead of the entire directory tree rooted there.

Remove the legend on a matplotlib figure

You could use the legend's set_visible method:

ax.legend().set_visible(False)
draw()

This is based on a answer provided to me in response to a similar question I had some time ago here

(Thanks for that answer Jouni - I'm sorry I was unable to mark the question as answered... perhaps someone who has the authority can do so for me?)

Update int column in table with unique incrementing values

In oracle-based products you may use the following statement:

update table set interfaceID=RowNum where condition;

How to check if a process is in hang state (Linux)

Is there any command in Linux through which i can know if the process is in hang state.

There is no command, but once I had to do a very dumb hack to accomplish something similar. I wrote a Perl script which periodically (every 30 seconds in my case):

  • run ps to find list of PIDs of the watched processes (along with exec time, etc)
  • loop over the PIDs
  • start gdb attaching to the process using its PID, dumping stack trace from it using thread apply all where, detaching from the process
  • a process was declared hung if:
    • its stack trace didn't change and time didn't change after 3 checks
    • its stack trace didn't change and time was indicating 100% CPU load after 3 checks
  • hung process was killed to give a chance for a monitoring application to restart the hung instance.

But that was very very very very crude hack, done to reach an about-to-be-missed deadline and it was removed a few days later, after a fix for the buggy application was finally installed.

Otherwise, as all other responders absolutely correctly commented, there is no way to find whether the process hung or not: simply because the hang might occur for way to many reasons, often bound to the application logic.

The only way is for application itself being capable of indicating whether it is alive or not. Simplest way might be for example a periodic log message "I'm alive".

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

Kotlin? Here we go:

android {

    // ... (compileSdkVersion, buildToolsVersion, etc)

    defaultConfig {

        // ... (applicationId, miSdkVersion, etc)

        kapt {
            arguments {
                arg("room.schemaLocation", "$projectDir/schemas")
            }
        }
    }

    buildTypes {
        // ... (buildTypes, compileOptions, etc)
    }
}

//...

Don't forget about plugin:

apply plugin: 'kotlin-kapt'

For more information about kotlin annotation processor please visit: Kotlin docs

Get final URL after curl is redirected

Can you try with it?

#!/bin/bash 
LOCATION=`curl -I 'http://your-domain.com/url/redirect?r=something&a=values-VALUES_FILES&e=zip' | perl -n -e '/^Location: (.*)$/ && print "$1\n"'` 
echo "$LOCATION"

Note: when you execute the command curl -I http://your-domain.com have to use single quotes in the command like curl -I 'http://your-domain.com'

What is the argument for printf that formats a long?

Put an l (lowercased letter L) directly before the specifier.

unsigned long n;
long m;

printf("%lu %ld", n, m);

Invalid use side-effecting operator Insert within a function

There is an exception (I'm using SQL 2014) when you are only using Insert/Update/Delete on Declared-Tables. These Insert/Update/Delete statements cannot contain an OUTPUT statement. The other restriction is that you are not allowed to do a MERGE, even into a Declared-Table. I broke up my Merge statements, that didn't work, into Insert/Update/Delete statements that did work.

The reason I didn't convert it to a stored-procedure is that the table-function was faster (even without the MERGE) than the stored-procedure. This is despite the stored-procedure allowing me to use Temp-Tables that have statistics. I needed the table-function to be very fast, since it is called 20-K times/day. This table function never updates the database.

I also noticed that the NewId() and RAND() SQL functions are not allowed in a function.

Mysql service is missing

Go to your mysql bin directory and install mysql service again:

c:
cd \mysql\bin
mysqld-nt.exe --install

or if mysqld-nt.exe is missing (depending on version):

mysqld.exe --install

Then go to services, start the service and set it to automatic start.

opening html from google drive

Found method to see your own html file (from here (scroll down to answer from prac): https://productforums.google.com/forum/#!topic/drive/YY_fou2vo0A)

-- use Get Link to get URL with id=... substring -- put uc instead of open in URL

How do you create a hidden div that doesn't create a line break or horizontal space?

Consider using <span> to isolate small segments of markup to be styled without breaking up layout. This would seem to be more idiomatic than trying to force a <div> not to display itself--if in fact the checkbox itself cannot be styled in the way you want.

increase legend font size ggplot2

You can also specify the font size relative to the base_size included in themes such as theme_bw() (where base_size is 11) using the rel() function.

For example:

ggplot(mtcars, aes(disp, mpg, col=as.factor(cyl))) +
  geom_point() +
  theme_bw() +
  theme(legend.text=element_text(size=rel(0.5)))

HTTP GET Request in Node.js Express

Unirest is the best library I've come across for making HTTP requests from Node. It's aiming at being a multiplatform framework, so learning how it works on Node will serve you well if you need to use an HTTP client on Ruby, PHP, Java, Python, Objective C, .Net or Windows 8 as well. As far as I can tell the unirest libraries are mostly backed by existing HTTP clients (e.g. on Java, the Apache HTTP client, on Node, Mikeal's Request libary) - Unirest just puts a nicer API on top.

Here are a couple of code examples for Node.js:

var unirest = require('unirest')

// GET a resource
unirest.get('http://httpbin.org/get')
  .query({'foo': 'bar'})
  .query({'stack': 'overflow'})
  .end(function(res) {
    if (res.error) {
      console.log('GET error', res.error)
    } else {
      console.log('GET response', res.body)
    }
  })

// POST a form with an attached file
unirest.post('http://httpbin.org/post')
  .field('foo', 'bar')
  .field('stack', 'overflow')
  .attach('myfile', 'examples.js')
  .end(function(res) {
    if (res.error) {
      console.log('POST error', res.error)
    } else {
      console.log('POST response', res.body)
    }
  })

You can jump straight to the Node docs here

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

<?php header("Access-Control-Allow-Origin: http://example.com"); ?>

This command disables only first console warning info

console

Result: console result

Get the difference between dates in terms of weeks, months, quarters, and years

I just wrote this for another question, then stumbled here.

library(lubridate)

#' Calculate age
#' 
#' By default, calculates the typical "age in years", with a
#' \code{floor} applied so that you are, e.g., 5 years old from
#' 5th birthday through the day before your 6th birthday. Set
#' \code{floor = FALSE} to return decimal ages, and change \code{units}
#' for units other than years.
#' @param dob date-of-birth, the day to start calculating age.
#' @param age.day the date on which age is to be calculated.
#' @param units unit to measure age in. Defaults to \code{"years"}. Passed to \link{\code{duration}}.
#' @param floor boolean for whether or not to floor the result. Defaults to \code{TRUE}.
#' @return Age in \code{units}. Will be an integer if \code{floor = TRUE}.
#' @examples
#' my.dob <- as.Date('1983-10-20')
#' age(my.dob)
#' age(my.dob, units = "minutes")
#' age(my.dob, floor = FALSE)
age <- function(dob, age.day = today(), units = "years", floor = TRUE) {
    calc.age = interval(dob, age.day) / duration(num = 1, units = units)
    if (floor) return(as.integer(floor(calc.age)))
    return(calc.age)
}

Usage examples:

my.dob <- as.Date('1983-10-20')

age(my.dob)
# [1] 31

age(my.dob, floor = FALSE)
# [1] 31.15616

age(my.dob, units = "minutes")
# [1] 16375680

age(seq(my.dob, length.out = 6, by = "years"))
# [1] 31 30 29 28 27 26

Determining the path that a yum package installed to

I don't know about yum, but rpm -ql will list the files in a particular .rpm file. If you can find the package file on your system you should be good to go.

SQL How to replace values of select return?

Replace the value in select statement itself...

(CASE WHEN Mobile LIKE '966%' THEN (select REPLACE(CAST(Mobile AS nvarchar(MAX)),'966','0')) ELSE Mobile END)

bash echo number of lines of file given in a bash variable without the file name

An Example Using Your Own Data

You can avoid having your filename embedded in the NUMOFLINES variable by using redirection from JAVA_TAGS_FILE, rather than passing the filename as an argument to wc. For example:

NUMOFLINES=$(wc -l < "$JAVA_TAGS_FILE")

Explanation: Use Pipes or Redirection to Avoid Filenames in Output

The wc utility will not print the name of the file in its output if input is taken from a pipe or redirection operator. Consider these various examples:

# wc shows filename when the file is an argument
$ wc -l /etc/passwd
41 /etc/passwd

# filename is ignored when piped in on standard input
$ cat /etc/passwd | wc -l
41

# unusual redirection, but wc still ignores the filename
$ < /etc/passwd wc -l
41

# typical redirection, taking standard input from a file
$ wc -l < /etc/passwd
41

As you can see, the only time wc will print the filename is when its passed as an argument, rather than as data on standard input. In some cases, you may want the filename to be printed, so it's useful to understand when it will be displayed.

MYSQL order by both Ascending and Descending sorting

I don't understand what the meaning of ordering with the same column ASC and DESC in the same ORDER BY, but this how you can do it: naam DESC, naam ASC like so:

ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

If the value of a disabled textbox needs to be retained when a form is cleared (reset), disabled = "disabled" has to be used, as read-only textbox will not retain the value

For Example:

HTML

Textbox

<input type="text" id="disabledText" name="randombox" value="demo" disabled="disabled" />

Reset button

<button type="reset" id="clearButton">Clear</button>

In the above example, when Clear button is pressed, disabled text value will be retained in the form. Value will not be retained in the case of input type = "text" readonly="readonly"

get the value of DisplayName attribute

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(foo);

foreach (PropertyDescriptor property in properties)
{
    if (property.Name == "Name")
    {
        Console.WriteLine(property.DisplayName); // Something To Name
    }
}

where foo is an instance of Class1

How do you make strings "XML safe"?

I prefer the way Golang does quote escaping for XML (and a few extras like newline escaping, and escaping some other characters), so I have ported its XML escape function to PHP below

function isInCharacterRange(int $r): bool {
    return $r == 0x09 ||
            $r == 0x0A ||
            $r == 0x0D ||
            $r >= 0x20 && $r <= 0xDF77 ||
            $r >= 0xE000 && $r <= 0xFFFD ||
            $r >= 0x10000 && $r <= 0x10FFFF;
}

function xml(string $s, bool $escapeNewline = true): string {
    $w = '';

    $Last = 0;
    $l = strlen($s);
    $i = 0;

    while ($i < $l) {
        $r = mb_substr(substr($s, $i), 0, 1);
        $Width = strlen($r);
        $i += $Width;
        switch ($r) {
            case '"':
                $esc = '&#34;';
                break;
            case "'":
                $esc = '&#39;';
                break;
            case '&':
                $esc = '&amp;';
                break;
            case '<':
                $esc = '&lt;';
                break;
            case '>':
                $esc = '&gt;';
                break;
            case "\t":
                $esc = '&#x9;';
                break;
            case "\n":
                if (!$escapeNewline) {
                    continue 2;
                }
                $esc = '&#xA;';
                break;
            case "\r":
                $esc = '&#xD;';
                break;
            default:
                if (!isInCharacterRange(mb_ord($r)) || (mb_ord($r) === 0xFFFD && $Width === 1)) {
                    $esc = "\u{FFFD}";
                    break;
                }

                continue 2;
        }
        $w .= substr($s, $Last, $i - $Last - $Width) . $esc;
        $Last = $i;
    }
    $w .= substr($s, $Last);
    return $w;
}

Note you'll need at least PHP7.2 because of the mb_ord usage, or you'll have to swap it out for another polyfill, but these functions are working great for us!

For anyone curious, here is the relevant Go source https://golang.org/src/encoding/xml/xml.go?s=44219:44263#L1887

How to run specific test cases in GoogleTest

Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:

On the console

You should use the flag --gtest_filter, like

--gtest_filter=Test_Cases1*

(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)

On the environment

You should set the variable GTEST_FILTER like

export GTEST_FILTER = "Test_Cases1*"

On the code

You should set a flag filter, like

::testing::GTEST_FLAG(filter) = "Test_Cases1*";

such that your main function becomes something like

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::GTEST_FLAG(filter) = "Test_Cases1*";
    return RUN_ALL_TESTS();
}

See section Running a Subset of the Tests for more info on the syntax of the string you can use.

What is the PostgreSQL equivalent for ISNULL()

SELECT CASE WHEN field IS NULL THEN 'Empty' ELSE field END AS field_alias

Or more idiomatic:

SELECT coalesce(field, 'Empty') AS field_alias

Getting around the Max String size in a vba function?

This works and shows more than 255 characters in the message box.

Sub TestStrLength()
    Dim s As String
    Dim i As Integer

    s = ""
    For i = 1 To 500
        s = s & "1234567890"
    Next i

    MsgBox s
End Sub

The message box truncates the string to 1023 characters, but the string itself can be very large.

I would also recommend that instead of using fixed variables names with numbers (e.g. Var1, Var2, Var3, ... Var255) that you use an array. This is much shorter declaration and easier to use - loops.

Here's an example:

Sub StrArray()
Dim var(256) As Integer
Dim i As Integer
Dim s As String

For i = 1 To 256
    var(i) = i
Next i

s = "Tims_pet_Robot"
For i = 1 To 256
    s = s & " """ & var(i) & """"
Next i

    SecondSub (s)
End Sub

Sub SecondSub(s As String)
    MsgBox "String length = " & Len(s)
End Sub

Updated this to show that a string can be longer than 255 characters and used in a subroutine/function as a parameter that way. This shows that the string length is 1443 characters. The actual limit in VBA is 2GB per string.

Perhaps there is instead a problem with the API that you are using and that has a limit to the string (such as a fixed length string). The issue is not with VBA itself.

Ok, I see the problem is specifically with the Application.OnTime method itself. It is behaving like Excel functions in that they only accept strings that are up to 255 characters in length. VBA procedures and functions though do not have this limit as I have shown. Perhaps then this limit is imposed for any built-in Excel object method.


Update:
changed ...longer than 256 characters... to ...longer than 255 characters...

How to compare only date in moment.js

You could use startOf('day') method to compare just the date

Example :

var dateToCompare = moment("06/04/2015 18:30:00");
var today = moment(new Date());

dateToCompare.startOf('day').isSame(today.startOf('day'));

Is there a limit to the length of a GET request?

As Requested By User Erickson, I Post My comment As Answer:

I have done some more testing with IE8, IE9, FF14, Opera11, Chrome20 and Tomcat 6.0.32 (fresh installation), Jersey 1.13 on the server side. I used the jQuery function $.getJson and JSONP. Results: All Browsers allowed up to around 5400 chars. FF and IE9 did up to around 6200 chars. Everything above returned "400 Bad request". I did not further investigate what was responsible for the 400. I was fine with the maximum I found, because I needed around 2000 chars in my case.

Encapsulation vs Abstraction?

in a simple sentence, I cay say: The essence of abstraction is to extract essential properties while omitting inessential details. But why should we omit inessential details? The key motivator is preventing the risk of change. You might consider abstraction is same as encapsulation. But encapsulation means the act of enclosing one or more items within a container, not hiding details. If you make the argument that "everything that was encapsulated was also hidden." This is obviously not true. For example, even though information may be encapsulated within record structures and arrays, this information is usually not hidden (unless hidden via some other mechanism).

Filename too long in Git for Windows

This might help:

git config core.longpaths true

Basic explanation: This answer suggests not to have such setting applied to the global system (to all projects so avoiding --system or --global tag) configurations. This command only solves the problem by being specific to the current project.

EDIT:

This is an important answer related to the "permission denied" issue for those whom does not granted to change git settings globally.

How do I get Flask to run on port 80?

you can easily disable any process running on port 80 and then run this command

flask run --host 0.0.0.0 --port 80

or if u prefer running it within the .py file

if __name__ == "__main__":
    app.run(host=0.0.0.0, port=80)

How to import CSV file data into a PostgreSQL table?

Most other solutions here require that you create the table in advance/manually. This may not be practical in some cases (e.g., if you have a lot of columns in the destination table). So, the approach below may come handy.

Providing the path and column count of your csv file, you can use the following function to load your table to a temp table that will be named as target_table:

The top row is assumed to have the column names.

create or replace function data.load_csv_file
(
    target_table text,
    csv_path text,
    col_count integer
)

returns void as $$

declare

iter integer; -- dummy integer to iterate columns with
col text; -- variable to keep the column name at each iteration
col_first text; -- first column name, e.g., top left corner on a csv file or spreadsheet

begin
    create table temp_table ();

    -- add just enough number of columns
    for iter in 1..col_count
    loop
        execute format('alter table temp_table add column col_%s text;', iter);
    end loop;

    -- copy the data from csv file
    execute format('copy temp_table from %L with delimiter '','' quote ''"'' csv ', csv_path);

    iter := 1;
    col_first := (select col_1 from temp_table limit 1);

    -- update the column names based on the first row which has the column names
    for col in execute format('select unnest(string_to_array(trim(temp_table::text, ''()''), '','')) from temp_table where col_1 = %L', col_first)
    loop
        execute format('alter table temp_table rename column col_%s to %s', iter, col);
        iter := iter + 1;
    end loop;

    -- delete the columns row
    execute format('delete from temp_table where %s = %L', col_first, col_first);

    -- change the temp table name to the name given as parameter, if not blank
    if length(target_table) > 0 then
        execute format('alter table temp_table rename to %I', target_table);
    end if;

end;

$$ language plpgsql;

How do I configure php to enable pdo and include mysqli on CentOS?

You might just have to install the packages.

yum install php-pdo php-mysqli

After they're installed, restart Apache.

httpd restart

or

apachectl restart

Openssl : error "self signed certificate in certificate chain"

You have a certificate which is self-signed, so it's non-trusted by default, that's why OpenSSL complains. This warning is actually a good thing, because this scenario might also rise due to a man-in-the-middle attack.

To solve this, you'll need to install it as a trusted server. If it's signed by a non-trusted CA, you'll have to install that CA's certificate as well.

Have a look at this link about installing self-signed certificates.

Getting list of tables, and fields in each, in a database

Is this what you are looking for:

Using OBJECT CATALOG VIEWS

 SELECT T.name AS Table_Name ,
       C.name AS Column_Name ,
       P.name AS Data_Type ,
       P.max_length AS Size ,
       CAST(P.precision AS VARCHAR) + '/' + CAST(P.scale AS VARCHAR) AS Precision_Scale
FROM   sys.objects AS T
       JOIN sys.columns AS C ON T.object_id = C.object_id
       JOIN sys.types AS P ON C.system_type_id = P.system_type_id
WHERE  T.type_desc = 'USER_TABLE';

Using INFORMATION SCHEMA VIEWS

  SELECT TABLE_SCHEMA ,
       TABLE_NAME ,
       COLUMN_NAME ,
       ORDINAL_POSITION ,
       COLUMN_DEFAULT ,
       DATA_TYPE ,
       CHARACTER_MAXIMUM_LENGTH ,
       NUMERIC_PRECISION ,
       NUMERIC_PRECISION_RADIX ,
       NUMERIC_SCALE ,
       DATETIME_PRECISION
FROM   INFORMATION_SCHEMA.COLUMNS;

Reference : My Blog - http://dbalink.wordpress.com/2008/10/24/querying-the-object-catalog-and-information-schema-views/

How to run html file on localhost?

If you are running Python3, you may want to instead try:

python -m http.server

See this answer.

How to add a footer to the UITableView?

You need to implement the UITableViewDelegate method

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section

and return the desired view (e.g. a UILabel with the text you'd like in the footer) for the appropriate section of the table.

VBA equivalent to Excel's mod function

Be very careful with the Excel MOD(a,b) function and the VBA a Mod b operator. Excel returns a floating point result and VBA an integer.

In Excel =Mod(90.123,90) returns 0.123000000000005 instead of 0.123 In VBA 90.123 Mod 90 returns 0

They are certainly not equivalent!

Equivalent are: In Excel: =Round(Mod(90.123,90),3) returning 0.123 and In VBA: ((90.123 * 1000) Mod 90000)/1000 returning also 0.123

Editing hosts file to redirect url?

hosts file:

1.2.3.4 google.com

1.2.3.4 - ip of your server.

Run script on the server for redirecting users to url that you want.

Most efficient way to append arrays in C#?

You can't append to an actual array - the size of an array is fixed at creation time. Instead, use a List<T> which can grow as it needs to.

Alternatively, keep a list of arrays, and concatenate them all only when you've grabbed everything.

See Eric Lippert's blog post on arrays for more detail and insight than I could realistically provide :)

Android Studio update -Error:Could not run build action using Gradle distribution

I forced to use a proxy and also forced to add proxy setting on gradle.properties as these:

systemProp.http.proxyHost=127.0.0.1
systemProp.http.proxyPort=1080
systemProp.https.proxyHost=127.0.0.1
systemProp.https.proxyPort=1080

And also forced to close and open studio64.exe as administrator . Now its all seems greate

Event log says

8:21:39 AM Platform and Plugin Updates: The following components are ready to update: Android Support Repository, Google Repository, Intel x86 Emulator Accelerator (HAXM installer), Android SDK Platform-Tools 24, Google APIs Intel x86 Atom System Image, Android SDK Tools 25.1.7
8:21:40 AM Gradle sync started
8:22:03 AM Gradle sync completed
8:22:04 AM Executing tasks: [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:prepareDebugUnitTestDependencies, :app:mockableAndroidJar]
8:22:25 AM Gradle build finished in 21s 607ms

I'm using android studio 2.1.2 downloaded as exe setup file. it has its Gradle ( I also forced to use custom install to address the Gradle )

Apply vs transform on a group object

As I felt similarly confused with .transform operation vs. .apply I found a few answers shedding some light on the issue. This answer for example was very helpful.

My takeout so far is that .transform will work (or deal) with Series (columns) in isolation from each other. What this means is that in your last two calls:

df.groupby('A').transform(lambda x: (x['C'] - x['D']))
df.groupby('A').transform(lambda x: (x['C'] - x['D']).mean())

You asked .transform to take values from two columns and 'it' actually does not 'see' both of them at the same time (so to speak). transform will look at the dataframe columns one by one and return back a series (or group of series) 'made' of scalars which are repeated len(input_column) times.

So this scalar, that should be used by .transform to make the Series is a result of some reduction function applied on an input Series (and only on ONE series/column at a time).

Consider this example (on your dataframe):

zscore = lambda x: (x - x.mean()) / x.std() # Note that it does not reference anything outside of 'x' and for transform 'x' is one column.
df.groupby('A').transform(zscore)

will yield:

       C      D
0  0.989  0.128
1 -0.478  0.489
2  0.889 -0.589
3 -0.671 -1.150
4  0.034 -0.285
5  1.149  0.662
6 -1.404 -0.907
7 -0.509  1.653

Which is exactly the same as if you would use it on only on one column at a time:

df.groupby('A')['C'].transform(zscore)

yielding:

0    0.989
1   -0.478
2    0.889
3   -0.671
4    0.034
5    1.149
6   -1.404
7   -0.509

Note that .apply in the last example (df.groupby('A')['C'].apply(zscore)) would work in exactly the same way, but it would fail if you tried using it on a dataframe:

df.groupby('A').apply(zscore)

gives error:

ValueError: operands could not be broadcast together with shapes (6,) (2,)

So where else is .transform useful? The simplest case is trying to assign results of reduction function back to original dataframe.

df['sum_C'] = df.groupby('A')['C'].transform(sum)
df.sort('A') # to clearly see the scalar ('sum') applies to the whole column of the group

yielding:

     A      B      C      D  sum_C
1  bar    one  1.998  0.593  3.973
3  bar  three  1.287 -0.639  3.973
5  bar    two  0.687 -1.027  3.973
4  foo    two  0.205  1.274  4.373
2  foo    two  0.128  0.924  4.373
6  foo    one  2.113 -0.516  4.373
7  foo  three  0.657 -1.179  4.373
0  foo    one  1.270  0.201  4.373

Trying the same with .apply would give NaNs in sum_C. Because .apply would return a reduced Series, which it does not know how to broadcast back:

df.groupby('A')['C'].apply(sum)

giving:

A
bar    3.973
foo    4.373

There are also cases when .transform is used to filter the data:

df[df.groupby(['B'])['D'].transform(sum) < -1]

     A      B      C      D
3  bar  three  1.287 -0.639
7  foo  three  0.657 -1.179

I hope this adds a bit more clarity.

UIImage: Resize, then Crop

The following simple code worked for me.

[imageView setContentMode:UIViewContentModeScaleAspectFill];
[imageView setClipsToBounds:YES];

Login to Microsoft SQL Server Error: 18456

SQL Server connection troubleshoot

In case you are not able to connect with SQL Authentication and you've tried the other solutions.

You may try the following:

Check connectivity

  • Disable Firewall.
  • Run PortQry on 1434 and check the answer.

Check the state

  • Try to connect with SSMS or sqlcmd and check the message.
  • State 1 is rarely documented but it just mean you don't have the right to know the true state.
  • Look at the log file in the directory of SQL server to know what is the state.

The State 5

What ? my login doesn't exist ? it's right there, I can see it in SSMS. How can it be ?

The most likely explanation is the most likely to be the right one.

The state of the login

  • Destroy, recreate it, enable it.
  • reset the password.

Or...

"You don't look at the right place" or "what you see is not what you think".

The Local DB and SQLEXPRESS conflict

If you connect with SSMS with Windows authentication, and your instance is named SQLEXPRESS, you are probably looking at the LocalDb and not the right server. So you just created your login on LocalDb.

When you connect through SQL Server authentication with SSMS, it will try to connect to SQLEXPRESS real server where your beloved login doesn't exist yet.

Additional note: Check in the connection parameters tab if you've not forgotten some strange connection string there.

Centering a canvas

Simple:

<body>
    <div>
        <div style="width: 800px; height:500px; margin: 50px auto;">
            <canvas width="800" height="500" style="background:#CCC">
             Your browser does not support HTML5 Canvas.
            </canvas>
        </div>
    </div>
</body>

How to remove the character at a given index from a string in C?

this is how I implemented the same in c++.

#include <iostream>
#include <cstring>

using namespace std;

int leng;
char ch;
string str, cpy;

int main() {
    cout << "Enter a string: ";
    getline(cin, str);
    leng = str.length();
    cout << endl << "Enter the character to delete: ";
    cin >> ch;
    for (int i=0; i<leng; i++) {
        if (str[i] != ch)
        cpy += str[i];
    }
    cout << endl << "String after removal: " << cpy;
    return 0;
}

window.location (JS) vs header() (PHP) for redirection

The result is same for all options. Redirect.

<meta> in HTML:

  • Show content of your site, and next redirect user after a few (or 0) seconds.
  • Don't need JavaScript enabled.
  • Don't need PHP.

window.location in JS:

  • Javascript enabled needed.
  • Don't need PHP.
  • Show content of your site, and next redirect user after a few (or 0) seconds.
  • Redirect can be dependent on any conditions if (1 === 1) { window.location.href = 'http://example.com'; }.

header('Location:') in PHP:

  • Don't need JavaScript enabled.
  • PHP needed.
  • Redirect will be executed first, user never see what is after. header() must be the first command in php script, before output any other. If you try output some before header, will receive an Warning: Cannot modify header information - headers already sent

How to read the last row with SQL Server

You can use last_value: SELECT LAST_VALUE(column) OVER (PARTITION BY column ORDER BY column)...

I test it at one of my databases and it worked as expected.

You can also check de documentation here: https://msdn.microsoft.com/en-us/library/hh231517.aspx

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

If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

Correct way to quit a Qt program?

if you need to close your application from main() you can use this code

int main(int argc, char *argv[]){
QApplication app(argc, argv);
...
if(!QSslSocket::supportsSsl()) return app.exit(0);
...
return app.exec();
}

The program will terminated if OpenSSL is not installed

Performing Breadth First Search recursively

C# implementation of recursive breadth-first search algorithm for a binary tree.

Binary tree data visualization

IDictionary<string, string[]> graph = new Dictionary<string, string[]> {
    {"A", new [] {"B", "C"}},
    {"B", new [] {"D", "E"}},
    {"C", new [] {"F", "G"}},
    {"E", new [] {"H"}}
};

void Main()
{
    var pathFound = BreadthFirstSearch("A", "H", new string[0]);
    Console.WriteLine(pathFound); // [A, B, E, H]

    var pathNotFound = BreadthFirstSearch("A", "Z", new string[0]);
    Console.WriteLine(pathNotFound); // []
}

IEnumerable<string> BreadthFirstSearch(string start, string end, IEnumerable<string> path)
{
    if (start == end)
    {
        return path.Concat(new[] { end });
    }

    if (!graph.ContainsKey(start)) { return new string[0]; }    

    return graph[start].SelectMany(letter => BreadthFirstSearch(letter, end, path.Concat(new[] { start })));
}

If you want algorithm to work not only with binary-tree but with graphs what can have two and more nodes that points to same another node you must to avoid self-cycling by holding list of already visited nodes. Implementation may be looks like this.

Graph data visualization

IDictionary<string, string[]> graph = new Dictionary<string, string[]> {
    {"A", new [] {"B", "C"}},
    {"B", new [] {"D", "E"}},
    {"C", new [] {"F", "G", "E"}},
    {"E", new [] {"H"}}
};

void Main()
{
    var pathFound = BreadthFirstSearch("A", "H", new string[0], new List<string>());
    Console.WriteLine(pathFound); // [A, B, E, H]

    var pathNotFound = BreadthFirstSearch("A", "Z", new string[0], new List<string>());
    Console.WriteLine(pathNotFound); // []
}

IEnumerable<string> BreadthFirstSearch(string start, string end, IEnumerable<string> path, IList<string> visited)
{
    if (start == end)
    {
        return path.Concat(new[] { end });
    }

    if (!graph.ContainsKey(start)) { return new string[0]; }


    return graph[start].Aggregate(new string[0], (acc, letter) =>
    {
        if (visited.Contains(letter))
        {
            return acc;
        }

        visited.Add(letter);

        var result = BreadthFirstSearch(letter, end, path.Concat(new[] { start }), visited);
        return acc.Concat(result).ToArray();
    });
}

How to store custom objects in NSUserDefaults

On your Player class, implement the following two methods (substituting calls to encodeObject with something relevant to your own object):

- (void)encodeWithCoder:(NSCoder *)encoder {
    //Encode properties, other class variables, etc
    [encoder encodeObject:self.question forKey:@"question"];
    [encoder encodeObject:self.categoryName forKey:@"category"];
    [encoder encodeObject:self.subCategoryName forKey:@"subcategory"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        //decode properties, other class vars
        self.question = [decoder decodeObjectForKey:@"question"];
        self.categoryName = [decoder decodeObjectForKey:@"category"];
        self.subCategoryName = [decoder decodeObjectForKey:@"subcategory"];
    }
    return self;
}

Reading and writing from NSUserDefaults:

- (void)saveCustomObject:(MyObject *)object key:(NSString *)key {
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:encodedObject forKey:key];
    [defaults synchronize];

}

- (MyObject *)loadCustomObjectWithKey:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *encodedObject = [defaults objectForKey:key];
    MyObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
}

Code shamelessly borrowed from: saving class in nsuserdefaults

Linux command (like cat) to read a specified quantity of characters

Here's a simple script that wraps up using the dd approach mentioned here:

extract_chars.sh

#!/usr/bin/env bash

function show_help()
{
  IT="
extracts characters X to Y from stdin or FILE
usage: X Y {FILE}

e.g. 

2 10 /tmp/it     => extract chars 2-10 from /tmp/it
EOF
  "
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

FROM=$1
TO=$2
COUNT=`expr $TO - $FROM + 1`

if [ -z "$3" ]
then
  dd skip=$FROM count=$COUNT bs=1 2>/dev/null
else
  dd skip=$FROM count=$COUNT bs=1 if=$3 2>/dev/null 
fi

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

Try the following steps:
1. Make sure you have the latest npm (npm install -g npm).
2. Add an exception to your antivirus to ignore the node_modules folder in your project.
3. $ rm -rf node_modules package-lock.json .
4. $ npm install

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

This should be very simple if Google Calendar does not require the *.ics-extension (which will require some URL rewriting in the server).

$ical = "BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//hacksw/handcal//NONSGML v1.0//EN
BEGIN:VEVENT
UID:" . md5(uniqid(mt_rand(), true)) . "@yourhost.test
DTSTAMP:" . gmdate('Ymd').'T'. gmdate('His') . "Z
DTSTART:19970714T170000Z
DTEND:19970715T035959Z
SUMMARY:Bastille Day Party
END:VEVENT
END:VCALENDAR";

//set correct content-type-header
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename=calendar.ics');
echo $ical;
exit;

That's essentially all you need to make a client think that you're serving a iCalendar file, even though there might be some issues regarding caching, text encoding and so on. But you can start experimenting with this simple code.

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

NUMBER (precision, scale) means precision number of total digits, of which scale digits are right of the decimal point.

NUMBER(2,2) in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2) to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.

More info at the Oracle docs.

How do I convert a pandas Series or index to a Numpy array?

Below is a simple way to convert dataframe column into numpy array.

df = pd.DataFrame(somedict) 
ytrain = df['label']
ytrain_numpy = np.array([x for x in ytrain['label']])

ytrain_numpy is a numpy array.

I tried with to.numpy() but it gave me the below error: TypeError: no supported conversion for types: (dtype('O'),) while doing Binary Relevance classfication using Linear SVC. to.numpy() was converting the dataFrame into numpy array but the inner element's data type was list because of which the above error was observed.

Formatting MM/DD/YYYY dates in textbox in VBA

Private Sub txtBoxBDayHim_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii >= 48 And KeyAscii <= 57 Or KeyAscii = 8 Then 'only numbers and backspace
    If KeyAscii = 8 Then 'if backspace, ignores + "/"
    Else
        If txtBoxBDayHim.TextLength = 10 Then 'limit textbox to 10 characters
        KeyAscii = 0
        Else
            If txtBoxBDayHim.TextLength = 2 Or txtBoxBDayHim.TextLength = 5 Then 'adds / automatically
            txtBoxBDayHim.Text = txtBoxBDayHim.Text + "/"
            End If
        End If
    End If
Else
KeyAscii = 0
End If
End Sub

This works for me. :)

Your code helped me a lot. Thanks!

I'm brazilian and my english is poor, sorry for any mistake.

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

UPDATED:

You can: create a constant:

private static final DateTimeFormatter DATE_FORMATTER_YYYY_MM_DD =
          DateTimeFormat.forPattern("yyyy-MM-dd"); // or whatever pattern that you need.

This DateTimeFormat is importing from: (be careful with that)

import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter;

Parse the Date with:

DateTime.parse(dateTimeScheduled.toString(), DATE_FORMATTER_YYYY_MM_DD);

Before:
DateTime.parse("201711201515",DateTimeFormat.forPattern("yyyyMMddHHmm")).toString("yyyyMMdd");

if want datetime:

DateTime.parse("201711201515", DateTimeFormat.forPattern("yyyyMMddHHmm")).withTimeAtStartOfDay();

Passing an Object from an Activity to a Fragment

Passing arguments by bundle is restricted to some data types. But you can transfer any data to your fragment this way:

In your fragment create a public method like this

public void passData(Context context, List<LexItem> list, int pos) {
    mContext = context;
    mLexItemList = list;
    mIndex = pos;
}

and in your activity call passData() with all your needed data types after instantiating the fragment

        WebViewFragment myFragment = new WebViewFragment();
        myFragment.passData(getApplicationContext(), mLexItemList, index);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.my_fragment_container, myFragment);
        ft.addToBackStack(null);
        ft.commit();

Remark: My fragment extends "android.support.v4.app.Fragment", therefore I have to use "getSupportFragmentManager()". Of course, this principle will work also with a fragment class extending "Fragment", but then you have to use "getFragmentManager()".

Verify object attribute value with mockito

Another easy way to do so:

import org.mockito.BDDMockito;    
import static org.mockito.Matchers.argThat;
import org.mockito.ArgumentMatcher;

BDDMockito.verify(mockedObject)
        .someMethodOnMockedObject(argThat(new ArgumentMatcher<TypeOfMethodArg>() {

            @Override
            public boolean matches(Object argument) {
                final TypeOfMethodArg castedArg = (TypeOfMethodArg) argument;

                // Make your verifications and return a boolean to say if it matches or not
                boolean isArgMarching = true;

                return isArgMarching;
            }
        }));

Upgrading Node.js to latest version

Install npm =>

sudo apt-get install npm

Install n =>

sudo npm install n -g

latest version of node =>

sudo n latest 

So latest version will be downloaded and installed

Specific version of node you can

List available node versions =>

n ls

Install a specific version =>

sudo n 4.5.0

How to make div fixed after you scroll to that div?

it worked for me

$(document).scroll(function() {
    var y = $(document).scrollTop(), //get page y value 
        header = $("#myarea"); // your div id
    if(y >= 400)  {
        header.css({position: "fixed", "top" : "0", "left" : "0"});
    } else {
        header.css("position", "static");
    }
});

How can I get the ID of an element using jQuery?

Important: if you are creating a new object with jQuery and binding an event, you MUST use prop and not attr, like this:

$("<div/>",{ id: "yourId", class: "yourClass", html: "<span></span>" }).on("click", function(e) { alert($(this).prop("id")); }).appendTo("#something");

is there any PHP function for open page in new tab

Use the target attribute on your anchor tag with the _blank value.

Example:

<a href="http://google.com" target="_blank">Click Me!</a>

Calculating sum of repeated elements in AngularJS ng-repeat

Huy Nguyen's answer is almost there. To make it work, add:

ng-repeat="_ in [ products ]"

...to the line with ng-init. The list always has a single item, so Angular will repeat the block exactly once.

Zybnek's demo using filtering can be made to work by adding:

ng-repeat="_ in [ [ products, search ] ]"

See http://plnkr.co/edit/dLSntiy8EyahZ0upDpgy?p=preview.

Can a foreign key be NULL and/or duplicate?

Here's an example using Oracle syntax:
First let's create a table COUNTRY

CREATE TABLE TBL_COUNTRY ( COUNTRY_ID VARCHAR2 (50) NOT NULL ) ;
ALTER TABLE TBL_COUNTRY ADD CONSTRAINT COUNTRY_PK PRIMARY KEY ( COUNTRY_ID ) ;

Create the table PROVINCE

CREATE TABLE TBL_PROVINCE(
PROVINCE_ID VARCHAR2 (50) NOT NULL ,
COUNTRY_ID  VARCHAR2 (50)
);
ALTER TABLE TBL_PROVINCE ADD CONSTRAINT PROVINCE_PK PRIMARY KEY ( PROVINCE_ID ) ;
ALTER TABLE TBL_PROVINCE ADD CONSTRAINT PROVINCE_COUNTRY_FK FOREIGN KEY ( COUNTRY_ID ) REFERENCES TBL_COUNTRY ( COUNTRY_ID ) ;

This runs perfectly fine in Oracle. Notice the COUNTRY_ID foreign key in the second table doesn't have "NOT NULL".

Now to insert a row into the PROVINCE table, it's sufficient to only specify the PROVINCE_ID. However, if you chose to specify a COUNTRY_ID as well, it must exist already in the COUNTRY table.

How to check whether a file is empty or not?

if for some reason you already had the file open you could try this:

>>> with open('New Text Document.txt') as my_file:
...     # I already have file open at this point.. now what?
...     my_file.seek(0) #ensure you're at the start of the file..
...     first_char = my_file.read(1) #get the first character
...     if not first_char:
...         print "file is empty" #first character is the empty string..
...     else:
...         my_file.seek(0) #first character wasn't empty, return to start of file.
...         #use file now
...
file is empty