Programs & Examples On #Text database

Fixed digits after decimal with f-strings

Adding to Rob's answer, you can use format specifiers with f strings (more here).

  • You can control the number of decimals:
pi = 3.141592653589793238462643383279

print(f'The first 6 decimals of pi are {pi:.6f}.')
The first 6 decimals of pi are 3.141593.
  • You can convert to percentage:
grade = 29/45

print(f'My grade rounded to 3 decimals is {grade:.3%}.')
My grade rounded to 3 decimals is 64.444%.
  • You can do other things like print constant length:
from random import randint
for i in range(5):
    print(f'My money is {randint(0, 150):>3}$')
My money is 126$
My money is   7$
My money is 136$
My money is  15$
My money is  88$
  • Or even print with a comma thousand separator:
print(f'I am worth {10000000000:,}$')
I am worth 10,000,000,000$

Html.DropDownList - Disabled/Readonly

Regarding the catch 22:

If we use @disabled, the field is not sent to the action (Mamoud) And if we use @readonly, the drop down bug still lets you change the value

Workaround: use @disabled, and add the field hidden after the drop down:

@Html.HiddenFor(model => model.xxxxxxxx)

Then it is truly disabled, and sent to the to the action too.

Reset IntelliJ UI to Default

Recent Versions

Window -> Restore Default Layout

(Thanks to Seven4X's answer)

Older Versions

You can simply delete the whole configuration folder ${user.home}/.IntelliJIdea60/config while IntelliJ IDEA is not running. Next time it restarts, everything is restored from the default settings.

It depends on the OS:

https://intellij-support.jetbrains.com/entries/23358108

Inheriting constructors

You have to explicitly define the constructor in B and explicitly call the constructor for the parent.

B(int x) : A(x) { }

or

B() : A(5) { }

Centering Bootstrap input fields

Well in my case the following work fine

<div class="card-body p-2">
  <div class="d-flex flex-row justify-content-center">
     <div style="margin: auto;">
        <input type="text" autocomplete="off"
          style="max-width:150px!important; "
          class="form-control form-control-sm font-weight-bold align-self-center w-25" id="dtTechState">
     </div>
  </div>
</div>

PRINT statement in T-SQL

I recently ran into this, and it ended up being because I had a convert statement on a null variable. Since that was causing errors, the entire print statement was rendering as null, and not printing at all.

Example - This will fail:

declare @myID int=null
print 'First Statement: ' + convert(varchar(4), @myID)

Example - This will print:

declare @myID int=null
print 'Second Statement: ' +  coalesce(Convert(varchar(4), @myID),'@myID is null')

Defining TypeScript callback type

I'm a little late, but, since some time ago in TypeScript you can define the type of callback with

type MyCallback = (KeyboardEvent) => void;

Example of use:

this.addEvent(document, "keydown", (e) => {
    if (e.keyCode === 1) {
      e.preventDefault();
    }
});

addEvent(element, eventName, callback: MyCallback) {
    element.addEventListener(eventName, callback, false);
}

How to deal with http status codes other than 200 in Angular 2

Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs for the same like this way

import {Observable} from 'rxjs/Rx';

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status === 500) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 400) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 409) {
                    return Observable.throw(new Error(error.status));
                }
                else if (error.status === 406) {
                    return Observable.throw(new Error(error.status));
                }
            });
    }

also you can handel error (with err block) that is throw by catch block while .map function,

like this -

...
.subscribe(res=>{....}
           err => {//handel here});

Update

as required for any status without checking particluar one you can try this: -

return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                if (res) {
                    if (res.status === 201) {
                        return [{ status: res.status, json: res }]
                    }
                    else if (res.status === 200) {
                        return [{ status: res.status, json: res }]
                    }
                }
            }).catch((error: any) => {
                if (error.status < 400 ||  error.status ===500) {
                    return Observable.throw(new Error(error.status));
                }
            })
            .subscribe(res => {...},
                       err => {console.log(err)} );

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Another great option is the free V-Tools addin for Microsoft Access. Among other helpful tools it has a form to edit and save the Import/Export specifications.

enter image description here

enter image description here

Note: As of version 1.83, there is a bug in enumerating the code pages on Windows 10. (Apparently due to a missing/changed API function in Windows 10) The tools still works great, you just need to comment out a few lines of code or step past it in the debug window.

This has been a real life-saver for me in editing a complex import spec for our online orders.

Expanding tuples into arguments

myfun(*some_tuple) does exactly what you request. The * operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.

How do you properly use WideCharToMultiByte

You use the lpMultiByteStr [out] parameter by creating a new char array. You then pass this char array in to get it filled. You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.

Here are a couple of useful helper functions for you, they show the usage of all parameters.

#include <string>

std::string wstrtostr(const std::wstring &wstr)
{
    // Convert a Unicode string to an ASCII string
    std::string strTo;
    char *szTo = new char[wstr.length() + 1];
    szTo[wstr.size()] = '\0';
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
    strTo = szTo;
    delete[] szTo;
    return strTo;
}

std::wstring strtowstr(const std::string &str)
{
    // Convert an ASCII string to a Unicode String
    std::wstring wstrTo;
    wchar_t *wszTo = new wchar_t[str.length() + 1];
    wszTo[str.size()] = L'\0';
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
    wstrTo = wszTo;
    delete[] wszTo;
    return wstrTo;
}

--

Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it. The function will use that pointer to fill your variable.

So you can understand this better:

//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
  *pX = 10;
}

int main(int argc, char ** argv)
{
  int X;
  fillXWith10(&X);
  return 0;
}

Is it possible to move/rename files in Git and maintain their history?

I make moving the files and then do

git add -A

which put in the sataging area all deleted/new files. Here git realizes that the file is moved.

git commit -m "my message"
git push

I do not know why but this works for me.

Change column type in pandas

this below code will change datatype of column.

df[['col.name1', 'col.name2'...]] = df[['col.name1', 'col.name2'..]].astype('data_type')

in place of data type you can give your datatype .what do you want like str,float,int etc.

Given URL is not allowed by the Application configuration

I ran into this with the IBM BlueMix SSO service and had to use the BlueMix provided redirect URL as my "site" URL instead of my actually web application site URL to fix it. Once I made that change the problem went away.

Turn off constraints temporarily (MS SQL)

You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE

ALTER TABLE foo NOCHECK CONSTRAINT ALL

or

ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column

Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.

Quadratic and cubic regression in Excel

The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.

Vertical Align Center in Bootstrap 4

you can vertically align your container by making the parent container flex and adding align-items:center:

body {
  display:flex;
  align-items:center;
}

Updated Pen

Converting binary to decimal integer output

The input may be string or integer.

num = 1000  #or num = '1000'  
sum(map(lambda x: x[1]*(2**x[0]), enumerate(map(int, str(num))[::-1])))

# 8

Visual Studio 2010 shortcut to find classes and methods?

try: ctrl + P

type: @

followed by the name of the class,method or variable name you search for.

How do I do a HTTP GET in Java?

Technically you could do it with a straight TCP socket. I wouldn't recommend it however. I would highly recommend you use Apache HttpClient instead. In its simplest form:

GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();

and here is a more complete example.

Delete specific values from column with where condition?

You can also use REPLACE():

UPDATE Table
   SET Column = REPLACE(Column, 'Test123', 'Test')

swift UITableView set rowHeight

Make sure Your TableView Delegate are working as well. if not then in your story board or in .xib press and hold Control + right click on tableView drag and Drop to your Current ViewController. swift 2.0

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 60.0;
}

Filter dict to contain only certain keys?

You could use python-benedict, it's a dict subclass.

Installation: pip install python-benedict

from benedict import benedict

dict_you_want = benedict(your_dict).subset(keys=['firstname', 'lastname', 'email'])

It's open-source on GitHub: https://github.com/fabiocaccamo/python-benedict


Disclaimer: I'm the author of this library.

Responsive Bootstrap Jumbotron Background Image

TLDR: Use background-size: 100% 100%;.

background-size: cover; may cut off some parts of the image producing poor results.

Using background-size: 100% 100%; you force the image to take up 100% of the parent element for both height and width.

See W3Schools for more information on this.

Here is a working, responsive jumbotron background image:

<div class="jumbotron"  style="background-image: url(http://yourImageUrl.jpg); background-size: 100% 100%;">
    <h1>Welcome</h1>
    <p class="lead">Your message here</p>
    <p><a href="http://www.YourLinkHere.com" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

How can I simulate a click to an anchor tag?

well, you can very quickly test the click dispatch via jQuery like so

$('#link-id').click();

If you're still having problem with click respecting the target, you can always do this

$('#link-id').click( function( event, anchor )
{
  window.open( anchor.href, anchor.target, '' );
  event.preventDefault();
  return false;
});

Landscape printing from HTML

My solution:

<style type="text/css" media="print">
    @page { 
        size: landscape;
    }
    body { 
        writing-mode: tb-rl;
    }
</style>

This works in IE, Firefox and Chrome

What's the difference between an argument and a parameter?

A parameter is something you have to fill in when you call a function. What you put in it is the argument.

Simply set: the argument goes into the parameter, an argument is the value of the parameter.

A bit more info on: http://en.wikipedia.org/wiki/Parameter_(computer_science)#Parameters_and_arguments

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

I use below code after js file include and it's working now.

<script src="js/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
    jQuery.browser = {};
    (function () {
        jQuery.browser.msie = false;
        jQuery.browser.version = 0;
        if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
            jQuery.browser.msie = true;
            jQuery.browser.version = RegExp.$1;
        }
    })();
</script>

Apache: "AuthType not set!" 500 Error

Remove the line that says

Require all granted

it's only needed on Apache >=2.4

Scroll part of content in fixed position container

Actually this is better way to do that. If height: 100% is used, the content goes off the border, but when it is 95% everything is in order:

div#scrollable {
    overflow-y: scroll;
    height: 95%;
}

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

Simple variant:

Regex.Replace(input, @"\r\n|\r|\n", "\r\n")

For better performance:

static Regex newline_pattern = new Regex(@"\r\n|\r|\n", RegexOptions.Compiled);
[...]
    newline_pattern.Replace(input, "\r\n");

Calling one Bash script from another Script passing it arguments with quotes and spaces

I found following program works for me

test1.sh 
a=xxx
test2.sh $a

in test2.sh you use $1 to refer variable a in test1.sh

echo $1

The output would be xxx

How to clear out session on log out

Go to file Global.asax.cs in your project and add the following code.

    protected void Application_BeginRequest()
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetExpires(DateTime.Now.AddHours(-1));
        Response.Cache.SetNoStore();
    }

It worked for me..! Reference link Clear session on Logout MVC 4

How do I match any character across multiple lines in a regular expression?

Use RegexOptions.Singleline, it changes the meaning of . to include newlines

Regex.Replace(content, searchText, replaceText, RegexOptions.Singleline);

rbind error: "names do not match previous names"

rbind() needs the two object names to be the same. For example, the first object names: ID Age, the next object names: ID Gender,if you want to use rbind(), it will print out:

names do not match previous names

Determine the number of lines within a text file

You can launch the "wc.exe" executable (comes with UnixUtils and does not need installation) run as an external process. It supports different line count methods (like unix vs mac vs windows).

How do you list all triggers in a MySQL database?

For showing a particular trigger in a particular schema you can try the following:

select * from information_schema.triggers where 
information_schema.triggers.trigger_name like '%trigger_name%' and 
information_schema.triggers.trigger_schema like '%data_base_name%'

Function to check if a string is a date

If you have PHP 5.2 Joey's answer won't work. You need to extend PHP's DateTime class:

class ExDateTime extends DateTime{
    public static function createFromFormat($frmt,$time,$timezone=null){
        $v = explode('.', phpversion());
        if(!$timezone) $timezone = new DateTimeZone(date_default_timezone_get());
        if(((int)$v[0]>=5&&(int)$v[1]>=2&&(int)$v[2]>17)){
            return parent::createFromFormat($frmt,$time,$timezone);
        }
        return new DateTime(date($frmt, strtotime($time)), $timezone);
    }
}

and than you can use this class without problems:

ExDateTime::createFromFormat('d.m.Y G:i',$timevar);

Argument Exception "Item with Same Key has already been added"

That Exception is thrown if there is already a key in the dictionary when you try to add the new one.

There must be more than one line in rct3Lines with the same first word. You can't have 2 entries in the same dictionary with the same key.

You need to decide what you want to happen if the key already exists - if you want to just update the value where the key exists you can simply

rct3Features[items[0]]=items[1]

but, if not you may want to test if the key already exists with:

if(rect3Features.ContainsKey(items[0]))
{
    //Do something
} 
else 
{
    //Do something else
}

Is it possible to make Font Awesome icons larger than 'fa-5x'?

  1. Just add the font awesome class like this:

    class="fa fa-plus-circle fa-3x"
    

    (You can increase the size as per 5x, 7x, 9x..)

  2. You can also add custom CSS.

Why does Firebug say toFixed() is not a function?

toFixed isn't a method of non-numeric variable types. In other words, Low and High can't be fixed because when you get the value of something in Javascript, it automatically is set to a string type. Using parseFloat() (or parseInt() with a radix, if it's an integer) will allow you to convert different variable types to numbers which will enable the toFixed() function to work.

var Low  = parseFloat($SliderValFrom.val()),
    High = parseFloat($SliderValTo.val());

Set Session variable using javascript in PHP

If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.

How to add url parameters to Django template url tag?

This can be done in three simple steps:

1) Add item id with url tag:

{% for item in post %}
<tr>
  <th>{{ item.id }}</th>
  <td>{{ item.title }}</td>
  <td>{{ item.body }}</td>
  <td>
    <a href={% url 'edit' id=item.id %}>Edit</a>
    <a href={% url 'delete' id=item.id %}>Delete</a>
  </td>
</tr>
{% endfor %}

2) Add path to urls.py:

path('edit/<int:id>', views.edit, name='edit')
path('delete/<int:id>', views.delete, name='delete')

3) Use the id on views.py:

def delete(request, id):
    obj = post.objects.get(id=id)
    obj.delete()

    return redirect('dashboard')

In SQL Server, how to create while loop in select

  1. Create function that parses incoming string (say "AABBCC") as a table of strings (in particular "AA", "BB", "CC").
  2. Select IDs from your table and use CROSS APPLY the function with data as argument so you'll have as many rows as values contained in the current row's data. No need of cursors or stored procs.

Creating random numbers with no duplicates

Your problem seems to reduce to choose k elements at random from a collection of n elements. The Collections.shuffle answer is thus correct, but as pointed out inefficient: its O(n).

Wikipedia: Fisher–Yates shuffle has a O(k) version when the array already exists. In your case, there is no array of elements and creating the array of elements could be very expensive, say if max were 10000000 instead of 20.

The shuffle algorithm involves initializing an array of size n where every element is equal to its index, picking k random numbers each number in a range with the max one less than the previous range, then swapping elements towards the end of the array.

You can do the same operation in O(k) time with a hashmap although I admit its kind of a pain. Note that this is only worthwhile if k is much less than n. (ie k ~ lg(n) or so), otherwise you should use the shuffle directly.

You will use your hashmap as an efficient representation of the backing array in the shuffle algorithm. Any element of the array that is equal to its index need not appear in the map. This allows you to represent an array of size n in constant time, there is no time spent initializing it.

  1. Pick k random numbers: the first is in the range 0 to n-1, the second 0 to n-2, the third 0 to n-3 and so on, thru n-k.

  2. Treat your random numbers as a set of swaps. The first random index swaps to the final position. The second random index swaps to the second to last position. However, instead of working against a backing array, work against your hashmap. Your hashmap will store every item that is out of position.

int getValue(i) { if (map.contains(i)) return map[i]; return i; } void setValue(i, val) { if (i == val) map.remove(i); else map[i] = val; } int[] chooseK(int n, int k) { for (int i = 0; i < k; i++) { int randomIndex = nextRandom(0, n - i); //(n - i is exclusive) int desiredIndex = n-i-1; int valAtRandom = getValue(randomIndex); int valAtDesired = getValue(desiredIndex); setValue(desiredIndex, valAtRandom); setValue(randomIndex, valAtDesired); } int[] output = new int[k]; for (int i = 0; i < k; i++) { output[i] = (getValue(n-i-1)); } return output; }

Using success/error/finally/catch with Promises in AngularJS

In Angular $http case, the success() and error() function will have response object been unwrapped, so the callback signature would be like $http(...).success(function(data, status, headers, config))

for then(), you probably will deal with the raw response object. such as posted in AngularJS $http API document

$http({
        url: $scope.url,
        method: $scope.method,
        cache: $templateCache
    })
    .success(function(data, status) {
        $scope.status = status;
        $scope.data = data;
    })
    .error(function(data, status) {
        $scope.data = data || 'Request failed';
        $scope.status = status;
    });

The last .catch(...) will not need unless there is new error throw out in previous promise chain.

How do I convert a Swift Array to a String?

if you have string array list , then convert to Int

let arrayList = list.map { Int($0)!} 
     arrayList.description

it will give you string value

How can I delete Docker's images?

I have found a solution with Powershell script that will do it for me.

The script at first stop all containers than remove all containers and then remove images that are named by the user.

Look here http://www.devcode4.com/article/powershell-remove-docker-containers-and-images

Convert .pfx to .cer

PFX files are PKCS#12 Personal Information Exchange Syntax Standard bundles. They can include arbitrary number of private keys with accompanying X.509 certificates and a certificate authority chain (set certificates).

If you want to extract client certificates, you can use OpenSSL's PKCS12 tool.

openssl pkcs12 -in input.pfx -out mycerts.crt -nokeys -clcerts

The command above will output certificate(s) in PEM format. The ".crt" file extension is handled by both macOS and Window.

You mention ".cer" extension in the question which is conventionally used for the DER encoded files. A binary encoding. Try the ".crt" file first and if it's not accepted, easy to convert from PEM to DER:

openssl x509 -inform pem -in mycerts.crt -outform der -out mycerts.cer

How do I style a <select> dropdown with only CSS?

The blog post How to CSS form drop down style no JavaScript works for me, but it fails in Opera though:

_x000D_
_x000D_
select {_x000D_
  border: 0 none;_x000D_
  color: #FFFFFF;_x000D_
  background: transparent;_x000D_
  font-size: 20px;_x000D_
  font-weight: bold;_x000D_
  padding: 2px 10px;_x000D_
  width: 378px;_x000D_
  *width: 350px;_x000D_
  *background: #58B14C;_x000D_
}_x000D_
_x000D_
#mainselection {_x000D_
  overflow: hidden;_x000D_
  width: 350px;_x000D_
  -moz-border-radius: 9px 9px 9px 9px;_x000D_
  -webkit-border-radius: 9px 9px 9px 9px;_x000D_
  border-radius: 9px 9px 9px 9px;_x000D_
  box-shadow: 1px 1px 11px #330033;_x000D_
  background: url("arrow.gif") no-repeat scroll 319px 5px #58B14C;_x000D_
}
_x000D_
<div id="mainselection">_x000D_
  <select>_x000D_
    <option>Select an Option</option>_x000D_
    <option>Option 1</option>_x000D_
    <option>Option 2</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

When to use RabbitMQ over Kafka?

The only benefit that I can think of is Transactional feature, rest all can be done by using Kafka

How to ping ubuntu guest on VirtualBox

If you start tinkering with VirtualBox network settings, watch out for this: you might make new network adapters (eth1, eth2), yet have your /etc/network/interfaces still configured for eth0.

Diagnose:

ethtool -i eth0
Cannot get driver information: no such device

Find your interfaces:

ls /sys/class/net
eth1 eth2 lo

Fix it:

Edit /etc/networking/interfaces and replace eth0 with the appropriate interface name (e.g eth1, eth2, etc.)

:%s/eth0/eth2/g

How to add new elements to an array?

If one really want to resize an array you could do something like this:

String[] arr = {"a", "b", "c"};
System.out.println(Arrays.toString(arr)); 
// Output is: [a, b, c]

arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
arr[3] = "d";
arr[4] = "e";
arr[5] = "f";

System.out.println(Arrays.toString(arr));
// Output is: [a, b, c, d, e, f, null, null, null, null]

How can I open a popup window with a fixed size using the HREF tag?

Since many browsers block popups by default and popups are really ugly, I recommend using lightbox or thickbox.

They are prettier and are not popups. They are extra HTML markups that are appended to your document's body with the appropriate CSS content.

http://jquery.com/demo/thickbox/

No Android SDK found - Android Studio

From the File menu, choose Project Structure (if you're running 0.4.4 there's a bug and the menu item doesn't have a title, but it still works), and choose the Android SDK item. You should see something like this where you can set up your JDK and SDK.

Project Structure dialog, Android SDK tab

After setting it, quit Android Studio and relaunch it for good measure.

How I could add dir to $PATH in Makefile?

What I usually do is supply the path to the executable explicitly:

EXE=./bin/
...
test all:
    $(EXE)x

I also use this technique to run non-native binaries under an emulator like QEMU if I'm cross compiling:

EXE = qemu-mips ./bin/

If make is using the sh shell, this should work:

test all:
    PATH=bin:$PATH x

Using python's eval() vs. ast.literal_eval()?

datamap = eval(input('Provide some data here: ')) means that you actually evaluate the code before you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also the dangers of eval.

ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.

Use ast.literal_eval whenever you need eval. You shouldn't usually evaluate literal Python statements.

jQuery return ajax result into outside variable

Using 'async': false to prevent asynchronous code is a bad practice,

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. https://xhr.spec.whatwg.org/

On the surface setting async to false fixes a lot of issues because, as the other answers show, you get your data into a variable. However, while waiting for the post data to return (which in some cases could take a few seconds because of database calls, slow connections, etc.) the rest of your Javascript functionality (like triggered events, Javascript handled buttons, JQuery transitions (like accordion, or autocomplete (JQuery UI)) will not be able to occur while the response is pending (which is really bad if the response never comes back as your site is now essentially frozen).

Try this instead,

var return_first;
function callback(response) {
  return_first = response;
  //use return_first variable here
}

$.ajax({
  'type': "POST",
  'global': false,
  'dataType': 'html',
  'url': "ajax.php?first",
  'data': { 'request': "", 'target': arrange_url, 'method': method_target },
  'success': function(data){
       callback(data);
  },
});

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

Is there an equivalent of 'which' on the Windows command line?

The GnuWin32 tools have which, along with a whole slew of other Unix tools.

Loop through list with both content and index

enumerate() makes this prettier:

for index, value in enumerate(S):
    print index, value

See here for more.

How to get everything after a certain character?

$string = "233718_This_is_a_string";
$withCharacter = strstr($string, '_'); // "_This_is_a_string"
echo substr($withCharacter, 1); // "This_is_a_string"

In a single statement it would be.

echo substr(strstr("233718_This_is_a_string", '_'), 1); // "This_is_a_string"

jQuery: Get the cursor position of text in input without browser specific code?

Using the syntax text_element.selectionStart we can get the starting position of the selection of a text in terms of the index of the first character of the selected text in the text_element.value and in case we want to get the same of the last character in the selection we have to use text_element.selectionEnd.

Use it as follows:

<input type=text id=t1 value=abcd>
<button onclick="alert(document.getElementById('t1').selectionStart)">check position</button>

I'm giving you the fiddle_demo

Can I have an onclick effect in CSS?

Edit: Answered before OP clarified what he wanted. The following is for an onclick similar to javascripts onclick, not the :active pseudo class.

This can only be achieved with either Javascript or the Checkbox Hack

The checkbox hack essentially gets you to click on a label, that "checks" a checkbox, allowing you to style the label as you wish.

The demo

How to pass multiple parameters from ajax to mvc controller?

Try this:

var req={StrContactDetails:'data',IsPrimary:'True'}

$.ajax({
                   type: 'POST',
                   data: req,
                   url: '@url.Action("SaveEmergencyContact","Dhp")',
                   contentType: "application/json; charset=utf-8",
                   dataType: "json",
                   data: JSON.stringify(req),
                   success: function (data) {
                       alert("Success");
                   },
                   error: function (ob, errStr) {
                       alert("An error occured.Please try after sometime.");
                   }
               });

http://api.jquery.com/jquery.ajax/

Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

Your server's response allows the request to include three specific non-simple headers:

Access-Control-Allow-Headers:origin, x-requested-with, content-type

but your request has a header not allowed by the server's response:

Access-Control-Request-Headers:access-control-allow-origin, content-type

All non-simple headers sent in a CORS request must be explicitly allowed by the Access-Control-Allow-Headers response header. The unnecessary Access-Control-Allow-Origin header sent in your request is not allowed by the server's CORS response. This is exactly what the "...not allowed by Access-Control-Allow-Headers" error message was trying to tell you.

There is no reason for the request to have this header: it does nothing, because Access-Control-Allow-Origin is a response header, not a request header.

Solution: Remove the setRequestHeader call that adds a Access-Control-Allow-Origin header to your request.

Center/Set Zoom of Map to cover all visible Markers?

You need to use the fitBounds() method.

var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
 bounds.extend(markers[i]);
}

map.fitBounds(bounds);

Documentation from developers.google.com/maps/documentation/javascript:

fitBounds(bounds[, padding])

Parameters:

`bounds`:  [`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1]
`padding` (optional):  number|[`Padding`][1]

Return Value: None

Sets the viewport to contain the given bounds.
Note: When the map is set to display: none, the fitBounds function reads the map's size as 0x0, and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden, thereby ensuring the map div has an actual size.

How to search if dictionary value contains certain string with Python

import re
for i in range(len(myDict.values())):
    for j in range(len(myDict.values()[i])):
         match=re.search(r'Mary', myDict.values()[i][j])
         if match:
                 print match.group() #Mary
                 print myDict.keys()[i] #firstName
                 print myDict.values()[i][j] #Mary-Ann

What is the point of the diamond operator (<>) in Java 7?

This line causes the [unchecked] warning:

List<String> list = new LinkedList();

So, the question transforms: why [unchecked] warning is not suppressed automatically only for the case when new collection is created?

I think, it would be much more difficult task then adding <> feature.

UPD: I also think that there would be a mess if it were legally to use raw types 'just for a few things'.

Your project contains error(s), please fix it before running it

What caused this problem for me was none of the above, but simply that I'd left the "debuggable" attribute to false in the manifest.xml file after doing a release. D'oh!

Of course neither the LogCat, Error log, Console, or Problems window alerted me to this..

How to define static constant in a class in swift

What about using computed properties?

class MyClass {
  class var myConstant: String { return "What is Love? Baby don't hurt me" }
}

MyClass.myConstant

How to set session variable in jquery?

Use localStorage to store the fact that you opened the page :

$(document).ready(function() {
    var yetVisited = localStorage['visited'];
    if (!yetVisited) {
        // open popup
        localStorage['visited'] = "yes";
    }
});

Read data from a text file using Java

You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here

and you can use the following method: FileUtils.readFileToString("yourFileName");

Hope it helps you..

Get the value for a listbox item by index

This works for me:

ListBox x = new ListBox();
x.Items.Add(new ListItem("Hello", "1"));
x.Items.Add(new ListItem("Bye", "2"));

Console.Write(x.Items[0].Value);

Binding a generic list to a repeater - ASP.NET

You should use ToList() method. (Don't forget about System.Linq namespace)

ex.:

IList<Model> models = Builder<Model>.CreateListOfSize(10).Build();
List<Model> lstMOdels = models.ToList();

Does it make sense to use Require.js with Angular.js?

Using RequireJS with AngularJS makes sense but only if you understand how each of them works regarding dependency injection, as although both of them injects dependencies, they inject very different things.

AngularJS has its own dependency system that let you inject AngularJS modules to a newly created module in order to reuse implementations. Let's say you created a "first" module that implements an AngularJS filter "greet":

angular
  .module('first', [])
  .filter('greet', function() {
    return function(name) {
      return 'Hello, ' + name + '!';
    }
  });

And now let's say you want to use the "greet" filter in another module called "second" that implements a "goodbye" filter. You may do that injecting the "first" module to the "second" module:

angular
  .module('second', ['first'])
  .filter('goodbye', function() {
    return function(name) {
      return 'Good bye, ' + name + '!';
    }
  });

The thing is that in order to make this work correctly without RequireJS, you have to make sure that the "first" AngularJS module is loaded on the page before you create the "second" AngularJS module. Quoting documentation:

Depending on a module implies that required module needs to be loaded before the requiring module is loaded.

In that sense, here is where RequireJS can help you as RequireJS provides a clean way to inject scripts to the page helping you organize script dependencies between each other.

Going back to the "first" and "second" AngularJS modules, here is how you can do it using RequireJS separating the modules on different files to leverage script dependencies loading:

// firstModule.js file
define(['angular'], function(angular) {
  angular
    .module('first', [])
    .filter('greet', function() {
      return function(name) {
        return 'Hello, ' + name + '!';
      }
    });
});
// secondModule.js file
define(['angular', 'firstModule'], function(angular) {
  angular
    .module('second', ['first'])
    .filter('goodbye', function() {
      return function(name) {
        return 'Good bye, ' + name + '!';
      }
    });
});

You can see that we are depending on "firstModule" file to be injected before the content of the RequireJS callback can be executed which needs "first" AngularJS module to be loaded to create "second" AngularJS module.

Side note: Injecting "angular" on the "firstModule" and "secondModule" files as dependency is required in order to use AngularJS inside the RequireJS callback function and it have to be configured on RequireJS config to map "angular" to the library code. You may have AngularJS loaded to the page in a traditional manner too (script tag) although defeats RequireJS benefits.

More details on having RequireJS support from AngularJS core from 2.0 version on my blog post.

Based on my blog post "Making sense of RequireJS with AngularJS", here is the link.

mysql alphabetical order

Wildcard Characters are used with like clause to sort records.

if we want to search a string which is starts with B then code is like the following:

select * from tablename where colname like 'B%' order by columnname ;

if we want to search a string which is ends with B then code is like the following: select * from tablename where colname like '%B' order by columnname ;

if we want to search a string which is contains B then code is like the following: select * from tablename where colname like '%B%' order by columnname ;

if we want to search a string in which second character is B then code is like the following: select * from tablename where colname like '_B%' order by columnname ;

if we want to search a string in which third character is B then code is like the following: select * from tablename where colname like '__B%' order by columnname ;

note : one underscore for one character.

Find distance between two points on map using Google Map API V2

The distance between two geo-coordinates can be found by using Haversine formula . This formula is effective to calculate distance in a spherical body i.e earth in our case.

How to enter newline character in Oracle?

According to the Oracle PLSQL language definition, a character literal can contain "any printable character in the character set". https://docs.oracle.com/cd/A97630_01/appdev.920/a96624/02_funds.htm#2876

@Robert Love's answer exhibits a best practice for readable code, but you can also just type in the linefeed character into the code. Here is an example from a Linux terminal using sqlplus:

SQL> set serveroutput on
SQL> begin   
  2  dbms_output.put_line( 'hello' || chr(10) || 'world' );
  3  end;
  4  /
hello
world

PL/SQL procedure successfully completed.

SQL> begin
  2  dbms_output.put_line( 'hello
  3  world' );
  4  end;
  5  /
hello
world

PL/SQL procedure successfully completed.

Instead of the CHR( NN ) function you can also use Unicode literal escape sequences like u'\0085' which I prefer because, well you know we are not living in 1970 anymore. See the equivalent example below:

SQL> begin
  2  dbms_output.put_line( 'hello' || u'\000A' || 'world' );
  3  end;
  4  /
hello
world

PL/SQL procedure successfully completed.

For fair coverage I guess it is worth noting that different operating systems use different characters/character sequences for end of line handling. You've got to have a think about the context in which your program output is going to be viewed or printed, in order to determine whether you are using the right technique.

  • Microsoft Windows: CR/LF or u'\000D\000A'
  • Unix (including Apple MacOS): LF or u'\000A'
  • IBM OS390: NEL or u'\0085'
  • HTML: '<BR>'
  • XHTML: '<br />'
  • etc. etc.

How to display my location on Google Maps for Android API v2

The API Guide has it all wrong (really Google?). With Maps API v2 you do not need to enable a layer to show yourself, there is a simple call to the GoogleMaps instance you created with your map.

Google Documentation

The actual documentation that Google provides gives you your answer. You just need to

If you are using Kotlin

// map is a GoogleMap object
map.isMyLocationEnabled = true


If you are using Java

// map is a GoogleMap object
map.setMyLocationEnabled(true);

and watch the magic happen.

Just make sure that you have location permission and requested it at runtime on API Level 23 (M) or above

Count specific character occurrences in a string

I use the following function. It is not the most memory efficient but it is very simple to understand, supports multiple compare methods, is only 4 lines, is fast, mostly works in VBA too, will find not just individual characters but any search string (I often search for VbCrLf (s)).

Only thing missing is the ability to start search from a different "Start"

    Function inStC(myInput As String, Search As String, Optional myCompareMethod As Long = CompareMethod.Text) As Long
        If InStr(1, myInput, Search, myCompareMethod) = 0 Then Return 0
        Return UBound(Split(myInput, Search,, myCompareMethod))
    End Function

One thing I like is that it is compact to use example.

str="the little red hen"
count=inStC(str,"e") 'count should equal 4
count=inStC(str,"t") 'count should equal 3

While I am here, I would like to shill my inStB function, which, instead of returning a count of a string, it will simply return a boolean if the search string is present. I need this function often and this makes my code cleaner.

Function inStB(myInput As String, Search As String, Optional Start As Long = 1, Optional myCompareMethod As Long = CompareMethod.Text) As Boolean
    If InStr(Start, myInput, Search, myCompareMethod) > 0 Then Return True
    Return False
End Function

Python function to convert seconds into minutes, hours, and days

To convert seconds (as string) into datetime, this could also help. You get number of days and seconds. Seconds can be further converted into minutes and hours.

from datetime import datetime, timedelta
sec = timedelta(seconds=(int(input('Enter the number of seconds: '))))
time = str(sec)

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

SMTP connect() failed PHPmailer - PHP

If anyone is still unable to solve the issue, please check following thread and follow callmebob's answer.

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

Laravel 5.4 Specific Table Migration

Just wanted to post another solution, which i think is worth mentioning.

  1. Find row with your migration name in migrations table and DELETE it. It should look like this: 2016_06_01_000001_create_oauth_auth_codes_table
  2. Remove your table from database e.g. DROP TABLE oauth_auth_codes
  3. Run php artisan migrate

It will migrate only the table you need, and won't touch anything else

How do I verify that an Android apk is signed with a release certificate?

Use this command : (Jarsigner is in your Java bin folder goto java->jdk->bin path in cmd prompt)

$ jarsigner -verify my_signed.apk

If the .apk is signed properly, Jarsigner prints "jar verified"

MySQL Multiple Left Joins

To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"

SELECT news.id, users.username, news.title, news.date,
       news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

Besides the HttpClient logging described in the other answer, you can also introduce a ClientHttpRequestInterceptor that reads the body of the request and the response and logs it. You might want to do this if other stuff also uses the HttpClient, or if you want a custom logging format. Caution: you will want to give the RestTemplate a BufferingClientHttpRequestFactory such that you can read the response twice.

System.Collections.Generic.List does not contain a definition for 'Select'

You need to have the System.Linq namespace included in your view since Select is an extension method. You have a couple of options on how to do this:

Add @using System.Linq to the top of your cshtml file.

If you find that you will be using this namespace often in many of your views, you can do this for all views by modifying the web.config inside of your Views folder (not the one at the root). You should see a pages/namespace XML element, create a new add child that adds System.Linq. Here is an example:

<configuration>
    <system.web.webPages.razor>
        <pages>
            <namespaces>
                <add namespace="System.Linq" />
            </namespaces>
        </pages>
    </system.web.webPages.razor>
</configuration>

Total memory used by Python process?

Current memory usage of the current process on Linux, for Python 2, Python 3, and pypy, without any imports:

def getCurrentMemoryUsage():
    ''' Memory usage in kB '''

    with open('/proc/self/status') as f:
        memusage = f.read().split('VmRSS:')[1].split('\n')[0][:-3]

    return int(memusage.strip())

It reads the status file of the current process, takes everything after VmRSS:, then takes everything before the first newline (isolating the value of VmRSS), and finally cuts off the last 3 bytes which are a space and the unit (kB).
To return, it strips any whitespace and returns it as a number.

Tested on Linux 4.4 and 4.9, but even an early Linux version should work: looking in man proc and searching for the info on the /proc/$PID/status file, it mentions minimum versions for some fields (like Linux 2.6.10 for "VmPTE"), but the "VmRSS" field (which I use here) has no such mention. Therefore I assume it has been in there since an early version.

Why would I use dirname(__FILE__) in an include or include_once statement?

I might have even a simpler explanation to this question compared to the accepted answer so I'm going to give it a go: Assume this is the structure of the files and directories of a project:

Project root directory:
                       file1.php
                       file3.php
                       dir1/
                            file2.php

(dir1 is a directory and file2.php is inside it)

And this is the content of each of the three files above:

//file1.php:
<?php include "dir1/file2.php"

//file2.php:
<?php include "../file3.php"

//file3.php:
<?php echo "Hello, Test!";

Now run file1.php and try to guess what should happen. You might expect to see "Hello, Test!", however, it won't be shown! What you'll get instead will be an error indicating that the file you have requested(file3.php) does not exist!

The reason is that, inside file1.php when you include file2.php, the content of it is getting copied and then pasted back directly into file1.php which is inside the root directory, thus this part "../file3.php" runs from the root directory and thus goes one directory up the root! (and obviously it won't find the file3.php).

Now, what should we do ?!

Relative paths of course have the problem above, so we have to use absolute paths. However, absolute paths have also one problem. If you (for example) copy the root folder (containing your whole project) and paste it in anywhere else on your computer, the paths will be invalid from that point on! And that'll be a REAL MESS!

So we kind of need paths that are both absolute and dynamic(Each file dynamically finds the absolute path of itself wherever we place it)!

The way we do that is by getting help from PHP, and dirname() is the function to go for, which gives the absolute path to the directory in which a file exists in. And each file name could also be easily accessed using the __FILE__ constant. So dirname(__FILE__) would easily give you the absolute (while dynamic!) path to the file we're typing in the above code. Now move your whole project to a new place, or even a new system, and tada! it works!

So now if we turn the project above to this:

//file1.php:
<?php include(dirname(__FILE__)."/dir1/file2.php");

//file2.php:
<?php include(dirname(__FILE__)."/../file3.php");

//file3.php:
<?php echo "Hello, Test!";

if you run it, you'll see the almighty Hello, Test!! (hopefully, if you've not done anything else wrong).

It's also worth mentioning that from PHP5, a nicer way(with regards to readability and preventing eye boilage!) has been provided by PHP as well which is the constant __DIR__ which does exactly the same thing as dirname(__FILE__)!

Hope that helps.

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

How to retrieve Key Alias and Key Password for signed APK in android studio(migrated from Eclipse)

I tried a lot of solves and only that work with me and i will share it with you

enter image description here

enter image description here

enter image description here

search by Ctrl + F

How do I uninstall a Windows service if the files do not exist anymore?

You have at least three options. I have presented them in order of usage preference.

Method 1 - You can use the SC tool (Sc.exe) included in the Resource Kit. (included with Windows 7/8)

Open a Command Prompt and enter

sc delete <service-name>

Tool help snippet follows:

DESCRIPTION:
        SC is a command line program used for communicating with the
        NT Service Controller and services.

delete----------Deletes a service (from the registry).

Method 2 - use delserv

Download and use delserv command line utility. This is a legacy tool developed for Windows 2000. In current Window XP boxes this was superseded by sc described in method 1.

Method 3 - manually delete registry entries (Note that this backfires in Windows 7/8)

Windows services are registered under the following registry key.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

Search for the sub-key with the service name under referred key and delete it. (and you might need to restart to remove completely the service from the Services list)

fatal error LNK1104: cannot open file 'kernel32.lib'

In Visual Studio 2017, I went to Project Properties -> Configuration Properties -> General, Selected All Platforms (1), then chose the dropdown (2) under Windows SDK Version and updated from 10.0.14393.0 to one that was installed (3). For me, that was 10.0.15063.0.

enter image description here

Additional details: This corrected the error in my case because Windows SDK Version helps VS select the correct paths. VC++ Directories -> Library Directories -> Edit -> Macros -> shows that macro $(WindowsSDK_LibraryPath_x86) has a path with the version number selected above.

@ViewChild in *ngIf

I think using defer from lodash makes a lot of sense especially in my case where my @ViewChild() was inside async pipe

Error when testing on iOS simulator: Couldn't register with the bootstrap server

I just had this happen to me: I was getting the error only on my device and the simulator was working fine. I ended up having to reset my device and the error went away.

How link to any local file with markdown syntax?

How are you opening the rendered Markdown?

If you host it over HTTP, i.e. you access it via http:// or https://, most modern browsers will refuse to open local links, e.g. with file://. This is a security feature:

For security purposes, Mozilla applications block links to local files (and directories) from remote files. This includes linking to files on your hard drive, on mapped network drives, and accessible via Uniform Naming Convention (UNC) paths. This prevents a number of unpleasant possibilities, including:

  • Allowing sites to detect your operating system by checking default installation paths
  • Allowing sites to exploit system vulnerabilities (e.g., C:\con\con in Windows 95/98)
  • Allowing sites to detect browser preferences or read sensitive data

There are some workarounds listed on that page, but my recommendation is to avoid doing this if you can.

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SSMS, "Query" menu item... "Results to"... "Results to File"

Shortcut = CTRL+shift+F

You can set it globally too

"Tools"... "Options"... "Query Results"... "SQL Server".. "Default destination" drop down

Edit: after comment

In SSMS, "Query" menu item... "SQLCMD" mode

This allows you to run "command line" like actions.

A quick test in my SSMS 2008

:OUT c:\foo.txt
SELECT * FROM sys.objects

Edit, Sep 2012

:OUT c:\foo.txt
SET NOCOUNT ON;SELECT * FROM sys.objects

How to define a two-dimensional array?

You should make a list of lists, and the best way is to use nested comprehensions:

>>> matrix = [[0 for i in range(5)] for j in range(5)]
>>> pprint.pprint(matrix)
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

On your [5][5] example, you are creating a list with an integer "5" inside, and try to access its 5th item, and that naturally raises an IndexError because there is no 5th item:

>>> l = [5]
>>> l[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

What command shows all of the topics and offsets of partitions in Kafka?

We're using Kafka 2.11 and make use of this tool - kafka-consumer-groups.

$ rpm -qf /bin/kafka-consumer-groups
confluent-kafka-2.11-1.1.1-1.noarch

For example:

$ kafka-consumer-groups --describe --group logstash | grep -E "TOPIC|filebeat"
Note: This will not show information about old Zookeeper-based consumers.
TOPIC            PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                     HOST             CLIENT-ID
beats_filebeat   0          20003914484     20003914888     404             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   1          19992522286     19992522709     423             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   2          19990597254     19990597637     383             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   7          19991718707     19991719268     561             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   8          20015611981     20015612509     528             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   5          19990536340     19990541331     4991            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   6          19990728038     19990733086     5048            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   3          19994613945     19994616297     2352            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0
beats_filebeat   4          19990681602     19990684038     2436            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0

Random Tip

NOTE: We use an alias that overloads kafka-consumer-groups like so in our /etc/profile.d/kafka.sh:

alias kafka-consumer-groups="KAFKA_JVM_PERFORMANCE_OPTS=\"-Djava.security.auth.login.config=$HOME/.kafka_client_jaas.conf\"  kafka-consumer-groups --bootstrap-server ${KAFKA_HOSTS} --command-config /etc/kafka/security-enabler.properties"

insert data into database with codeigniter

Try this in your model:

function order_summary_insert()
    $OrderLines=$this->input->post('orderlines');
    $CustomerName=$this->input->post('customer');
    $data = array(
        'OrderLines'=>$OrderLines,
        'CustomerName'=>$CustomerName
    );

    $this->db->insert('Customer_Orders',$data);
}

Try to use controller just to control the view and models always post your values in model. it makes easy to understand. Your controller will be:

function new_blank_order_summary() {
    $this->sales_model->order_summary_insert($data);
    $this->load->view('sales/new_blank_order_summary');
}

Java enum - why use toString instead of name

It really depends on what you want to do with the returned value:

  • If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overriden
  • If you want to print the enum constant in a user friendly way, you should use toString which may have been overriden (or not!).

When I feel that it might be confusing, I provide a more specific getXXX method, for example:

public enum Fields {
    LAST_NAME("Last Name"), FIRST_NAME("First Name");

    private final String fieldDescription;

    private Fields(String value) {
        fieldDescription = value;
    }

    public String getFieldDescription() {
        return fieldDescription;
    }
}

React prevent event bubbling in nested components on click

I had the same issue. I found stopPropagation did work. I would split the list item into a separate component, as so:

class List extends React.Component {
  handleClick = e => {
    // do something
  }

  render() {
    return (
      <ul onClick={this.handleClick}>
        <ListItem onClick={this.handleClick}>Item</ListItem> 
      </ul>
    )
  }
}

class ListItem extends React.Component {
  handleClick = e => {
    e.stopPropagation();  //  <------ Here is the magic
    this.props.onClick();
  }

  render() {
    return (
      <li onClick={this.handleClick}>
        {this.props.children}
      </li>       
    )
  }
}

How to write a foreach in SQL Server?

Here is the one of the better solutions.

DECLARE @i int
            DECLARE @curren_val int
            DECLARE @numrows int
            create table #Practitioner (idx int IDENTITY(1,1), PractitionerId int)
            INSERT INTO #Practitioner (PractitionerId) values (10),(20),(30)
            SET @i = 1
            SET @numrows = (SELECT COUNT(*) FROM #Practitioner)
            IF @numrows > 0
            WHILE (@i <= (SELECT MAX(idx) FROM #Practitioner))
            BEGIN

                SET @curren_val = (SELECT PractitionerId FROM #Practitioner WHERE idx = @i)

                --Do something with Id here
                PRINT @curren_val
                SET @i = @i + 1
            END

Here i've add some values in the table beacuse, initially it is empty.

We can access or we can do anything in the body of the loop and we can access the idx by defining it inside the table definition.

              BEGIN
                SET @curren_val = (SELECT PractitionerId FROM #Practitioner WHERE idx = @i)

                --Do something with Id here

                PRINT @curren_val
                SET @i = @i + 1
            END

Getting "type or namespace name could not be found" but everything seems ok?

I know this thread is old but anyway I'm sharing, I have to install all third part dependencies of the imported assembly - as the imported assembly wasn't included as Nuget package thus its dependencies were missing.

Hop this help :)

PHP, How to get current date in certain format

I belive the answer is:

echo date('Y-m-d H:i:s');

Checkout another branch when there are uncommitted changes on the current branch

You have two choices: stash your changes:

git stash

then later to get them back:

git stash apply

or put your changes on a branch so you can get the remote branch and then merge your changes onto it. That's one of the greatest things about git: you can make a branch, commit to it, then fetch other changes on to the branch you were on.

You say it doesn't make any sense, but you are only doing it so you can merge them at will after doing the pull. Obviously your other choice is to commit on your copy of the branch and then do the pull. The presumption is you either don't want to do that (in which case I am puzzled that you don't want a branch) or you are afraid of conflicts.

How to plot all the columns of a data frame in R

The ggplot2 package takes a little bit of learning, but the results look really nice, you get nice legends, plus many other nice features, all without having to write much code.

require(ggplot2)
require(reshape2)
df <- data.frame(time = 1:10,
                 a = cumsum(rnorm(10)),
                 b = cumsum(rnorm(10)),
                 c = cumsum(rnorm(10)))
df <- melt(df ,  id.vars = 'time', variable.name = 'series')

# plot on same grid, each series colored differently -- 
# good if the series have same scale
ggplot(df, aes(time,value)) + geom_line(aes(colour = series))

# or plot on different plots
ggplot(df, aes(time,value)) + geom_line() + facet_grid(series ~ .)

enter image description here enter image description here

JBoss default password

just commenting the line of user and password in file ./server/default/conf/props jmx-console-users.properties worked for me

What's the difference between OpenID and OAuth?

I am currently working on OAuth 2.0 and OpenID connect spec. So here is my understanding: Earlier they were:

  1. OpenID was proprietary implementation of Google allowing third party applications like for newspaper websites you can login using google and comment on an article and so on other usecases. So essentially, no password sharing to newspaper website. Let me put up a definition here, this approach in enterprise approach is called Federation. In Federation, You have a server where you authenticate and authorize (called IDP, Identity Provider) and generally the keeper of User credentials. the client application where you have business is called SP or Service Provider. If we go back to same newspaper website example then newspaper website is SP here and Google is IDP. In enterprise this problem was earlier solved using SAML. that time XML used to rule the software industry. So from webservices to configuration, everything used to go to XML so we have SAML, a complete Federation protocol
  2. OAuth: OAuth saw it's emergence as an standard looking at all these kind of proprietary approaches and so we had OAuth 1.o as standard but addressing only authorization. Not many people noticed but it kind of started picking up. Then we had OAuth 2.0 in 2012. CTOs, Architects really started paying attention as world is moving towards Cloud computing and with computing devices moving towards mobile and other such devices. OAuth kind of looked upon as solving major problem where software customers might give IDP Service to one company and have many services from different vendors like salesforce, SAP, etc. So integration here really looks like federation scenario bit one big problem, using SAML is costly so let's explore OAuth 2.o. Ohh, missed one important point that during this time, Google sensed that OAuth actually doesn't address Authentication, how will IDP give user data to SP (which is actually wonderfully addressed in SAML) and with other loose ends like:

    a. OAuth 2.o doesn't clearly say, how client registration will happen b. it doesn't mention anything about the interaction between SP (Resource Server) and client application (like Analytics Server providing data is Resource Server and application displaying that data is Client)

There are already wonderful answers given here technically, I thought of giving of giving brief evolution perspective

How to close a window using jQuery

just window.close() is OK, why should write in jQuery?

Why use 'git rm' to remove a file instead of 'rm'?

Adding to Andy's answer, there is additional utility to git rm:

  1. Safety: When doing git rm instead of rm, Git will block the removal if there is a discrepancy between the HEAD version of a file and the staging index or working tree version. This block is a safety mechanism to prevent removal of in-progress changes.

  2. Safeguarding: git rm --dry-run. This option is a safeguard that will execute the git rm command but not actually delete the files. Instead it will output which files it would have removed.

How to change the port of Tomcat from 8080 to 80?

Ubuntu 14.04 LTS, in Amazon EC2. The following steps resolved this issue for me:

1. Edit server.xml and change port="8080" to "80"

sudo vi /var/lib/tomcat7/conf/server.xml

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

2. Edit tomcat7 file (if the file is not created then you need to create it)

sudo vi /etc/default/tomcat7

uncomment and change #AUTHBIND=no to yes

3. Install authbind

sudo apt-get install authbind

4. Run the following commands to provide tomcat7 read+execute on port 80.

sudo touch /etc/authbind/byport/80
sudo chmod 500 /etc/authbind/byport/80
sudo chown tomcat7 /etc/authbind/byport/80

5. Restart tomcat:

sudo /etc/init.d/tomcat7 restart

did you specify the right host or port? error on Kubernetes

Regardless of your environment (gcloud or not ) , you need to point your kubectl to kubeconfig. By default, kubectl expects the path as $HOME/.kube/config or point your custom path as env variable (for scripting etc ) export KUBECONFIG=/your_kubeconfig_path

Please refer :: https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/

If you don't have a kubeconfig file for your cluster, create one by referring :: https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/

It is required to find cluster's ca.crt , apiserver-kubelet-client key and cert.

Ubuntu, how do you remove all Python 3 but not 2

So I worked out at the end that you cannot uninstall 3.4 as it is default on Ubuntu.

All I did was simply remove Jupyter and then alias python=python2.7 and install all packages on Python 2.7 again.

Arguably, I can install virtualenv but me and my colleagues are only using 2.7. I am just going to be lazy in this case :)

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

What does getActivity() mean?

getActivity() is used for fragment. For activity, wherever you can use this, you can replace the this in fragment in similar cases with getActivity().

How does Facebook Sharer select Images and other metadata when sharing my URL?

Use facebook feed dialog instead of share dialog to show custom Images

Example:

https://www.facebook.com/dialog/feed?app_id=1389892087910588
&redirect_uri=https://scotch.io
&link=https://scotch.io
&picture=http://placekitten.com/500/500
&caption=This%20is%20the%20caption
&description=This%20is%20the%20description

Best way to compare 2 XML documents in Java

The following will check if the documents are equal using standard JDK libraries.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setCoalescing(true);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setIgnoringComments(true);
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc1 = db.parse(new File("file1.xml"));
doc1.normalizeDocument();

Document doc2 = db.parse(new File("file2.xml"));
doc2.normalizeDocument();

Assert.assertTrue(doc1.isEqualNode(doc2));

normalize() is there to make sure there are no cycles (there technically wouldn't be any)

The above code will require the white spaces to be the same within the elements though, because it preserves and evaluates it. The standard XML parser that comes with Java does not allow you to set a feature to provide a canonical version or understand xml:space if that is going to be a problem then you may need a replacement XML parser such as xerces or use JDOM.

How to change line color in EditText

Its pretty simple (Required: Minimum API 21)...

  1. Go to your xml and select the EditText field
  2. On the right side, you can see the 'Attributes' window. Select 'View All Attributes'
  3. Just search for 'tint'
  4. And add/change the 'backgroundTint' to a desired color hex (say #FF0000)

enter image description here

enter image description here

Keep Coding........ :)

Unable to preventDefault inside passive event listener

For me

document.addEventListener("mousewheel", this.mousewheel.bind(this), { passive: false });

did the trick (the { passive: false } part).

Finding all possible combinations of numbers to reach a given sum

Perl version (of the leading answer):

use strict;

sub subset_sum {
  my ($numbers, $target, $result, $sum) = @_;

  print 'sum('.join(',', @$result).") = $target\n" if $sum == $target;
  return if $sum >= $target;

  subset_sum([@$numbers[$_ + 1 .. $#$numbers]], $target, 
             [@{$result||[]}, $numbers->[$_]], $sum + $numbers->[$_])
    for (0 .. $#$numbers);
}

subset_sum([3,9,8,4,5,7,10,6], 15);

Result:

sum(3,8,4) = 15
sum(3,5,7) = 15
sum(9,6) = 15
sum(8,7) = 15
sum(4,5,6) = 15
sum(5,10) = 15

Javascript version:

_x000D_
_x000D_
const subsetSum = (numbers, target, partial = [], sum = 0) => {_x000D_
  if (sum < target)_x000D_
    numbers.forEach((num, i) =>_x000D_
      subsetSum(numbers.slice(i + 1), target, partial.concat([num]), sum + num));_x000D_
  else if (sum == target)_x000D_
    console.log('sum(%s) = %s', partial.join(), target);_x000D_
}_x000D_
_x000D_
subsetSum([3,9,8,4,5,7,10,6], 15);
_x000D_
_x000D_
_x000D_

Javascript one-liner that actually returns results (instead of printing it):

_x000D_
_x000D_
const subsetSum=(n,t,p=[],s=0,r=[])=>(s<t?n.forEach((l,i)=>subsetSum(n.slice(i+1),t,[...p,l],s+l,r)):s==t?r.push(p):0,r);_x000D_
_x000D_
console.log(subsetSum([3,9,8,4,5,7,10,6], 15));
_x000D_
_x000D_
_x000D_

And my favorite, one-liner with callback:

_x000D_
_x000D_
const subsetSum=(n,t,cb,p=[],s=0)=>s<t?n.forEach((l,i)=>subsetSum(n.slice(i+1),t,cb,[...p,l],s+l)):s==t?cb(p):0;_x000D_
_x000D_
subsetSum([3,9,8,4,5,7,10,6], 15, console.log);
_x000D_
_x000D_
_x000D_

Java FileWriter how to write to next Line

I'm not sure if I understood correctly, but is this what you mean?

out.write("this is line 1");
out.newLine();
out.write("this is line 2");
out.newLine();
...

Unique constraint on multiple columns

By using the constraint definition on table creation, you can specify one or multiple constraints that span multiple columns. The syntax, simplified from technet's documentation, is in the form of:

CONSTRAINT constraint_name UNIQUE [ CLUSTERED | NONCLUSTERED ] 
(
    column [ ASC | DESC ] [ ,...n ]
)

Therefore, the resuting table definition would be:

CREATE TABLE [dbo].[user](
    [userID] [int] IDENTITY(1,1) NOT NULL,
    [fcode] [int] NULL,
    [scode] [int] NULL,
    [dcode] [int] NULL,
    [name] [nvarchar](50) NULL,
    [address] [nvarchar](50) NULL,
    CONSTRAINT [PK_user_1] PRIMARY KEY CLUSTERED 
    (
        [userID] ASC
    ),
    CONSTRAINT [UQ_codes] UNIQUE NONCLUSTERED
    (
        [fcode], [scode], [dcode]
    )
) ON [PRIMARY]

Understanding unique keys for array children in React.js

Warning: Each child in an array or iterator should have a unique "key" prop.

This is a warning as for array items which we are going to iterate over will need a unique resemblance.

React handles iterating component rendering as arrays.

Better way to resolve this is provide index on the array items you are going to iterate over.for example:

class UsersState extends Component
    {
        state = {
            users: [
                {name:"shashank", age:20},
                {name:"vardan", age:30},
                {name:"somya", age:40}
            ]
        }
    render()
        {
            return(
                    <div>
                        {
                            this.state.users.map((user, index)=>{
                                return <UserState key={index} age={user.age}>{user.name}</UserState>
                            })
                        }
                    </div>
                )
        }

index is React built-in props.

How do I add multiple conditions to "ng-disabled"?

Wanny is correct. The && operator doesn't work in HTML. With Angular, you must use the double pipes (||)for multiple conditions.

How to select an item from a dropdown list using Selenium WebDriver with java?

public class checkBoxSel {

    public static void main(String[] args) {

         WebDriver driver = new FirefoxDriver();
         EventFiringWebDriver dr = null ;


         dr = new EventFiringWebDriver(driver);
         dr.get("http://www.google.co.in/");

         dr.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

         dr.findElement(By.linkText("Gmail")).click() ;

         Select sel = new Select(driver.findElement(By.tagName("select")));
         sel.selectByValue("fil");

    }

}

I am using GOOGLE LOGIN PAGE to test the seletion option. The above example was to find and select language "Filipino" from the drop down list. I am sure this will solve the problem.

How to reset or change the passphrase for a GitHub SSH key?

In short there's no way to recover the passphrase for a pair of SSH keys. Why? Because it was intended this way in the first place for security reasons. The answers the other people gave you are all correct ways to CHANGE the password of your keys, not to recover them. So if you've forgotten your passphrase, the best you can do is create a new pair of SSH keys. Here's how to generate SSH keys and add it to your GitHub account.

Add CSS box shadow around the whole DIV

Use this below code

 border:2px soild #eee;

 margin: 15px 15px;
 -webkit-box-shadow: 2px 3px 8px #eee;
-moz-box-shadow: 2px 3px 8px #eee;
box-shadow: 2px 3px 8px #eee;

Explanation:-

box-shadow requires you to set the horizontal & vertical offsets, you can then optionally set the blur and colour, you can also choose to have the shadow inset instead of the default outset. Colour can be defined as hex or rgba.

box-shadow : inset/outset h-offset v-offset blur spread color;

Explanation of the values...

inset/outset -- whether the shadow is inside or outside the box. If not specified it will default to outset.

h-offset -- the horizontal offset of the shadow (required value)

v-offset -- the vertical offset of the shadow (required value)

blur -- as it says, the blur of the shadow

spread -- moves the shadow away from the box equally on all sides. A positive value causes the shadow to expand, negative causes it to contract. Though this value isn't often used, it is useful with multiple shadows.

color -- as it says, the color of the shadow

Usage

box-shadow:2px 3px 8px #eee; a gray shadow with a horizontal outset of 2px, vertical of 3px and a blur of 8px

How do I change the default library path for R packages

See help(Startup) and help(.libPaths) as you have several possibilities where this may have gotten set. Among them are

  • setting R_LIBS_USER
  • assigning .libPaths() in .Rprofile or Rprofile.site

and more.

In this particular case you need to go backwards and unset whereever \\\\The library/path/I/don't/want is set.

To otherwise ignore it you need to override it use explicitly i.e. via

library("somePackage", lib.loc=.libPaths()[-1])

when loading a package.

Using subprocess to run Python script on Windows

It looks like windows tries to run the script using its own EXE framework rather than call it like

python /the/script.py

Try,

subprocess.Popen(["python", "/the/script.py"])

Edit: "python" would need to be on your path.

How to check if a "lateinit" variable has been initialized?

There is a lateinit improvement in Kotlin 1.2 that allows to check the initialization state of lateinit variable directly:

lateinit var file: File    

if (this::file.isInitialized) { ... }

See the annoucement on JetBrains blog or the KEEP proposal.

UPDATE: Kotlin 1.2 has been released. You can find lateinit enhancements here:

jQuery select change event get selected option

$('#_SelectID').change(function () {
        var SelectedText = $('option:selected',this).text();
        var SelectedValue = $('option:selected',this).val();
});

How to create many labels and textboxes dynamically depending on the value of an integer variable?

You can try this:

int cleft = 1;
intaleft = 1;
private void button2_Click(object sender, EventArgs e) 
{
     TextBox txt = new TextBox();
     this.Controls.Add(txt);
     txt.Top = cleft * 40;
     txt.Size = new Size(200, 16);
     txt.Left = 150;
     cleft = cleft + 1;
     Label lbl = new Label();
     this.Controls.Add(lbl);
     lbl.Top = aleft * 40;
     lbl.Size = new Size(100, 16);
     lbl.ForeColor = Color.Blue;
     lbl.Text = "BoxNo/CardNo";
     lbl.Left = 70;
     aleft = aleft + 1;
     return;
}
private void btd_Click(object sender, EventArgs e)
{ 
    //Here you Delete Text Box One By One(int ix for Text Box)
    for (int ix = this.Controls.Count - 2; ix >= 0; ix--)
    //Here you Delete Lable One By One(int ix for Lable)
    for (int x = this.Controls.Count - 2; x >= 0; x--)
    {
        if (this.Controls[ix] is TextBox) 
        this.Controls[ix].Dispose();
        if (this.Controls[x] is Label) 
        this.Controls[x].Dispose();
        return;
    }
}

Random float number generation

If you are using C++ and not C, then remember that in technical report 1 (TR1) and in the C++0x draft they have added facilities for a random number generator in the header file, I believe it is identical to the Boost.Random library and definitely more flexible and "modern" than the C library function, rand.

This syntax offers the ability to choose a generator (like the mersenne twister mt19937) and then choose a distribution (normal, bernoulli, binomial etc.).

Syntax is as follows (shameless borrowed from this site):

  #include <iostream>
  #include <random>

  ...

  std::tr1::mt19937 eng;  // a core engine class 
  std::tr1::normal_distribution<float> dist;     

  for (int i = 0; i < 10; ++i)        
      std::cout << dist(eng) << std::endl;

Using group by on two fields and count in SQL

You must group both columns, group and sub-group, then use the aggregate function COUNT().

SELECT
  group, subgroup, COUNT(*)
FROM
  groups
GROUP BY
  group, subgroup

How can I convert IPV6 address to IPV4 address?

Some googling led me to the following post:

http://www.developerweb.net/forum/showthread.php?t=3434

The code provided in the post is in C, but it shouldn't be too hard to rewrite it to Java.

Substring with reverse index

Although this is an old question, to support answer by user187291

In case of fixed length of desired substring I would use substr() with negative argument for its short and readable syntax

"xxx_456".substr(-3)

For now it is compatible with common browsers and not yet strictly deprecated.

How to count the number of observations in R like Stata command count

You can also use the filter function from the dplyr package which returns rows with matching conditions.

> library(dplyr)

> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2

if block inside echo statement?

In sake of readability it should be something like

<?php 
  $countries = $myaddress->get_countries();
  foreach($countries as $value) {
    $selected ='';
    if($value=='United States') $selected ='selected="selected"'; 
    echo '<option value="'.$value.'"'.$selected.'>'.$value.'</option>';
  }
?>

desire to stuff EVERYTHING in a single line is a decease, man. Write distinctly.

But there is another way, a better one. There is no need to use echo at all. Learn to use templates. Prepare your data first, and display it only then ready.

Business logic part:

$countries = $myaddress->get_countries();
$selected_country = 1;    

Template part:

<? foreach($countries as $row): ?>
<option value="<?=$row['id']?>"<? if ($row['id']==$current_country):> "selected"><? endif ?>
  <?=$row['name']?>
</option>
<? endforeach ?>

How to drop a PostgreSQL database if there are active connections to it?

I noticed that postgres 9.2 now calls the column pid rather than procpid.

I tend to call it from the shell:

#!/usr/bin/env bash
# kill all connections to the postgres server
if [ -n "$1" ] ; then
  where="where pg_stat_activity.datname = '$1'"
  echo "killing all connections to database '$1'"
else
  echo "killing all connections to database"
fi

cat <<-EOF | psql -U postgres -d postgres 
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
${where}
EOF

Hope that is helpful. Thanks to @JustBob for the sql.

How to convert a DataFrame back to normal RDD in pyspark?

Use the method .rdd like this:

rdd = df.rdd

Difference in months between two dates

You can use Noda Time https://nodatime.org/

LocalDate start = new LocalDate(2010, 1, 5);
LocalDate end = new LocalDate(2012, 6, 1);
Period period = Period.Between(start, end, PeriodUnits.Months);
Console.WriteLine(period.Months);

How to overplot a line on a scatter plot in python?

Another way to do it, using axes.get_xlim():

import matplotlib.pyplot as plt
import numpy as np

def scatter_plot_with_correlation_line(x, y, graph_filepath):
    '''
    http://stackoverflow.com/a/34571821/395857
    x does not have to be ordered.
    '''
    # Create scatter plot
    plt.scatter(x, y)

    # Add correlation line
    axes = plt.gca()
    m, b = np.polyfit(x, y, 1)
    X_plot = np.linspace(axes.get_xlim()[0],axes.get_xlim()[1],100)
    plt.plot(X_plot, m*X_plot + b, '-')

    # Save figure
    plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight')

def main():
    # Data
    x = np.random.rand(100)
    y = x + np.random.rand(100)*0.1

    # Plot
    scatter_plot_with_correlation_line(x, y, 'scatter_plot.png')

if __name__ == "__main__":
    main()
    #cProfile.run('main()') # if you want to do some profiling

enter image description here

phpMyAdmin says no privilege to create database, despite logged in as root user

Look at the user and host column of your permission. Where you are coming from localhost or some other IPs do make a difference.

Apache Prefork vs Worker MPM

For CentOS 6.x and 7.x (including Amazon Linux) use:

sudo httpd -V

This will show you which of the MPMs are configured. Either prefork, worker, or event. Prefork is the earlier, threadsafe model. Worker is multi-threaded, and event supports php-mpm which is supposed to be a better system for handling threads and requests.

However, your results may vary, based on configuration. I've seen a lot of instability in php-mpm and not any speed improvements. An aggressive spider can exhaust the maximum child processes in php-mpm quite easily.

The setting for prefork, worker, or event is set in sudo nano /etc/httpd/conf.modules.d/00-mpm.conf (for CentOS 6.x/7.x/Apache 2.4).

# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:

# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
#LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#LoadModule mpm_worker_module modules/mod_mpm_worker.so

# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#LoadModule mpm_event_module modules/mod_mpm_event.so

How to pass an object from one activity to another on Android

I am using parcelable to send data from one activity to another acivity. Here is my code that works fine in my project.

public class Channel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String uniqueID;
    private String name;
    private String logo;
    private String thumb;


    /**
     * @return The cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *     The cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return The uniqueID
     */
    public String getUniqueID() {
        return uniqueID;
    }

    /**
     * @param uniqueID
     *     The uniqueID to set
     */
    public void setUniqueID(String uniqueID) {
        this.uniqueID = uniqueID;
    }

    /**
     * @return The name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            The name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the logo
     */
    public String getLogo() {
        return logo;
    }

    /**
     * @param logo
     *     The logo to set
     */
    public void setLogo(String logo) {
        this.logo = logo;
    }

    /**
     * @return the thumb
     */
    public String getThumb() {
        return thumb;
    }

    /**
     * @param thumb
     *     The thumb to set
     */
    public void setThumb(String thumb) {
        this.thumb = thumb;
    }


    public Channel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<Channel> CREATOR = new Parcelable.Creator<Channel>() {
        public Channel createFromParcel(Parcel in) {
            return new Channel(in);
        }

        public Channel[] newArray(int size) {

            return new Channel[size];
        }
    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[5];
        in.readStringArray(result);

        this.cid = result[0];
        this.uniqueID = result[1];
        this.name = result[2];
        this.logo = result[3];
        this.thumb = result[4];
    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {

        dest.writeStringArray(new String[] { this.cid, this.uniqueID,
                this.name, this.logo, this.thumb});
    }
}

In activityA use it like this:

Bundle bundle = new Bundle();
bundle.putParcelableArrayList("channel",(ArrayList<Channel>) channels);
Intent intent = new Intent(ActivityA.this,ActivityB.class);
intent.putExtras(bundle);
startActivity(intent);

In ActivityB use it like this to get data:

Bundle getBundle = this.getIntent().getExtras();
List<Channel> channelsList = getBundle.getParcelableArrayList("channel");

What is LDAP used for?

  • LDAP main usage is to provider faster retrieval of data . It acts as a central repository for storing user details that can be accessed by various application at same time .

  • The data that is read various time but we rarely update the data then LDAP is better option as it is faster to read in it because of its structure but updating(add/updatee or delete) is bit tedious job in case of LDAP

  • Security provided by LDAP : LDAP can work with SSL & TLS and thus can be used for sensitive information .

  • LDAP also can work with number of database providing greater flexibility to choose database best suited for our environment

  • Can be a better option for synchronising information between master and its replicase
  • LDAP apart from supporting the data recovery capability .Also , allows us to export data into LDIF file that can be read by various software available in the market

Javascript - validation, numbers only

If you are using React, just do:

<input
  value={this.state.input}
  placeholder="Enter a number"
  onChange={e => this.setState({ input: e.target.value.replace(/[^0-9]/g, '') })}
/>

_x000D_
_x000D_
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>_x000D_
<script type="text/babel">_x000D_
class Demo extends React.Component {_x000D_
    state = {_x000D_
      input: '',_x000D_
    }_x000D_
    _x000D_
    onChange = e => {_x000D_
      let input = e.target.value.replace(/[^0-9]/g, '');_x000D_
      this.setState({ input });_x000D_
    }_x000D_
    _x000D_
    render() {_x000D_
        return (_x000D_
          <div>_x000D_
            <input_x000D_
              value={this.state.input}_x000D_
              placeholder="Enter a number"_x000D_
              onChange={this.onChange}_x000D_
            />_x000D_
            <br />_x000D_
            <h1>{this.state.input}</h1>_x000D_
           </div>_x000D_
        );_x000D_
    }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Demo />, document.getElementById('root'));_x000D_
</script>
_x000D_
_x000D_
_x000D_

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

You need to open the file in binary mode i.e. wb instead of w. If you don't, the end of line characters are auto-converted to OS specific ones.

Here is an excerpt from Python reference about open().

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

select2 - hiding the search box

This is the best solution, clean and work good :

$("#select2Id").select2 () ;
$("#select2Id").select2 ('container').find ('.select2-search').addClass ('hidden') ;

Then, create a class .hidden { display;none; }

How to perform Unwind segue programmatically?

I used [self dismissViewControllerAnimated: YES completion: nil]; which will return you to the calling ViewController.

Is SQL syntax case sensitive?

I found this blog post to be very helpful (I am not the author). Summarizing (please read, though):

...delimited identifiers are case sensitive ("table_name" != "Table_Name"), while non quoted identifiers are not, and are transformed to upper case (table_name => TABLE_NAME).

He found DB2, Oracle and Interbase/Firebird are 100% compliant:

PostgreSQL ... lowercases every unquoted identifier, instead of uppercasing it. MySQL ... file system dependent. SQLite and SQL Server ... case of the table and field names are preserved on creation, but they are completely ignored afterwards.

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

javascript getting my textbox to display a variable

_x000D_
_x000D_
function myfunction() {_x000D_
  var first = document.getElementById("textbox1").value;_x000D_
  var second = document.getElementById("textbox2").value;_x000D_
  var answer = parseFloat(first) + parseFloat(second);_x000D_
_x000D_
  var textbox3 = document.getElementById('textbox3');_x000D_
  textbox3.value = answer;_x000D_
}
_x000D_
<input type="text" name="textbox1" id="textbox1" /> + <input type="text" name="textbox2" id="textbox2" />_x000D_
<input type="submit" name="button" id="button1" onclick="myfunction()" value="=" />_x000D_
<br/> Your answer is:--_x000D_
<input type="text" name="textbox3" id="textbox3" readonly="true" />
_x000D_
_x000D_
_x000D_

"Couldn't read dependencies" error with npm

1)Nodejs installs in C:\ProgramFiles in some cases. Try installing in C: drive or another directory if you don't have admin rights.

2)Make sure you are not installing behind a company's proxy setting. This can sometimes affect installation.

3) Finally, make sure you run the npm command from this directory: Path\nodejs\node_modules\npm where Path is your own directory.

Open files always in a new tab

you need edit setting.json file,

settings.json, located at

Windows %APPDATA%\Code\User\settings.json
macOS $HOME/Library/Application Support/Code/User/settings.json
Linux $HOME/.config/Code/User/settings.json


        {
          "workbench.editor.showTabs": true,
          "workbench.editor.enablePreview": false
        }

Entity Framework The underlying provider failed on Open

I was facing the same error today, what I was doing wrong was that I was not adding Password tag in the connection string. As soon as I added the Password tag with correct password the error went away. Hope it helps someone.

Does Java have a complete enum for HTTP response codes?

Use javax.servlet.http.HttpServletResponse class

Example:

javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED //401
javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR //500

Matching an optional substring in a regex

You can do this:

([0-9]+) (\([^)]+\))? Z

This will not work with nested parens for Y, however. Nesting requires recursion which isn't strictly regular any more (but context-free). Modern regexp engines can still handle it, albeit with some difficulties (back-references).

How to trigger the onclick event of a marker on a Google Maps V3?

For future Googlers, If you get an error similar below after you trigger click for a polygon

"Uncaught TypeError: Cannot read property 'vertex' of undefined"

then try the code below

google.maps.event.trigger(polygon, "click", {});

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

Run an Ansible task only when the variable contains a specific string

This example uses regex_search to perform a substring search.

- name: make conditional variable
  command: "file -s /dev/xvdf"
  register: fsm_out

- name: makefs
  command: touch "/tmp/condition_satisfied"
  when: fsm_out.stdout | regex_search(' data')

ansible version: 2.4.3.0

Google Maps: Auto close open InfoWindows?

Here is what I used if you are using many markers in a for loop (Django here). You can set an index on each marker and set that index every time you open a window. Closing the previously saved index:

markers = Array();
infoWindows = Array();
var prev_infowindow =false;
{% for obj in objects %}
var contentString = 'your content'
var infowindow = new google.maps.InfoWindow({
            content: contentString,
          });
var marker = new google.maps.Marker({
               position: {lat: {{ obj.lat }}, lng: {{ obj.lon }}},
               map: map,
               title: '{{ obj.name }}',
               infoWindowIndex : {{ forloop.counter0 }}
          });
google.maps.event.addListener(marker, 'click',
            function(event)
            {
           if( prev_infowindow ) {
               infoWindows[prev_infowindow].close();
                }
                prev_infowindow = this.infoWindowIndex;
                infoWindows[this.infoWindowIndex].open(map, this);
            }
        );

        infoWindows.push(infowindow);
        markers.push(marker);

      {% endfor %}

How do I put double quotes in a string in vba?

Another work-around is to construct a string with a temporary substitute character. Then you can use REPLACE to change each temp character to the double quote. I use tilde as the temporary substitute character.

Here is an example from a project I have been working on. This is a little utility routine to repair a very complicated formula if/when the cell gets stepped on accidentally. It is a difficult formula to enter into a cell, but this little utility fixes it instantly.

Sub RepairFormula()
Dim FormulaString As String

FormulaString = "=MID(CELL(~filename~,$A$1),FIND(~[~,CELL(~filename~,$A$1))+1,FIND(~]~, CELL(~filename~,$A$1))-FIND(~[~,CELL(~filename~,$A$1))-1)"
FormulaString = Replace(FormulaString, Chr(126), Chr(34)) 'this replaces every instance of the tilde with a double quote.
Range("WorkbookFileName").Formula = FormulaString

This is really just a simple programming trick, but it makes entering the formula in your VBA code pretty easy.

How can I loop through all rows of a table? (MySQL)

You should really use a set based solution involving two queries (basic insert):

INSERT INTO TableB (Id2Column, Column33, Column44)
SELECT id, column1, column2 FROM TableA

UPDATE TableA SET column1 = column2 * column3

And for your transform:

INSERT INTO TableB (Id2Column, Column33, Column44)
SELECT 
    id, 
    column1 * column4 * 100, 
    (column2 / column12) 
FROM TableA

UPDATE TableA SET column1 = column2 * column3

Now if your transform is more complicated than that and involved multiple tables, post another question with the details.

This Activity already has an action bar supplied by the window decor

I solved it by removing this line:

android:theme="@style/Theme.MyCompatTheme"

from activity properties in the Manifest file

Understanding the grid classes ( col-sm-# and col-lg-# ) in Bootstrap 3

To amend SDP's answer above, you do NOT need to declarecol-xs-12 in <div class="col-xs-12 col-sm-6">. Bootstrap 3 is mobile-first, so every div column is assumed to be a 100% width div by default - which means at the "xs" size it is 100% width, it will always default to that behavior regardless of what you set at sm, md, lg. If you want your xs columns to be not 100%, then you normally do a col-xs-(1-11).

Line Break in XML?

If you are using CSS to style (Not recommended.) you can use display:block;, however, this will only give you line breaks before and after the styled element.

Plot two histograms on single chart with matplotlib

The accepted answers gives the code for a histogram with overlapping bars, but in case you want each bar to be side-by-side (as I did), try the variation below:

import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-deep')

x = np.random.normal(1, 2, 5000)
y = np.random.normal(-1, 3, 2000)
bins = np.linspace(-10, 10, 30)

plt.hist([x, y], bins, label=['x', 'y'])
plt.legend(loc='upper right')
plt.show()

enter image description here

Reference: http://matplotlib.org/examples/statistics/histogram_demo_multihist.html

EDIT [2018/03/16]: Updated to allow plotting of arrays of different sizes, as suggested by @stochastic_zeitgeist

Rownum in postgresql

Postgresql does not have an equivalent of Oracle's ROWNUM. In many cases you can achieve the same result by using LIMIT and OFFSET in your query.

Style input type file?

After looking around on Google for a long time, trying out several solutions, both CSS, JavaScript and JQuery, i found that most of them were using an Image as the button. Some of them were hard to use, but i did manage to piece together something that ended out working out for me.

The important parts for me was:

  • The Browse button had to be a Button (not an image).
  • The button had to have a hover effect (to make it look nice).
  • The Width of both the Text and the button had to be easy to adjust.
  • The solution had to work in IE8, FF, Chrome and Safari.

This is the solution i came up with. And hope it can be of use to others as well.

Change the width of .file_input_textbox to change the width of the textbox.

Change the width of both .file_input_div, .file_input_button and .file_input_button_hover to change the width of the button. You might need to tweak a bit on the positions also. I never figured out why...

To test this solution, make a new html file and paste the content into it.

<html>
<head>

<style type="text/css">

.file_input_textbox {height:25px;width:200px;float:left; }
.file_input_div     {position: relative;width:80px;height:26px;overflow: hidden; }
.file_input_button  {width: 80px;position:absolute;top:0px;
                     border:1px solid #F0F0EE;padding:2px 8px 2px 8px; font-weight:bold; height:25px; margin:0px; margin-right:5px; }
.file_input_button_hover{width:80px;position:absolute;top:0px;
                     border:1px solid #0A246A; background-color:#B2BBD0;padding:2px 8px 2px 8px; height:25px; margin:0px; font-weight:bold; margin-right:5px; }
.file_input_hidden  {font-size:45px;position:absolute;right:0px;top:0px;cursor:pointer;
                     opacity:0;filter:alpha(opacity=0);-ms-filter:"alpha(opacity=0)";-khtml-opacity:0;-moz-opacity:0; }
</style>
</head>
<body>
    <input type="text" id="fileName" class="file_input_textbox" readonly="readonly">
 <div class="file_input_div">
  <input id="fileInputButton" type="button" value="Browse" class="file_input_button" />
  <input type="file" class="file_input_hidden" 
      onchange="javascript: document.getElementById('fileName').value = this.value" 
      onmouseover="document.getElementById('fileInputButton').className='file_input_button_hover';"
      onmouseout="document.getElementById('fileInputButton').className='file_input_button';" />
</div>
</body>
</html>

What causes a TCP/IP reset (RST) flag to be sent?

Some firewalls do that if a connection is idle for x number of minutes. Some ISPs set their routers to do that for various reasons as well.

In this day and age, you'll need to gracefully handle (re-establish as needed) that condition.

Input length must be multiple of 16 when decrypting with padded cipher

This is a very old question, but my answer may help someone.

  • In the encrypt method, don't forget to encode your string to Base64
  • In the decrypt method, don't forget to decode your string to Base64

Below is the working code

    import java.util.Arrays;
    import java.util.Base64;

    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;

    public class EncryptionDecryptionUtil {

    public static String encrypt(final String secret, final String data) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while encrypting data", e);
        }

    }

    public static String decrypt(final String secret,
            final String encryptedString) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.DECRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
            return new String(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while decrypting data", e);
        }
    }


    public static void main(String[] args) {

        String data = "This is not easy as you think";
        String key = "---------------------------------";
        String encrypted = encrypt(key, data);
        System.out.println(encrypted);
        System.out.println(decrypt(key, encrypted));
      }
  }

For Generating Key you can use below class

    import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SecretKeyGenerator {

    public static void main(String[] args) throws NoSuchAlgorithmException {

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

        SecureRandom secureRandom = new SecureRandom();
        int keyBitSize = 256;
        keyGenerator.init(keyBitSize, secureRandom);

        SecretKey secretKey = keyGenerator.generateKey();

 System.out.println(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
    }

}

How to stop/shut down an elasticsearch node?

If you just want to apply new config you don't need to shut it down.

$ sudo service elasticsearch restart

But if you want to shut it down anyway:

$ sudo service elasticsearch stop

OR

$ sudo systemctl stop elasticsearch.service

$ sudo systemctl restart elasticsearch.service

Docker:

docker restart <elasticsearch-container-name or id>

How to set index.html as root file in Nginx?

location / { is the most general location (with location {). It will match anything, AFAIU. I doubt that it would be useful to have location / { index index.html; } because of a lot of duplicate content for every subdirectory of your site.

The approach with

try_files $uri $uri/index.html index.html;

is bad, as mentioned in a comment above, because it returns index.html for pages which should not exist on your site (any possible $uri will end up in that). Also, as mentioned in an answer above, there is an internal redirect in the last argument of try_files.

Your approach

location = / {
   index index.html;

is also bad, since index makes an internal redirect too. In case you want that, you should be able to handle that in a specific location. Create e.g.

location = /index.html {

as was proposed here. But then you will have a working link http://example.org/index.html, which may be not desired. Another variant, which I use, is:

root /www/my-root;

# http://example.org
# = means exact location
location = / {
    try_files /index.html =404;
}

# disable http://example.org/index as a duplicate content
location = /index      { return 404; }

# This is a general location. 
# (e.g. http://example.org/contacts <- contacts.html)
location / {
    # use fastcgi or whatever you need here
    # return 404 if doesn't exist
    try_files $uri.html =404;
}

P.S. It's extremely easy to debug nginx (if your binary allows that). Just add into the server { block:

error_log /var/log/nginx/debug.log debug;

and see there all internal redirects etc.

Non-static variable cannot be referenced from a static context

Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.

Static variables are marked as static and instance variables doesn't have specific keyword.

JavaScript "cannot read property "bar" of undefined

Just check for it before you pass to your function. So you would pass:

thing.foo ? thing.foo.bar : undefined

How to check if all of the following items are in a list?

Not OP's case, but - for anyone who wants to assert intersection in dicts and ended up here due to poor googling (e.g. me) - you need to work with dict.items:

>>> a = {'key': 'value'}
>>> b = {'key': 'value', 'extra_key': 'extra_value'}
>>> all(item in a.items() for item in b.items())
True
>>> all(item in b.items() for item in a.items())
False

That's because dict.items returns tuples of key/value pairs, and much like any object in Python, they're interchangeably comparable

Reading an Excel file in python using pandas

Close: first you call ExcelFile, but then you call the .parse method and pass it the sheet name.

>>> xl = pd.ExcelFile("dummydata.xlsx")
>>> xl.sheet_names
[u'Sheet1', u'Sheet2', u'Sheet3']
>>> df = xl.parse("Sheet1")
>>> df.head()
                  Tid  dummy1    dummy2    dummy3    dummy4    dummy5  \
0 2006-09-01 00:00:00       0  5.894611  0.605211  3.842871  8.265307   
1 2006-09-01 01:00:00       0  5.712107  0.605211  3.416617  8.301360   
2 2006-09-01 02:00:00       0  5.105300  0.605211  3.090865  8.335395   
3 2006-09-01 03:00:00       0  4.098209  0.605211  3.198452  8.170187   
4 2006-09-01 04:00:00       0  3.338196  0.605211  2.970015  7.765058   

     dummy6  dummy7    dummy8    dummy9  
0  0.623354       0  2.579108  2.681728  
1  0.554211       0  7.210000  3.028614  
2  0.567841       0  6.940000  3.644147  
3  0.581470       0  6.630000  4.016155  
4  0.595100       0  6.350000  3.974442  

What you're doing is calling the method which lives on the class itself, rather than the instance, which is okay (although not very idiomatic), but if you're doing that you would also need to pass the sheet name:

>>> parsed = pd.io.parsers.ExcelFile.parse(xl, "Sheet1")
>>> parsed.columns
Index([u'Tid', u'dummy1', u'dummy2', u'dummy3', u'dummy4', u'dummy5', u'dummy6', u'dummy7', u'dummy8', u'dummy9'], dtype=object)

Maven build debug in Eclipse

The Run/Debug configuration you're using is meant to let you run Maven on your workspace as if from the command line without leaving Eclipse.

Assuming your tests are JUnit based you should be able to debug them by choosing a source folder containing tests with the right button and choose Debug as... -> JUnit tests.

Screenshot sizes for publishing android app on Google Play

  • We require 2 screenshots.
  • Use: Displayed on the details page for your application in Google Play.
  • You may upload up to 8 screenshots each for phone, 7” tablet and 10” tablet.
  • Specs: Minimum dimension: 320 pixels. Maximum dimension: 3840 pixels. The maximum dimension of your screenshot cannot be more than twice as long as the minimum dimension. You may use 24 bit PNG or JPEG image (no alpha). Full bleed, no border in art.
  • We recommend adding screenshots of your app running on a 7" and 10" tablet. Go to ‘Store listing’ page in your Developer Console to add tablet apps screenshots.

https://support.google.com/googleplay/android-developer/answer/1078870?hl=en&ref_topic=2897459

Can't compare naive and aware datetime.now() <= challenge.datetime_end

datetime.datetime.now is not timezone aware.

Django comes with a helper for this, which requires pytz

from django.utils import timezone
now = timezone.now()

You should be able to compare now to challenge.datetime_start

If else on WHERE clause

Here is a sample query for a table having a foreign key relationship to the same table with a query parameter.

enter image description here

SET @x = -1;
SELECT id, categoryName 
FROM Catergory WHERE IF(@x > 0,category_ParentId = @x,category_ParentId IS NOT NULL);

@x can be changed.

Git: How to return from 'detached HEAD' state

Use git reflog to find the hashes of previously checked out commits.

A shortcut command to get to your last checked out branch (not sure if this work correctly with detached HEAD and intermediate commits though) is git checkout -

How to find top three highest salary in emp table in oracle?

SELECT  *FROM 
    (
    SELECT *FROM emp 
    ORDER BY Salary desc
    )
WHERE rownum <= 3
ORDER BY Salary ;

How to set fake GPS location on IOS real device

you can do it on real device by run device in Debug mode

Click Debug->Simulate Location -> add .gpx file for your location during run time

How to change font size in Eclipse for Java text editors?

If you are using windows then try with CTRL,SHIFT,+ and for decreasing font size you can use CTRL,SHIFT,-

how to implement a pop up dialog box in iOS

Updated for iOS 8.0

Since iOS 8.0, you will need to use UIAlertController as the following:

-(void)alertMessage:(NSString*)message
{
    UIAlertController* alert = [UIAlertController
          alertControllerWithTitle:@"Alert"
          message:message
          preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction 
          actionWithTitle:@"OK" style:UIAlertActionStyleDefault
         handler:^(UIAlertAction * action) {}];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

Where self in my example is a UIViewController, which implements "presentViewController" method for a popup.

David

How to debug "ImagePullBackOff"?

Run docker login

Push the image to docker hub

Re-create pod

This solved the problem for me. Hope it helps.

What's the difference between Visual Studio Community and other, paid versions?

There are 2 major differences.

  1. Technical
  2. Licensing

Technical, there are 3 major differences:

First and foremost, Community doesn't have TFS support.
You'll just have to use git (arguable whether this constitutes a disadvantage or whether this actually is a good thing).
Note: This is what MS wrote. Actually, you can check-in&out with TFS as normal, if you have a TFS server in the network. You just cannot use Visual Studio as TFS SERVER.

Second, VS Community is severely limited in its testing capability.
Only unit tests. No Performance tests, no load tests, no performance profiling.

Third, VS Community's ability to create Virtual Environments has been severely cut.

On the other hand, syntax highlighting, IntelliSense, Step-Through debugging, GoTo-Definition, Git-Integration and Build/Publish are really all the features I need, and I guess that applies to a lot of developers.

For all other things, there are tools that do the same job faster, better and cheaper.

If you, like me, anyway use git, do unit testing with NUnit, and use Java-Tools to do Load-Testing on Linux plus TeamCity for CI, VS Community is more than sufficient, technically speaking.

Licensing:

A) If you're an individual developer (no enterprise, no organization), no difference (AFAIK), you can use CommunityEdition like you'd use the paid edition (as long as you don't do subcontracting)
B) You can use CommunityEdition freely for OpenSource (OSI) projects
C) If you're an educational insitution, you can use CommunityEdition freely (for education/classroom use)
D) If you're an enterprise with 250 PCs or users or more than one million US dollars in revenue (including subsidiaries), you are NOT ALLOWED to use CommunityEdition.
E) If you're not an enterprise as defined above, and don't do OSI or education, but are an "enterprise"/organization, with 5 or less concurrent (VS) developers, you can use VS Community freely (but only if you're the owner of the software and sell it, not if you're a subcontractor creating software for a larger enterprise, software which in the end the enterprise will own), otherwise you need a paid edition.

The above does not consitute legal advise.
See also:
https://softwareengineering.stackexchange.com/questions/262916/understanding-visual-studio-community-edition-license

How to embed HTML into IPython output?

First, the code:

from random import choices

def random_name(length=6):
    return "".join(choices("abcdefghijklmnopqrstuvwxyz", k=length))
# ---

from IPython.display import IFrame, display, HTML
import tempfile
from os import unlink

def display_html_to_frame(html, width=600, height=600):
    name = f"temp_{random_name()}.html"
    with open(name, "w") as f:
        print(html, file=f)
    display(IFrame(name, width, height), metadata=dict(isolated=True))
    # unlink(name)
    
def display_html_inline(html):
    display(HTML(html, metadata=dict(isolated=True)))

h="<html><b>Hello</b></html>"    
display_html_to_iframe(h)
display_html_inline(h)

Some quick notes:

  • You can generally just use inline HTML for simple items. If you are rendering a framework, like a large JavaScript visualization framework, you may need to use an IFrame. Its hard enough for Jupyter to run in a browser without random HTML embedded.
  • The strange parameter, metadata=dict(isolated=True) does not isolate the result in an IFrame, as older documentation suggests. It appears to prevent clear-fix from resetting everything. The flag is no longer documented: I just found using it allowed certain display: grid styles to correctly render.
  • This IFrame solution writes to a temporary file. You could use a data uri as described here but it makes debugging your output difficult. The Jupyter IFrame function does not take a data or srcdoc attribute.
  • The tempfile module creations are not sharable to another process, hence the random_name().
  • If you use the HTML class with an IFrame in it, you get a warning. This may be only once per session.
  • You can use HTML('Hello, <b>world</b>') at top level of cell and its return value will render. Within a function, use display(HTML(...)) as is done above. This also allows you to mix display and print calls freely.
  • Oddly, IFrames are indented slightly more than inline HTML.

Get Selected value from dropdown using JavaScript

Try

var e = document.getElementById("mySelect");
var selectedOp = e.options[e.selectedIndex].text;

Saving to CSV in Excel loses regional date format

Change the date and time settings for your computer in the "short date" format under calendar settings. This will change the format for everything yyyy-mm-dd or however you want it to display; but remember it will look like that even for files saved on your computer.

At least it works.

enable cors in .htaccess

I tried @abimelex solution, but in Slim 3.0, mapping the OPTIONS requests goes like:

$app = new \Slim\App();
$app->options('/books/{id}', function ($request, $response, $args) {
    // Return response headers
});

https://www.slimframework.com/docs/objects/router.html#options-route

Java/Groovy - simple date reformatting

Your DateFormat pattern does not match you input date String. You could use

new SimpleDateFormat("dd-MMM-yyyy")

How do I set default values for functions parameters in Matlab?

I am confused nobody has pointed out this blog post by Loren, one of Matlab's developers. The approach is based on varargin and avoids all those endless and painfull if-then-else or switch cases with convoluted conditions. When there are a few default values, the effect is dramatic. Here's an example from the linked blog:

function y = somefun2Alt(a,b,varargin)
% Some function that requires 2 inputs and has some optional inputs.

% only want 3 optional inputs at most
numvarargs = length(varargin);
if numvarargs > 3
    error('myfuns:somefun2Alt:TooManyInputs', ...
        'requires at most 3 optional inputs');
end

% set defaults for optional inputs
optargs = {eps 17 @magic};

% now put these defaults into the valuesToUse cell array, 
% and overwrite the ones specified in varargin.
optargs(1:numvarargs) = varargin;
% or ...
% [optargs{1:numvarargs}] = varargin{:};

% Place optional args in memorable variable names
[tol, mynum, func] = optargs{:};

If you still don't get it, then try reading the entire blog post by Loren. I have written a follow up blog post which deals with missing positional default values. I mean that you could write something like:

somefun2Alt(a, b, '', 42)

and still have the default eps value for the tol parameter (and @magic callback for func of course). Loren's code allows this with a slight but tricky modification.

Finally, just a few advantages of this approach:

  1. Even with a lot of defaults the boilerplate code doesn't get huge (as opposed to the family of if-then-else approaches, which get longer with each new default value)
  2. All the defaults are in one place. If any of those need to change, you have just one place to look at.

Trooth be told, there is a disadvantage too. When you type the function in Matlab shell and forget its parameters, you will see an unhelpful varargin as a hint. To deal with that, you're advised to write a meaningful usage clause.