Programs & Examples On #Python 2.6

For issues that are specific to Python 2.6. If your question applies to Python in general, use the tag [python].

Get all object attributes in Python?

Use the built-in function dir().

How to convert a set to a list in python?

[EDITED] It's seems you earlier have redefined "list", using it as a variable name, like this:

list = set([1,2,3,4]) # oops
#...
first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)

And you'l get

Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'set' object is not callable

Pipe subprocess standard output to a variable

With a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE) , you need to either use a list or use shell=True;

Either of these will work. The former is preferable.

a = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE)

a = subprocess.Popen('cdrecord --help', shell=True, stdout=subprocess.PIPE)

Also, instead of using Popen.stdout.read/Popen.stderr.read, you should use .communicate() (refer to the subprocess documentation for why).

proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()

Visibility of global variables in imported modules

As a workaround, you could consider setting environment variables in the outer layer, like this.

main.py:

import os
os.environ['MYVAL'] = str(myintvariable)

mymodule.py:

import os

myval = None
if 'MYVAL' in os.environ:
    myval = os.environ['MYVAL']

As an extra precaution, handle the case when MYVAL is not defined inside the module.

Is there a way to perform "if" in python's lambda

An easy way to perform an if in lambda is by using list comprehension.

You can't raise an exception in lambda, but this is a way in Python 3.x to do something close to your example:

f = lambda x: print(x) if x==2 else print("exception")

Another example:

return 1 if M otherwise 0

f = lambda x: 1 if x=="M" else 0

sort dict by value python

From your comment to gnibbler answer, i'd say you want a list of pairs of key-value sorted by value:

sorted(data.items(), key=lambda x:x[1])

How to calculate the time interval between two time strings

Structure that represent time difference in Python is called timedelta. If you have start_time and end_time as datetime types you can calculate the difference using - operator like:

diff = end_time - start_time

you should do this before converting to particualr string format (eg. before start_time.strftime(...)). In case you have already string representation you need to convert it back to time/datetime by using strptime method.

How do you get the current text contents of a QComboBox?

If you want the text value of a QString object you can use the __str__ property, like this:

>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'

Hope that helps.

How to remove all characters after a specific character in python?

another easy way using re will be

import re, clr

text = 'some string... this part will be removed.'

text= re.search(r'(\A.*)\.\.\..+',url,re.DOTALL|re.IGNORECASE).group(1)

// text = some string

How to make an unaware datetime timezone aware in python

I agree with the previous answers, and is fine if you are ok to start in UTC. But I think it is also a common scenario for people to work with a tz aware value that has a datetime that has a non UTC local timezone.

If you were to just go by name, one would probably infer replace() will be applicable and produce the right datetime aware object. This is not the case.

the replace( tzinfo=... ) seems to be random in its behaviour. It is therefore useless. Do not use this!

localize is the correct function to use. Example:

localdatetime_aware = tz.localize(datetime_nonaware)

Or a more complete example:

import pytz
from datetime import datetime
pytz.timezone('Australia/Melbourne').localize(datetime.now())

gives me a timezone aware datetime value of the current local time:

datetime.datetime(2017, 11, 3, 7, 44, 51, 908574, tzinfo=<DstTzInfo 'Australia/Melbourne' AEDT+11:00:00 DST>)

How Should I Set Default Python Version In Windows?

Nothing above worked, this is what worked for me:

ftype Python.File=C:\Path\to\python.exe "%1" %*

This command should be run in Command prompt launched as administrator

Warning: even if the path in this command is set to python35, if you have python36 installed it's going to set the default to python36. To prevent this, you can temporarily change the folder name from Python36 to xxPython36, run the command and then remove the change to the Python 36 folder.

How to fix symbol lookup error: undefined symbol errors in a cluster environment

yum update

helped me out. After I had

wget: symbol lookup error: wget: undefined symbol: psl_latest

Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever.


I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read().

The documentation for readlines() explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list full of strings out of those lines.

But the documentation for read() likewise guarantees that it reads the whole file into memory, and builds a string, so that doesn't help.


On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.


You can work around this in three ways:

  1. Write a loop around readlines(sizehint), read(size), or readline().
  2. Just use the file as a lazy iterator without calling any of these.
  3. mmap the file, which allows you to treat it as a giant string without first reading it in.

For example, this has to read all of foo at once:

with open('foo') as f:
    lines = f.readlines()
    for line in lines:
        pass

But this only reads about 8K at a time:

with open('foo') as f:
    while True:
        lines = f.readlines(8192)
        if not lines:
            break
        for line in lines:
            pass

And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.

with open('foo') as f:
    while True:
        line = f.readline()
        if not line:
            break
        pass

And this will do the exact same thing as the previous:

with open('foo') as f:
    for line in f:
        pass

Meanwhile:

but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?

Python doesn't make any such guarantees about garbage collection.

The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.

However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.

On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.

Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of mallocs to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).


Putting it all together, here's how I'd write your program:

for filename in os.listdir(input_dir):
    with open(filename, 'rb') as f:
        if filename.endswith(".gz"):
            f = gzip.open(fileobj=f)
        words = (line.split(delimiter) for line in f)
        ... my logic ...  

Or, maybe:

for filename in os.listdir(input_dir):
    if filename.endswith(".gz"):
        f = gzip.open(filename, 'rb')
    else:
        f = open(filename, 'rb')
    with contextlib.closing(f):
        words = (line.split(delimiter) for line in f)
        ... my logic ...

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

That's probably useful for someone, who uses unittest, if imported modules use request library. To suppress warnings in requests' vendored urllib3, add

warnings.filterwarnings('ignore', message='Unverified HTTPS request')

to setUp method in your testclass, i.e:

import unittest, warnings

class MyTests(unittest.TestCase):
    
    def setUp(self):
        warnings.filterwarnings('ignore', message='Unverified HTTPS request')
    
    (all test methods here)

bash: pip: command not found

Not sure why this wasnt mentioned before, but the only thing that worked for me (on my NVIDIA Xavier) was:

sudo apt-get install python3-pip

(or sudo apt-get install python-pip for python 2)

X-Frame-Options: ALLOW-FROM in firefox and chrome

For Chrome, instead of

response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);

you need to add Content-Security-Policy

string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;
response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);

to the HTTP-response-headers.
Note that this assumes you checked on the server whether or not refAuth is allowed.
And also, note that you need to do browser-detection in order to avoid adding the allow-from header for Chrome (outputs error on console).

For details, see my answer here.

Using Mockito to test abstract classes

Mocking frameworks are designed to make it easier to mock out dependencies of the class you are testing. When you use a mocking framework to mock a class, most frameworks dynamically create a subclass, and replace the method implementation with code for detecting when a method is called and returning a fake value.

When testing an abstract class, you want to execute the non-abstract methods of the Subject Under Test (SUT), so a mocking framework isn't what you want.

Part of the confusion is that the answer to the question you linked to said to hand-craft a mock that extends from your abstract class. I wouldn't call such a class a mock. A mock is a class that is used as a replacement for a dependency, is programmed with expectations, and can be queried to see if those expectations are met.

Instead, I suggest defining a non-abstract subclass of your abstract class in your test. If that results in too much code, than that may be a sign that your class is difficult to extend.

An alternative solution would be to make your test case itself abstract, with an abstract method for creating the SUT (in other words, the test case would use the Template Method design pattern).

How do you get a directory listing sorted by creation date in python?

Here's my answer using glob without filter if you want to read files with a certain extension in date order (Python 3).

dataset_path='/mydir/'   
files = glob.glob(dataset_path+"/morepath/*.extension")   
files.sort(key=os.path.getmtime)

Javascript get Object property Name

Like the other answers you can do theTypeIs = Object.keys(myVar)[0]; to get the first key. If you are expecting more keys, you can use

Object.keys(myVar).forEach(function(k) {
    if(k === "typeA") {
        // do stuff
    }
    else if (k === "typeB") {
        // do more stuff
    }
    else {
        // do something
    }
});

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

Jacob Helwig mentions in his answer that:

It looks like rev-parse is being used without sufficient error checking before-hand

Commit 62f162f from Jeff King (peff) should improve the robustness of git rev-parse in Git 1.9/2.0 (Q1 2014) (in addition of commit 1418567):

For cases where we do not match (e.g., "doesnotexist..HEAD"), we would then want to try to treat the argument as a filename.
try_difference() gets this right, and always unmunges in this case.
However, try_parent_shorthand() never unmunges, leading to incorrect error messages, or even incorrect results:

$ git rev-parse foobar^@
foobar
fatal: ambiguous argument 'foobar': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

Bootstrap change div order with pull-right, pull-left on 3 columns

Try this...

<div class="row">
    <div class="col-xs-3">
        Menu
    </div>
    <div class="col-xs-9">
        <div class="row">
          <div class="col-sm-4 col-sm-push-8">
          Right content
          </div>
          <div class="col-sm-8 col-sm-pull-4">
          Content
          </div>
       </div>
    </div>
</div>

Bootply

displaying a string on the textview when clicking a button in android

Try this

public void onClick(View view){
    txtView.setText("hello");

    //printmyname();
    Toast.makeText(NameonbuttonclickActivity.this, "hello", Toast.LENGTH_LONG).show();
}

Also in toast use "Hello"

Generating a random & unique 8 character string using MySQL

This problem consists of two very different sub-problems:

  • the string must be seemingly random
  • the string must be unique

While randomness is quite easily achieved, the uniqueness without a retry loop is not. This brings us to concentrate on the uniqueness first. Non-random uniqueness can trivially be achieved with AUTO_INCREMENT. So using a uniqueness-preserving, pseudo-random transformation would be fine:

  • Hash has been suggested by @paul
  • AES-encrypt fits also
  • But there is a nice one: RAND(N) itself!

A sequence of random numbers created by the same seed is guaranteed to be

  • reproducible
  • different for the first 8 iterations
  • if the seed is an INT32

So we use @AndreyVolk's or @GordonLinoff's approach, but with a seeded RAND:

e.g. Assumin id is an AUTO_INCREMENT column:

INSERT INTO vehicles VALUES (blah); -- leaving out the number plate
SELECT @lid:=LAST_INSERT_ID();
UPDATE vehicles SET numberplate=concat(
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@lid)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
  substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed)*36+1, 1)
)
WHERE id=@lid;

Sanitizing user input before adding it to the DOM in Javascript

Never use escape(). It's nothing to do with HTML-encoding. It's more like URL-encoding, but it's not even properly that. It's a bizarre non-standard encoding available only in JavaScript.

If you want an HTML encoder, you'll have to write it yourself as JavaScript doesn't give you one. For example:

function encodeHTML(s) {
    return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
}

However whilst this is enough to put your user_id in places like the input value, it's not enough for id because IDs can only use a limited selection of characters. (And % isn't among them, so escape() or even encodeURIComponent() is no good.)

You could invent your own encoding scheme to put any characters in an ID, for example:

function encodeID(s) {
    if (s==='') return '_';
    return s.replace(/[^a-zA-Z0-9.-]/g, function(match) {
        return '_'+match[0].charCodeAt(0).toString(16)+'_';
    });
}

But you've still got a problem if the same user_id occurs twice. And to be honest, the whole thing with throwing around HTML strings is usually a bad idea. Use DOM methods instead, and retain JavaScript references to each element, so you don't have to keep calling getElementById, or worrying about how arbitrary strings are inserted into IDs.

eg.:

function addChut(user_id) {
    var log= document.createElement('div');
    log.className= 'log';
    var textarea= document.createElement('textarea');
    var input= document.createElement('input');
    input.value= user_id;
    input.readonly= True;
    var button= document.createElement('input');
    button.type= 'button';
    button.value= 'Message';

    var chut= document.createElement('div');
    chut.className= 'chut';
    chut.appendChild(log);
    chut.appendChild(textarea);
    chut.appendChild(input);
    chut.appendChild(button);
    document.getElementById('chuts').appendChild(chut);

    button.onclick= function() {
        alert('Send '+textarea.value+' to '+user_id);
    };

    return chut;
}

You could also use a convenience function or JS framework to cut down on the lengthiness of the create-set-appends calls there.

ETA:

I'm using jQuery at the moment as a framework

OK, then consider the jQuery 1.4 creation shortcuts, eg.:

var log= $('<div>', {className: 'log'});
var input= $('<input>', {readOnly: true, val: user_id});
...

The problem I have right now is that I use JSONP to add elements and events to a page, and so I can not know whether the elements already exist or not before showing a message.

You can keep a lookup of user_id to element nodes (or wrapper objects) in JavaScript, to save putting that information in the DOM itself, where the characters that can go in an id are restricted.

var chut_lookup= {};
...

function getChut(user_id) {
    var key= '_map_'+user_id;
    if (key in chut_lookup)
        return chut_lookup[key];
    return chut_lookup[key]= addChut(user_id);
}

(The _map_ prefix is because JavaScript objects don't quite work as a mapping of arbitrary strings. The empty string and, in IE, some Object member names, confuse it.)

Linq with group by having count

For anyone looking to do this in vb (as I was and couldn't find anything)

From c In db.Company 
Select c.Name Group By Name Into Group 
Where Group.Count > 1

HTML combo box with option to type an entry

This link can help you: http://www.scriptol.com/html5/combobox.php

You have two examples. One in html4 and other in html5

HTML5

<input type="text" list="browsers"/>
 <datalist id="browsers">
    <option>Google</option>
    <option>IE9</option>
 </datalist>

HTML4

 <input type="text" id="theinput" name="theinput" />
 <select name="thelist" onChange="combo(this, 'theinput')">
   <option>one</option>
   <option>two</option>
   <option>three</option>
 </select>
 function combo(thelist, theinput) {
     theinput = document.getElementById(theinput);
     var idx = thelist.selectedIndex;
     var content = thelist.options[idx].innerHTML;
     theinput.value = content;
 }

How to get am pm from the date time string using moment js

you will get the time without specifying the date format. convert the string to date using Date object

var myDate = new Date('Mon 03-Jul-2017, 06:00 PM');

working solution:

_x000D_
_x000D_
var myDate= new Date('Mon 03-Jul-2017, 06:00 PM');_x000D_
console.log(moment(myDate).format('HH:mm')); // 24 hour format _x000D_
console.log(moment(myDate).format('hh:mm'));_x000D_
console.log(moment(myDate).format('hh:mm A'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Add attribute 'checked' on click jquery

$( this ).attr( 'checked', 'checked' )

just attr( 'checked' ) will return the value of $( this )'s checked attribute. To set it, you need that second argument. Based on <input type="checkbox" checked="checked" />

Edit:

Based on comments, a more appropriate manipulation would be:

$( this ).attr( 'checked', true )

And a straight javascript method, more appropriate and efficient:

this.checked = true;

Thanks @Andy E for that.

The application may be doing too much work on its main thread

After doing much R&D on this issue I got the Solution,

In my case I am using Service that will run every 2 second and with the runonUIThread, I was wondering the problem was there but not at all. The next issue that I found is that I am using large Image in may App and thats the problem.

I removed the Images and set new Images.

Conclusion :- Look into your code is there any raw file that you are using is of big size.

Synchronization vs Lock

Many answers here recommend using synchronized.

However, it depends on the usecase.

The synchronized keyword has naturally built in language support. This can mean the JIT can optimise synchronised blocks in ways it cannot with Locks. e.g. it can combine synchronized blocks. Only one thread is allowed to access only one method at any given point of time using a synchronized block. This is a very expensive operation.

Locks avoid this by allowing configuration of various locks for different purpose. One can have couple of methods synchronized under one lock and other methods under a different lock. This allows more concurrency and also increases overall performance.

So, for a smaller system which can do without concurrency and allowing one thread to execute an operation, synchronized can work. Otherwise, lock can be taken on the key.

How link to any local file with markdown syntax?

If you have spaces in the filename, try these:

[file](./file%20with%20spaces.md)
[file](<./file with spaces.md>)

First one seems more reliable

How to upload a file to directory in S3 bucket using boto

import boto3

s3 = boto3.resource('s3')
BUCKET = "test"

s3.Bucket(BUCKET).upload_file("your/local/file", "dump/file")

How to remove all .svn directories from my application directories

As an important issue, when you want to utilize shell to delete .svn folders You need -depth argument to prevent find command entering the directory that was just deleted and showing error messages like e.g.

"find: ./.svn: No such file or directory"

As a result, You can use find command like below:

cd [dir_to_delete_svn_folders]
find . -depth -name .svn -exec rm -fr {} \;

adb is not recognized as internal or external command on windows

If you get your adb from Android Studio (which most will nowadays since Android is deprecated on Eclipse), your adb program will most likely be located here:

%USERPROFILE%\AppData\Local\Android\sdk\platform-tools

Where %USERPROFILE% represents something like C:\Users\yourName.

If you go into your computer's environmental variables and add %USERPROFILE%\AppData\Local\Android\sdk\platform-tools to the PATH (just copy-paste that line, even with the % --- it will work fine, at least on Windows, you don't need to hardcode your username) then it should work now. Open a new command prompt and type adb to check.

ImportError: cannot import name

The problem is that you have a circular import: in app.py

from mod_login import mod_login

in mod_login.py

from app import app

This is not permitted in Python. See Circular import dependency in Python for more info. In short, the solution are

  • either gather everything in one big file
  • delay one of the import using local import

How can I remove all files in my git repo and update/push from my local git repo?

Delete the hidden .git folder (that you can locate within your project folder) and again start the process of creating a git repository using git init command.

Make an image follow mouse pointer

by using jquery to register .mousemove to document to change the image .css left and top to event.pageX and event.pageY.

example as below http://jsfiddle.net/BfLAh/1/

_x000D_
_x000D_
$(document).mousemove(function(e) {
  $("#follow").css({
    left: e.pageX,
    top: e.pageY
  });
});
_x000D_
#follow {
  position: absolute;
  text-align: center;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="follow"><img src="https://placekitten.com/96/140" /><br>Kitteh</br>
</div>
_x000D_
_x000D_
_x000D_

updated to follow slowly

http://jsfiddle.net/BfLAh/3/

for the orientation , you need to get the current css left and css top and compare with event.pageX and event.pageY , then set the image orientation with

-webkit-transform: rotate(-90deg); 
-moz-transform: rotate(-90deg); 

for the speed , you can set the jquery .animation duration to certain amount.

addClass and removeClass in jQuery - not removing class

I actually just resolved an issue I was having by swapping around the order that I was altering the properties in. For example I was changing the attribute first but I actually had to remove the class and add the new class before modifying the attributes. I'm not sure why it worked but it did. So something to try would be to change from $("XXXX").attr('something').removeClass( "class" ).addClass( "newClass" ) to $("XXXX").removeClass( "class" ).addClass( "newClass" ).attr('something').

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

The exception indicates a problem with the unobtrusive JavaScript validation mode. This issue is not Sitefinity specific and occurs in any standard ASP.NET applications when the project targets .NET 4.5 framework and the pre-4.5 validation is not enabled in the web.config file.

Open the web.config file and make sure that there is a ValidationSettings:UnobtrusiveValidationMode in the app settings:

<appSettings>
  <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

How to get keyboard input in pygame?

Try this:

keys=pygame.key.get_pressed()
if keys[K_LEFT]:
    if count == 10:
        location-=1
        count=0
    else:
        count +=1
    if location==-1:
        location=0
if keys[K_RIGHT]:
    if count == 10:
        location+=1
        count=0
    else:
        count +=1
    if location==5:
        location=4

This will mean you only move 1/10 of the time. If it still moves to fast you could try increasing the value you set "count" too.

How to get the selected index of a RadioGroup in Android

It worked perfectly for me in this way:

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
    int radioButtonID = radioGroup.getCheckedRadioButtonId();
    RadioButton radioButton = (RadioButton) radioGroup.findViewById(radioButtonID);
    String selectedtext = (String) radioButton.getText();

CSS: Fix row height

I haven't tried it but if you put a div in your table cell set so that it will have scrollbars if needed, then you could insert in there, with a fixed height on the div and it should keep your table row to a fixed height.

create array from mysql query php

You do need to iterate through...

$typeArray = array();
$query = "select * from whatever";
$result = mysql_query($query);

if ($result) {
    while ($record = mysql_fetch_array($results)) $typeArray[] = $record['type'];
}

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

> is not in the documentation.

< is for one-way binding.

@ binding is for passing strings. These strings support {{}} expressions for interpolated values.

= binding is for two-way model binding. The model in parent scope is linked to the model in the directive's isolated scope.

& binding is for passing a method into your directive's scope so that it can be called within your directive.

When we are setting scope: true in directive, Angular js will create a new scope for that directive. That means any changes made to the directive scope will not reflect back in parent controller.

What does the exclamation mark do before the function?

The function:

function () {}

returns nothing (or undefined).

Sometimes we want to call a function right as we create it. You might be tempted to try this:

function () {}()

but it results in a SyntaxError.

Using the ! operator before the function causes it to be treated as an expression, so we can call it:

!function () {}()

This will also return the boolean opposite of the return value of the function, in this case true, because !undefined is true. If you want the actual return value to be the result of the call, then try doing it this way:

(function () {})()

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

create database if not exists `test`;

USE `test`;

SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;

/*Table structure for table `test` */

***CREATE TABLE IF NOT EXISTS `tblsample` (
  `id` int(11) NOT NULL auto_increment,   
  `recid` int(11) NOT NULL default '0',       
  `cvfilename` varchar(250)  NOT NULL default '',     
  `cvpagenumber`  int(11) NULL,     
  `cilineno` int(11)  NULL,    
  `batchname`  varchar(100) NOT NULL default '',
  `type` varchar(20) NOT NULL default '',    
  `data` varchar(100) NOT NULL default '',
   PRIMARY KEY  (`id`)
);***

OrderBy pipe issue

Recommend u use lodash with angular, then your pipe will be next:

import {Pipe, PipeTransform} from '@angular/core';
import * as _ from 'lodash'
@Pipe({
    name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {

    transform(array: Array<any>, args?: any): any {
        return _.sortBy(array, [args]);
    }

}

and use it in html like

*ngFor = "#todo of todos | orderBy:'completed'"

and don't forget add Pipe to your module

@NgModule({
    ...,
    declarations: [OrderByPipe, ...],
    ...
})

Can I set state inside a useEffect hook

Effects are always executed after the render phase is completed even if you setState inside the one effect, another effect will read the updated state and take action on it only after the render phase.

Having said that its probably better to take both actions in the same effect unless there is a possibility that b can change due to reasons other than changing a in which case too you would want to execute the same logic

C++ float array initialization

No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

How to use <DllImport> in VB.NET?

I know this has already been answered, but here is an example for the people who are trying to use SQL Server Types in a vb project:

            Imports System
            Imports System.IO
            Imports System.Runtime.InteropServices

            Namespace SqlServerTypes
                Public Class Utilities



                    <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
                    Public Shared Function LoadLibrary(ByVal libname As String) As IntPtr

                    End Function

                    Public Shared Sub LoadNativeAssemblies(ByVal rootApplicationPath As String)
                        Dim nativeBinaryPath = If(IntPtr.Size > 4, Path.Combine(rootApplicationPath, "SqlServerTypes\x64\"), Path.Combine(rootApplicationPath, "SqlServerTypes\x86\"))
                        LoadNativeAssembly(nativeBinaryPath, "msvcr120.dll")
                        LoadNativeAssembly(nativeBinaryPath, "SqlServerSpatial140.dll")
                    End Sub

                    Private Shared Sub LoadNativeAssembly(ByVal nativeBinaryPath As String, ByVal assemblyName As String)
                        Dim path = System.IO.Path.Combine(nativeBinaryPath, assemblyName)
                        Dim ptr = LoadLibrary(path)

                        If ptr = IntPtr.Zero Then
                            Throw New Exception(String.Format("Error loading {0} (ErrorCode: {1})", assemblyName, Marshal.GetLastWin32Error()))
                        End If
                    End Sub
                End Class
            End Namespace

Programmatic equivalent of default(Type)

Equivalent to Dror's answer but as an extension method:

namespace System
{
    public static class TypeExtensions
    {
        public static object Default(this Type type)
        {
            object output = null;

            if (type.IsValueType)
            {
                output = Activator.CreateInstance(type);
            }

            return output;
        }
    }
}

Laravel 5 call a model function in a blade view

You can pass it to view but first query it in controller, and then after that add this :

return view('yourview', COMPACT('variabelnametobepassedtoview'));

How to format strings using printf() to get equal length in the output

printf allows formatting with width specifiers. For example,

printf( "%-30s %s\n", "Starting initialization...", "Ok." );

You would use a negative width specifier to indicate left-justification because the default is to use right-justification.

SSRS - Checking whether the data is null

Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).

Either way works, I like to put that logic in the query so the report has to do less.

Can I safely delete contents of Xcode Derived data folder?

yes, safe to delete, my script searches and nukes every instance it finds, easily modified to a local directory

#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
IFS=$'\n\t'

for drive in Swap Media OSX_10.11.6/$HOME
do
   pushd /Volumes/${drive}  &> /dev/null
   gfind . -depth -name 'DerivedData'|xargs -I '{}' /bin/rm -fR '{}'
   popd &> /dev/null
done

What version of JBoss I am running?

Just found another way to know the jboss version, so pointing out here:

In Linux/Windows use --version parameter along with Jboss executable to know the Jboss Version

eg:

[immo@g012 bin]$  ./run.sh --version
========================================================================

  JBoss Bootstrap Environment

  JBOSS_HOME: /programs/jboss4.2-AES2.3Cert

  JAVA: /programs/java/jdk1.7.0_09/bin/java

  JAVA_OPTS: -server -Xms128m -Xmx512m -Dsun.rmi.dgc.client.gcInterval=3600000 

  CLASSPATH: /programs/jboss4.2-AES2.3Cert/bin/run.jar:/programs/java/jdk1.7.0_09/lib/tools.jar

=========================================================================

Listening for transport dt_socket at address: 8787
JBoss 4.0.4.GA (build: CVSTag=JBoss_4_0_4_GA date=200605151000)

Here JBoss 4.0.4.GA is the Jboss version

in windows this could be

run.bat --version

Also, in new versions of jboss the executable is standalone.sh / standalone.bat

How to get a list of images on docker registry v2

This has been driving me crazy, but I finally put all the pieces together. As of 1/25/2015, I've confirmed that it is possible to list the images in the docker V2 registry ( exactly as @jonatan mentioned, above. )

I would up-vote that answer, if I had the rep for it.

Instead, I'll expand on the answer. Since registry V2 is made with security in mind, I think it's appropriate to include how to set it up with a self signed cert, and run the container with that cert in order that an https call can be made to it with that cert:

This is the script I actually use to start the registry:

sudo docker stop registry
sudo docker rm -v registry
sudo docker run -d \
  -p 5001:5001 \
  -p 5000:5000 \
  --restart=always \
  --name registry \
  -v /data/registry:/var/lib/registry \
  -v /root/certs:/certs \
  -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt \
  -e REGISTRY_HTTP_TLS_KEY=/certs/domain.key \ 
  -e REGISTRY_HTTP_DEBUG_ADDR=':5001' \
  registry:2.2.1

This may be obvious to some, but I always get mixed up with keys and certs. The file that needs to be referenced to make the call @jonaton mentions above**, is the domain.crt listed above. ( Since I put domain.crt in /root, I made a copy into the user directory where it could be accessed. )

curl --cacert ~/domain.crt https://myregistry:5000/v2/_catalog
> {"repositories":["redis","ubuntu"]}

**The command above has been changed: -X GET didn't actually work when I tried it.

Note: https://myregistry:5000 ( as above ) must match the domain given to the cert generated.

AngularJS ui-router login authentication

I Created this module to help make this process piece of cake

You can do things like:

$routeProvider
  .state('secret',
    {
      ...
      permissions: {
        only: ['admin', 'god']
      }
    });

Or also

$routeProvider
  .state('userpanel',
    {
      ...
      permissions: {
        except: ['not-logged-in']
      }
    });

It's brand new but worth checking out!

https://github.com/Narzerus/angular-permission

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):

The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:

[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }

Will output the following if it is over the character limit: "Address can have a max of 100 characters"

The placeholders I am aware of are:

  • {0} = Property Name
  • {1} = Max Length
  • {2} = Min Length

Much thanks to bloudraak for initially pointing this out.

Detecting endianness programmatically in a C++ program

Declare:

My initial post is incorrectly declared as "compile time". It's not, it's even impossible in current C++ standard. The constexpr does NOT means the function always do compile-time computation. Thanks Richard Hodges for correction.

compile time, non-macro, C++11 constexpr solution:

union {
  uint16_t s;
  unsigned char c[2];
} constexpr static  d {1};

constexpr bool is_little_endian() {
  return d.c[0] == 1;
}

Set formula to a range of cells

Range("C1:C10").Formula = "=A1+B1"

Simple as that.

It autofills (FillDown) the range with the formula.

Typescript export vs. default export

Here's example with simple object exporting.

var MyScreen = {

    /* ... */

    width : function (percent){

        return window.innerWidth / 100 * percent

    }

    height : function (percent){

        return window.innerHeight / 100 * percent

    }


};

export default MyScreen

In main file (Use when you don't want and don't need to create new instance) and it is not global you will import this only when it needed :

import MyScreen from "./module/screen";
console.log( MyScreen.width(100) );

Reinitialize Slick js after successful ajax call

I had to unslick the carousel before the ajax call starts, but you can't do that until there is already a slick carousel. So, I set a variable to 0 and only run unslick after it changed

var slide = 0
if(slide>0)      
$('#ui-id-1').slick('unslick');

        $.ajax({
            //do stuff, here
        },
        success: function( data ) {

            $('#ui-id-1').slick();
            slide++;

        }

Testing for empty or nil-value string

variable = id if variable.to_s.empty?

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

I was facing similar issue with openCV on the python:3.7-slim docker box. Following did the trick for me :

apt-get install build-essential libglib2.0-0 libsm6 libxext6 libxrender-dev

Please see if this helps !

Backbone.js fetch with parameters

try {
    // THIS for POST+JSON
    options.contentType = 'application/json';
    options.type = 'POST';
    options.data = JSON.stringify(options.data);

    // OR THIS for GET+URL-encoded
    //options.data = $.param(_.clone(options.data));

    console.log('.fetch options = ', options);
    collection.fetch(options);
} catch (excp) {
    alert(excp);
}

Parse date without timezone javascript

The Date object itself will contain timezone anyway, and the returned result is the effect of converting it to string in a default way. I.e. you cannot create a date object without timezone. But what you can do is mimic the behavior of Date object by creating your own one. This is, however, better to be handed over to libraries like moment.js.

Create a date from day month and year with T-SQL

Sql Server 2012 has a function that will create the date based on the parts (DATEFROMPARTS). For the rest of us, here is a db function I created that will determine the date from the parts (thanks @Charles)...

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[func_DateFromParts]'))
    DROP FUNCTION [dbo].[func_DateFromParts]
GO

CREATE FUNCTION [dbo].[func_DateFromParts]
(
    @Year INT,
    @Month INT,
    @DayOfMonth INT,
    @Hour INT = 0,  -- based on 24 hour clock (add 12 for PM :)
    @Min INT = 0,
    @Sec INT = 0
)
RETURNS DATETIME
AS
BEGIN

    RETURN DATEADD(second, @Sec, 
            DATEADD(minute, @Min, 
            DATEADD(hour, @Hour,
            DATEADD(day, @DayOfMonth - 1, 
            DATEADD(month, @Month - 1, 
            DATEADD(Year, @Year-1900, 0))))))

END

GO

You can call it like this...

SELECT dbo.func_DateFromParts(2013, 10, 4, 15, 50, DEFAULT)

Returns...

2013-10-04 15:50:00.000

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

What you put directly under src/main/java is in the default package, at the root of the classpath. It's the same for resources put under src/main/resources: they end up at the root of the classpath.

So the path of the resource is app-context.xml, not main/resources/app-context.xml.

How to convert a string to lower case in Bash?

The are various ways:

POSIX standard

tr

$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all

AWK

$ echo "$a" | awk '{print tolower($0)}'
hi all

Non-POSIX

You may run into portability issues with the following examples:

Bash 4.0

$ echo "${a,,}"
hi all

sed

$ echo "$a" | sed -e 's/\(.*\)/\L\1/'
hi all
# this also works:
$ sed -e 's/\(.*\)/\L\1/' <<< "$a"
hi all

Perl

$ echo "$a" | perl -ne 'print lc'
hi all

Bash

lc(){
    case "$1" in
        [A-Z])
        n=$(printf "%d" "'$1")
        n=$((n+32))
        printf \\$(printf "%o" "$n")
        ;;
        *)
        printf "%s" "$1"
        ;;
    esac
}
word="I Love Bash"
for((i=0;i<${#word};i++))
do
    ch="${word:$i:1}"
    lc "$ch"
done

Note: YMMV on this one. Doesn't work for me (GNU bash version 4.2.46 and 4.0.33 (and same behaviour 2.05b.0 but nocasematch is not implemented)) even with using shopt -u nocasematch;. Unsetting that nocasematch causes [[ "fooBaR" == "FOObar" ]] to match OK BUT inside case weirdly [b-z] are incorrectly matched by [A-Z]. Bash is confused by the double-negative ("unsetting nocasematch")! :-)

Fragments within Fragments

I have an application that I am developing that is laid out similar with Tabs in the Action Bar that launches fragments, some of these Fragments have multiple embedded Fragments within them.

I was getting the same error when I tried to run the application. It seems like if you instantiate the Fragments within the xml layout after a tab was unselected and then reselected I would get the inflator error.

I solved this replacing all the fragments in xml with Linearlayouts and then useing a Fragment manager/ fragment transaction to instantiate the fragments everything seems to working correctly at least on a test level right now.

I hope this helps you out.

Vertically align text to top within a UILabel

Building on all the other solutions posted, I made a simple little UILabel subclass that will handle vertical alignment for you when setting its alignment property. This will also update the label on orientation changes as well, will constrain the height to the text, and keep the label's width at it's original size.

.h

@interface VAlignLabel : UILabel
@property (nonatomic, assign) WBZVerticalAlignment alignment;
@end


.m

 -(void)setAlignment:(WBZVerticalAlignment)alignment{

    _alignment = alignment;

    CGSize s = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(self.frame.size.width, 9999) lineBreakMode:NSLineBreakByWordWrapping];

    switch (_alignment)
    {
        case wbzLabelAlignmentVerticallyTop:
            self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, s.height);
            break;
        case wbzLabelAlignmentVerticallyMiddle:
            self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + (self.frame.size.height - s.height)/2, self.frame.size.width, s.height);
            break;
        case wbzLabelAlignmentVerticallyBottom:
            self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + (self.frame.size.height - s.height), self.frame.size.width, s.height);
            break;
        default:
            break;
    }
}

-(void)layoutSubviews{
    [self setAlignment:self.alignment];
}

Excel how to fill all selected blank cells with text

Here's a tricky way to do this - select the cells that you want to replace and in Excel 2010 select F5 to bring up the "goto" box. Hit the "special" button. Select "blanks" - this should select all the cells that are blank. Enter NULL or whatever you want in the formula box and hit ctrl + enter to apply to all selected cells. Easy!

Swift - encode URL

Swift 3

In Swift 3 there is addingPercentEncoding

let originalString = "test/test"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
print(escapedString!)

Output:

test%2Ftest

Swift 1

In iOS 7 and above there is stringByAddingPercentEncodingWithAllowedCharacters

var originalString = "test/test"
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
println("escapedString: \(escapedString)")

Output:

test%2Ftest

The following are useful (inverted) character sets:

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

If you want a different set of characters to be escaped create a set:
Example with added "=" character:

var originalString = "test/test=42"
var customAllowedSet =  NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSet
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
println("escapedString: \(escapedString)")

Output:

test%2Ftest%3D42

Example to verify ascii characters not in the set:

func printCharactersInSet(set: NSCharacterSet) {
    var characters = ""
    let iSet = set.invertedSet
    for i: UInt32 in 32..<127 {
        let c = Character(UnicodeScalar(i))
        if iSet.longCharacterIsMember(i) {
            characters = characters + String(c)
        }
    }
    print("characters not in set: \'\(characters)\'")
}

How to find the date of a day of the week from a date using PHP?

I think this is what you want.

$dayofweek = date('w', strtotime($date));
$result    = date('Y-m-d', strtotime(($day - $dayofweek).' day', strtotime($date)));

How to change background color in android app

To change the background color in the simplest way possible programmatically (exclusively - no XML changes):

LinearLayout bgElement = (LinearLayout) findViewById(R.id.container);
bgElement.setBackgroundColor(Color.WHITE);

Only requirement is that your "base" element in the activity_whatever.xml has an id which you can reference in Java (container in this case):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/container"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
     ...
</LinearLayout>

Paschalis and James, who replied here, kind of lead me to this solution, after checking out the various possibilities in How to set the text color of TextView in code?.

Hope it helps someone!

How to position a div scrollbar on the left hand side?

Kind of an old question, but I thought I should throw in a method which wasn't widely available when this question was asked.

You can reverse the side of the scrollbar in modern browsers using transform: scaleX(-1) on a parent <div>, then apply the same transform to reverse a child, "sleeve" element.

HTML

<div class="parent">
  <div class="sleeve">
    <!-- content -->
  </div>
</div>

CSS

.parent {
  overflow: auto;
  transform: scaleX(-1); //Reflects the parent horizontally
}

.sleeve {
  transform: scaleX(-1); //Flips the child back to normal
}

Note: You may need to use an -ms-transform or -webkit-transform prefix for browsers as old as IE 9. Check CanIUse and click "show all" to see older browser requirements.

sklearn plot confusion matrix with labels

You might be interested by https://github.com/pandas-ml/pandas-ml/

which implements a Python Pandas implementation of Confusion Matrix.

Some features:

  • plot confusion matrix
  • plot normalized confusion matrix
  • class statistics
  • overall statistics

Here is an example:

In [1]: from pandas_ml import ConfusionMatrix
In [2]: import matplotlib.pyplot as plt

In [3]: y_test = ['business', 'business', 'business', 'business', 'business',
        'business', 'business', 'business', 'business', 'business',
        'business', 'business', 'business', 'business', 'business',
        'business', 'business', 'business', 'business', 'business']

In [4]: y_pred = ['health', 'business', 'business', 'business', 'business',
       'business', 'health', 'health', 'business', 'business', 'business',
       'business', 'business', 'business', 'business', 'business',
       'health', 'health', 'business', 'health']

In [5]: cm = ConfusionMatrix(y_test, y_pred)

In [6]: cm
Out[6]:
Predicted  business  health  __all__
Actual
business         14       6       20
health            0       0        0
__all__          14       6       20

In [7]: cm.plot()
Out[7]: <matplotlib.axes._subplots.AxesSubplot at 0x1093cf9b0>

In [8]: plt.show()

Plot confusion matrix

In [9]: cm.print_stats()
Confusion Matrix:

Predicted  business  health  __all__
Actual
business         14       6       20
health            0       0        0
__all__          14       6       20


Overall Statistics:

Accuracy: 0.7
95% CI: (0.45721081772371086, 0.88106840959427235)
No Information Rate: ToDo
P-Value [Acc > NIR]: 0.608009812201
Kappa: 0.0
Mcnemar's Test P-Value: ToDo


Class Statistics:

Classes                                 business health
Population                                    20     20
P: Condition positive                         20      0
N: Condition negative                          0     20
Test outcome positive                         14      6
Test outcome negative                          6     14
TP: True Positive                             14      0
TN: True Negative                              0     14
FP: False Positive                             0      6
FN: False Negative                             6      0
TPR: (Sensitivity, hit rate, recall)         0.7    NaN
TNR=SPC: (Specificity)                       NaN    0.7
PPV: Pos Pred Value (Precision)                1      0
NPV: Neg Pred Value                            0      1
FPR: False-out                               NaN    0.3
FDR: False Discovery Rate                      0      1
FNR: Miss Rate                               0.3    NaN
ACC: Accuracy                                0.7    0.7
F1 score                               0.8235294      0
MCC: Matthews correlation coefficient        NaN    NaN
Informedness                                 NaN    NaN
Markedness                                     0      0
Prevalence                                     1      0
LR+: Positive likelihood ratio               NaN    NaN
LR-: Negative likelihood ratio               NaN    NaN
DOR: Diagnostic odds ratio                   NaN    NaN
FOR: False omission rate                       1      0

What's the difference between ASCII and Unicode?

Storage

Given numbers are only for storing 1 character

  • ASCII ? 27 bits (1 byte)
  • Extended ASCII ? 28 bits (1 byte)
  • UTF-8 ? minimum 28, maximum 232 bits (min 1, max 4 bytes)
  • UTF-16 ? minimum 216, maximum 232 bits (min 2, max 4 bytes)
  • UTF-32 ? 232 bits (4 bytes)

Usage (as of Feb 2020)

Percentages of websites using various character encodings

Find and Replace string in all files recursive using grep and sed

As @Didier said, you can change your delimiter to something other than /:

grep -rl $oldstring /path/to/folder | xargs sed -i s@$oldstring@$newstring@g

error: strcpy was not declared in this scope

When you say:

 #include <cstring>

the g++ compiler should put the <string.h> declarations it itself includes into the std:: AND the global namespaces. It looks for some reason as if it is not doing that. Try replacing one instance of strcpy with std::strcpy and see if that fixes the problem.

How to compress a String in Java?

Take a look at the Huffman algorithm.

https://codereview.stackexchange.com/questions/44473/huffman-code-implementation

The idea is that each character is replaced with sequence of bits, depending on their frequency in the text (the more frequent, the smaller the sequence).

You can read your entire text and build a table of codes, for example:

Symbol Code

a 0

s 10

e 110

m 111

The algorithm builds a symbol tree based on the text input. The more variety of characters you have, the worst the compression will be.

But depending on your text, it could be effective.

Vertical Alignment of text in a table cell

td.description {vertical-align: top;}

where description is the class name of the td with that text in it

_x000D_
_x000D_
td.description {_x000D_
  vertical-align: top;_x000D_
}
_x000D_
<td class="description">Description</td>
_x000D_
_x000D_
_x000D_

OR inline (yuk!)

_x000D_
_x000D_
<td style="vertical-align: top;">Description</td>
_x000D_
_x000D_
_x000D_

Repeat a string in JavaScript a number of times

In ES2015/ES6 you can use "*".repeat(n)

So just add this to your projects, and your are good to go.

  String.prototype.repeat = String.prototype.repeat || 
    function(n) {
      if (n < 0) throw new RangeError("invalid count value");
      if (n == 0) return "";
      return new Array(n + 1).join(this.toString()) 
    };

How to Navigate from one View Controller to another using Swift

In AppDelegate you can write like this...

var window: UIWindow?

fileprivate let navigationCtrl = UINavigationController()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    self.createWindow()

    self.showLoginVC()

    return true
}

func createWindow() {
    let screenSize = UIScreen.main.bounds
    self.window = UIWindow(frame: screenSize)
    self.window?.backgroundColor = UIColor.white
    self.window?.makeKeyAndVisible()
    self.window?.rootViewController = navigationCtrl
}

func showLoginVC() {
    let storyboardBundle = Bundle.main
    // let storyboardBundle = Bundle(for: ClassName.self) // if you are not using main application, means may be you are crating a framework or library you can use this statement instead
    let storyboard = UIStoryboard(name: "LoginVC", bundle: storyboardBundle)
    let loginVC = storyboard.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
    navigationCtrl.pushViewController(loginVC, animated: false)
}

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

I had the same problem, then I did this two steps:

  • Enable "Allow less secure apps" on your google account security policy.
  • Restart your local servers.

jQuery changing font family and font size

Full working solution :

HTML:

<form id="myform">
    <button>erase</button>
    <select id="fs"> 
        <option value="Arial">Arial</option>
        <option value="Verdana ">Verdana </option>
        <option value="Impact ">Impact </option>
        <option value="Comic Sans MS">Comic Sans MS</option>
    </select>

    <select id="size">
        <option value="7">7</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
    </select>
</form>

<br/>

<textarea class="changeMe">Text into textarea</textarea>
<div id="container" class="changeMe">
    <div id="float">
        <p>
            Text into container
        </p>
    </div>
</div>

jQuery:

$("#fs").change(function() {
    //alert($(this).val());
    $('.changeMe').css("font-family", $(this).val());

});

$("#size").change(function() {
    $('.changeMe').css("font-size", $(this).val() + "px");
});

Fiddle here: http://jsfiddle.net/AaT9b/

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

Just use the javascript window.open function with the second parameter at "_blank"

<button onClick="javascript:window.open('http://www.facebook.com', '_blank');">facebook</button>

How to limit the maximum files chosen when using multiple file input

In javascript you can do something like this

<input
  ref="fileInput"
  multiple
  type="file"
  style="display: none"
  @change="trySubmitFile"
>

and the function can be something like this.

trySubmitFile(e) {
  if (this.disabled) return;
  const files = e.target.files || e.dataTransfer.files;
  if (files.length > 5) {
    alert('You are only allowed to upload a maximum of 2 files at a time');
  }
  if (!files.length) return;
  for (let i = 0; i < Math.min(files.length, 2); i++) {
    this.fileCallback(files[i]);
  }
}

I am also searching for a solution where this can be limited at the time of selecting files but until now I could not find anything like that.

How often should Oracle database statistics be run?

At my last job we ran statistics once a week. If I remember correctly, we scheduled them on a Thursday night, and on Friday the DBAs were very careful to monitor the longest running queries for anything unexpected. (Friday was picked because it was often just after a code release, and tended to be a fairly low traffic day.) When they saw a bad query they would find a better query plan and save that one so it wouldn't change again unexpectedly. (Oracle has tools to do this for you automatically, you tell it the query to optimize and it does.)

Many organizations avoid running statistics out of fear of bad query plans popping up unexpectedly. But this usually means that their query plans get worse and worse over time. And when they do run statistics then they encounter a number of problems. The resulting scramble to fix those issues confirms their fears about the dangers of running statistics. But if they ran statistics regularly, used the monitoring tools as they are supposed to, and fixed issues as they came up then they would have fewer headaches, and they wouldn't encounter them all at once.

Detecting Windows or Linux?

Useful simple class are forked by me on: https://gist.github.com/kiuz/816e24aa787c2d102dd0

public class OSValidator {

    private static String OS = System.getProperty("os.name").toLowerCase();

    public static void main(String[] args) {

        System.out.println(OS);

        if (isWindows()) {
            System.out.println("This is Windows");
        } else if (isMac()) {
            System.out.println("This is Mac");
        } else if (isUnix()) {
            System.out.println("This is Unix or Linux");
        } else if (isSolaris()) {
            System.out.println("This is Solaris");
        } else {
            System.out.println("Your OS is not support!!");
        }
    }

    public static boolean isWindows() {
        return OS.contains("win");
    }

    public static boolean isMac() {
        return OS.contains("mac");
    }

    public static boolean isUnix() {
        return (OS.contains("nix") || OS.contains("nux") || OS.contains("aix"));
    }

    public static boolean isSolaris() {
        return OS.contains("sunos");
    }
    public static String getOS(){
        if (isWindows()) {
            return "win";
        } else if (isMac()) {
            return "osx";
        } else if (isUnix()) {
            return "uni";
        } else if (isSolaris()) {
            return "sol";
        } else {
            return "err";
        }
    }

}

Write a number with two decimal places SQL Server

try this

SELECT CONVERT(DECIMAL(10,2),YOURCOLUMN)

How to get all options in a drop-down list by Selenium WebDriver using C#?

It seems to be a cast exception. Can you try converting your result to a list i.e. elem.findElements(xx).toList ?

Python String and Integer concatenation

NOTE:

The method used in this answer (backticks) is deprecated in later versions of Python 2, and removed in Python 3. Use the str() function instead.


You can use :

string = 'string'
for i in range(11):
    string +=`i`
print string

It will print string012345678910.

To get string0, string1 ..... string10 you can use this as @YOU suggested

>>> string = "string"
>>> [string+`i` for i in range(11)]

Update as per Python3

You can use :

string = 'string'
for i in range(11):
    string +=str(i)
print string

It will print string012345678910.

To get string0, string1 ..... string10 you can use this as @YOU suggested

>>> string = "string"
>>> [string+str(i) for i in range(11)]

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

I faced this error becouse I sent the Query string with wrong format

http://localhost:56110/user/updateuserinfo?Id=55?Name=Basheer&Phone=(111)%20111-1111
------------------------------------------^----(^)-----------^---...
--------------------------------------------must be &

so make sure your Query String or passed parameter in the right format

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

'simple' code that works and can be read by a ten year old:

function deleteNonEmptyDir($dir) 
{
   if (is_dir($dir)) 
   {
        $objects = scandir($dir);

        foreach ($objects as $object) 
        {
            if ($object != "." && $object != "..") 
            {
                if (filetype($dir . "/" . $object) == "dir")
                {
                    deleteNonEmptyDir($dir . "/" . $object); 
                }
                else
                {
                    unlink($dir . "/" . $object);
                }
            }
        }

        reset($objects);
        rmdir($dir);
    }
}

Please note that all I did was expand/simplify and fix (didn't work for non empty dir) the solution here: In PHP how do I recursively remove all folders that aren't empty?

Can I use Homebrew on Ubuntu?

Linux is now officially supported in brew - see the Homebrew 2.0.0 blog post. As shown on https://brew.sh, just copy/paste this into a command prompt:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

PostgreSQL: days/months/years between two dates

SELECT
  AGE('2012-03-05', '2010-04-01'),
  DATE_PART('year', AGE('2012-03-05', '2010-04-01')) AS years,
  DATE_PART('month', AGE('2012-03-05', '2010-04-01')) AS months,
  DATE_PART('day', AGE('2012-03-05', '2010-04-01')) AS days;

This will give you full years, month, days ... between two dates:

          age          | years | months | days
-----------------------+-------+--------+------
 1 year 11 mons 4 days |     1 |     11 |    4

More detailed datediff information.

Does hosts file exist on the iPhone? How to change it?

It might exist, but you cannot change it on a non-jailbreaked iPhone.

Assuming that your development webserver is on a Mac, why don't you simply use its Bonjour name (e.g. MyMac.local.) instead of myrealwebserverontheinternet.com?

Error in plot.new() : figure margins too large in R

I found the same error today. I have tried the "Clear all Plots" button, but it was giving me the same error. Then this trick worked for me, Try to increase the plot area by dragging. It will help you for sure.

How to pass text in a textbox to JavaScript function?

You could either access the element’s value by its name:

document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"

So:

<input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />

Or you assign an ID to the element that then identifies it and you can access it with getElementById:

<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />

MySQL - length() vs char_length()

LENGTH() returns the length of the string measured in bytes.
CHAR_LENGTH() returns the length of the string measured in characters.

This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:

select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1

As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC in UTF-8) even though it's only one character.

How to enumerate a range of numbers starting at 1

h = [(i + 1, x) for i, x in enumerate(xrange(2000, 2005))]

Get Enum from Description attribute

Should be pretty straightforward, its just the reverse of your previous method;

public static int GetEnumFromDescription(string description, Type enumType)
{
    foreach (var field in enumType.GetFields())
    {
        DescriptionAttribute attribute
            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))as DescriptionAttribute;
        if(attribute == null)
            continue;
        if(attribute.Description == description)
        {
            return (int) field.GetValue(null);
        }
    }
    return 0;
}

Usage:

Console.WriteLine((Animal)GetEnumFromDescription("Giant Panda",typeof(Animal)));

How to implement and do OCR in a C# project?

I'm using tesseract OCR engine with TessNet2 (a C# wrapper - http://www.pixel-technology.com/freeware/tessnet2/).

Some basic code:

using tessnet2;

...

Bitmap image = new Bitmap(@"u:\user files\bwalker\2849257.tif");
            tessnet2.Tesseract ocr = new tessnet2.Tesseract();
            ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,$-/#&=()\"':?"); // Accepted characters
            ocr.Init(@"C:\Users\bwalker\Documents\Visual Studio 2010\Projects\tessnetWinForms\tessnetWinForms\bin\Release\", "eng", false); // Directory of your tessdata folder
            List<tessnet2.Word> result = ocr.DoOCR(image, System.Drawing.Rectangle.Empty);
            string Results = "";
            foreach (tessnet2.Word word in result)
            {
                Results += word.Confidence + ", " + word.Text + ", " + word.Left + ", " + word.Top + ", " + word.Bottom + ", " + word.Right + "\n";
            }

How to send list of file in a folder to a txt file in Linux

If only names of regular files immediately contained within a directory (assume it's ~/dirs) are needed, you can do

find ~/docs -type f -maxdepth 1 > filenames.txt

Access VBA | How to replace parts of a string with another string

Since the string "North" might be the beginning of a street name, e.g. "Northern Boulevard", street directions are always between the street number and the street name, and separated from street number and street name.

Public Function strReplace(varValue As Variant) as Variant

Select Case varValue

    Case "Avenue"
        strReplace = "Ave"

    Case " North "
        strReplace = " N "

    Case Else
        strReplace = varValue

End Select

End Function

:first-child not working as expected

:first-child selects the first h1 if and only if it is the first child of its parent element. In your example, the ul is the first child of the div.

The name of the pseudo-class is somewhat misleading, but it's explained pretty clearly here in the spec.

jQuery's :first selector gives you what you're looking for. You can do this:

$('.detail_container h1:first').css("color", "blue");

Bootstrap 3 and Youtube in Modal

Here is another solution: Force HTML5 youtube video

Just add ?html5=1 to the source attribute on the iframe, like this:

<iframe src="http://www.youtube.com/embed/dP15zlyra3c?html5=1"></iframe>

Difference between socket and websocket?

WebSocket is just another application level protocol over TCP protocol, just like HTTP.

Some snippets < Spring in Action 4> quoted below, hope it can help you understand WebSocket better.

In its simplest form, a WebSocket is just a communication channel between two applications (not necessarily a browser is involved)...WebSocket communication can be used between any kinds of applications, but the most common use of WebSocket is to facilitate communication between a server application and a browser-based application.

Cannot invoke an expression whose type lacks a call signature

TypeScript supports structural typing (also called duck typing), meaning that types are compatible when they share the same members. Your problem is that Apple and Pear don't share all their members, which means that they are not compatible. They are however compatible to another type that has only the isDecayed: boolean member. Because of structural typing, you don' need to inherit Apple and Pear from such an interface.

There are different ways to assign such a compatible type:

Assign type during variable declaration

This statement is implicitly typed to Apple[] | Pear[]:

const fruits = fruitBasket[key];

You can simply use a compatible type explicitly in in your variable declaration:

const fruits: { isDecayed: boolean }[] = fruitBasket[key];

For additional reusability, you can also define the type first and then use it in your declaration (note that the Apple and Pear interfaces don't need to be changed):

type Fruit = { isDecayed: boolean };
const fruits: Fruit[] = fruitBasket[key];

Cast to compatible type for the operation

The problem with the given solution is that it changes the type of the fruits variable. This might not be what you want. To avoid this, you can narrow the array down to a compatible type before the operation and then set the type back to the same type as fruits:

const fruits: fruitBasket[key];
const freshFruits = (fruits as { isDecayed: boolean }[]).filter(fruit => !fruit.isDecayed) as typeof fruits;

Or with the reusable Fruit type:

type Fruit = { isDecayed: boolean };
const fruits: fruitBasket[key];
const freshFruits = (fruits as Fruit[]).filter(fruit => !fruit.isDecayed) as typeof fruits;

The advantage of this solution is that both, fruits and freshFruits will be of type Apple[] | Pear[].

How to convert BigDecimal to Double in Java?

Use doubleValue method present in BigDecimal class :

double doubleValue()

Converts this BigDecimal to a double.

How to change Status Bar text color in iOS

You can do this from info.plist:

1) "View controller-based status bar appearance" set to "NO"

2) "Status bar style" set to "UIStatusBarStyleLightContent"

done

What is the keyguard in Android?

Keyguard basically refers to the code that handles the unlocking of the phone. it's like the keypad lock on your nokia phone a few years back just with the utility on a touchscreen.

you can find more info it you look in android/app or com\android\internal\policy\impl

Good Luck !

Java: Sending Multiple Parameters to Method

You can use varargs

public function yourFunction(Parameter... parameters)

See also

Java multiple arguments dot notation - Varargs

Python conditional assignment operator

I am not sure I understand the question properly here ... Trying to "read" the value of an "undefined" variable name will trigger a NameError. (see here, that Python has "names", not variables...).

== EDIT ==

As pointed out in the comments by delnan, the code below is not robust and will break in numerous situations ...

Nevertheless, if your variable "exists", but has some sort of dummy value, like None, the following would work :

>>> my_possibly_None_value = None
>>> myval = my_possibly_None_value or 5
>>> myval
5
>>> my_possibly_None_value = 12
>>> myval = my_possibly_None_value or 5
>>> myval
12
>>> 

(see this paragraph about Truth Values)

Angularjs: Get element in controller

Create custom directive

masterApp.directive('ngRenderCallback', function() {
    return {
        restrict: "A",
        link: function ($scope, element, attrs) {
            setTimeout(function(){ 
                $scope[attrs.ngEl] = element[0];
                $scope.$eval(attrs.ngRenderCallback);               
            }, 30);
        }
    }
});

code for html template

<div ng-render-callback="fnRenderCarousel('carouselA')" ng-el="carouselA"></div>

function in controller

$scope.fnRenderCarousel = function(elName){
    $($scope[elName]).carousel();
}

insert data into database with codeigniter

function saveProfile(){
    $firstname = $this->input->post('firstname');
    $lastname = $this->input->post('lastname');
    $post_data = array('firstname'=> $firstname,'lastname'=>$lastname);
    $this->db->insert('posts',$post_data);
    return $this->db->insert_id(); 
}

How to convert String to DOM Document object in java?

     public static void main(String[] args) {
    final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
                            "<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
                            "<role>Developer</role><gen>Male</gen></Emp>";
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder;  
        try 
        {  
            builder = factory.newDocumentBuilder();  
            Document doc = builder.parse( new InputSource( new StringReader( xmlStr )) ); 

        } catch (Exception e) {  
            e.printStackTrace();  
        } 
  }

How to install Anaconda on RaspBerry Pi 3 Model B

Installing Miniconda on Raspberry Pi and adding Python 3.5 / 3.6

Skip the first section if you have already installed Miniconda successfully.

Installation of Miniconda on Raspberry Pi

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
sudo md5sum Miniconda3-latest-Linux-armv7l.sh
sudo /bin/bash Miniconda3-latest-Linux-armv7l.sh

Accept the license agreement with yes

When asked, change the install location: /home/pi/miniconda3

Do you wish the installer to prepend the Miniconda3 install location to PATH in your /root/.bashrc ? yes

Now add the install path to the PATH variable:

sudo nano /home/pi/.bashrc

Go to the end of the file .bashrc and add the following line:

export PATH="/home/pi/miniconda3/bin:$PATH"

Save the file and exit.

To test if the installation was successful, open a new terminal and enter

conda

If you see a list with commands you are ready to go.

But how can you use Python versions greater than 3.4 ?


Adding Python 3.5 / 3.6 to Miniconda on Raspberry Pi

After the installation of Miniconda I could not yet install Python versions higher than Python 3.4, but i needed Python 3.5. Here is the solution which worked for me on my Raspberry Pi 4:

First i added the Berryconda package manager by jjhelmus (kind of an up-to-date version of the armv7l version of Miniconda):

conda config --add channels rpi

Only now I was able to install Python 3.5 or 3.6 without the need for compiling it myself:

conda install python=3.5
conda install python=3.6

Afterwards I was able to create environments with the added Python version, e.g. with Python 3.5:

conda create --name py35 python=3.5

The new environment "py35" can now be activated:

source activate py35

Using Python 3.7 on Raspberry Pi

Currently Jonathan Helmus, who is the developer of berryconda, is working on adding Python 3.7 support, if you want to see if there is an update or if you want to support him, have a look at this pull request. (update 20200623) berryconda is now inactive, This project is no longer active, no recipe will be updated and no packages will be added to the rpi channel. If you need to run Python 3.7 on your Pi right now, you can do so without Miniconda. Check if you are running the latest version of Raspbian OS called Buster. Buster ships with Python 3.7 preinstalled (source), so simply run your program with the following command:

Python3.7 app-that-needs-python37.py

I hope this solution will work for you too!

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

You can leverage Conditional Formatting as follows.

  1. In cell H8 select Format > Conditional Formatting...
  2. In Condition1, select Formula Is in first drop down menu
  3. In the next textbox type =I8="Elementary"
  4. Select Format... and select the color you want etc.
  5. Select Add>> and repeat steps 1 to 4

Note that you can only have (in excel 2003) three separate conditions so you will only be able to have different formatting for three items in the drop down menu. If the idea is to make them visually distinct then (maybe) having no color for one of the selections is not a problem?

If the cell is never blank, you can use format (not conditional) to get 4 distinct visuals.

Installing PIL with pip

You can install PIL using apt install:

For Python 3 use:

sudo apt install python3-pil

For Python 2 use:

sudo apt install python-pil

Where pil should be lowercase as Clarkey252 points out

How to create dispatch queue in Swift 3

 DispatchQueue.main.async {
          self.collectionView?.reloadData() // Depends if you were populating a collection view or table view
    }


OperationQueue.main.addOperation {
    self.lblGenre.text = self.movGenre
}

//use Operation Queue if you need to populate the objects(labels, imageview, textview) on your viewcontroller

Drop a temporary table if it exists

Check for the existence by retrieving its object_id:

if object_id('tempdb..##clients_keyword') is not null
    drop table ##clients_keyword

How to Delete Session Cookie?

This needs to be done on the server-side, where the cookie was issued.

How to get Linux console window width in Python

use

import console
(width, height) = console.getTerminalSize()

print "Your terminal's width is: %d" % width

EDIT: oh, I'm sorry. That's not a python standard lib one, here's the source of console.py (I don't know where it's from).

The module seems to work like that: It checks if termcap is available, when yes. It uses that; if no it checks whether the terminal supports a special ioctl call and that does not work, too, it checks for the environment variables some shells export for that. This will probably work on UNIX only.

def getTerminalSize():
    import os
    env = os.environ
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
        '1234'))
        except:
            return
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        cr = (env.get('LINES', 25), env.get('COLUMNS', 80))

        ### Use get(key[, default]) instead of a try/catch
        #try:
        #    cr = (env['LINES'], env['COLUMNS'])
        #except:
        #    cr = (25, 80)
    return int(cr[1]), int(cr[0])

Sort a List of Object in VB.NET

If you need a custom string sort, you can create a function that returns a number based on the order you specify.

For example, I had pictures that I wanted to sort based on being front side or clasp. So I did the following:

Private Function sortpictures(s As String) As Integer
    If Regex.IsMatch(s, "FRONT") Then
        Return 0
    ElseIf Regex.IsMatch(s, "SIDE") Then
        Return 1
    ElseIf Regex.IsMatch(s, "CLASP") Then
        Return 2
    Else
        Return 3
    End If
End Function

Then I call the sort function like this:

list.Sort(Function(elA As String, elB As String)
                  Return sortpictures(elA).CompareTo(sortpictures(elB))
              End Function)

MySql export schema without data

Beware though that --no-data option will not include the view definition. So if yo had a view like following

create view v1 
 select `a`.`id` AS `id`,
 `a`.`created_date` AS `created_date` 
from t1;

with --no-data option, view definition will get changed to following

create view v1
 select 1 AS `id`, 1 AS `created_date`

Get sum of MySQL column in PHP

You can completely handle it in the MySQL query:

SELECT SUM(column_name) FROM table_name;

Using PDO (mysql_query is deprecated)

$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');
$stmt->execute();

$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sum = $row['value_sum'];

Or using mysqli:

$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes'); 
$row = mysqli_fetch_assoc($result); 
$sum = $row['value_sum'];

Creating a blurring overlay view

An important supplement to @Joey's answer

This applies to a situation where you want to present a blurred-background UIViewController with UINavigationController.

// suppose you've done blur effect with your presented view controller
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController];

// this is very important, if you don't do this, the blur effect will darken after view did appeared
// the reason is that you actually present navigation controller, not presented controller
// please note it's "OverFullScreen", not "OverCurrentContext"
nav.modalPresentationStyle = UIModalPresentationOverFullScreen;

UIViewController *presentedViewController = [[UIViewController alloc] init]; 
// the presented view controller's modalPresentationStyle is "OverCurrentContext"
presentedViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;

[presentingViewController presentViewController:nav animated:YES completion:nil];

Enjoy!

How do I install cURL on cygwin?

In the Cygwin package manager, click on curl from within the "net" category. Yes, it's that simple.

comparing strings in vb

If String.Compare(string1,string2,True) Then

    'perform operation

EndIf

Modifying a subset of rows in a pandas dataframe

Here is from pandas docs on advanced indexing:

The section will explain exactly what you need! Turns out df.loc (as .ix has been deprecated -- as many have pointed out below) can be used for cool slicing/dicing of a dataframe. And. It can also be used to set things.

df.loc[selection criteria, columns I want] = value

So Bren's answer is saying 'find me all the places where df.A == 0, select column B and set it to np.nan'

Cannot access wamp server on local network

Turn off your firewall for port 80 from any address. Turn off 443 if you need https (SSL) access. Open the configuration file (http.conf) and find the lines that say:

Allow from 127.0.0.1

Change them to read

Allow from all

Restart the wampserver. It will now work. Enjoy!!

Rails - How to use a Helper Inside a Controller

My problem resolved with Option 1. Probably the simplest way is to include your helper module in your controller:

class ApplicationController < ActionController::Base
  include ApplicationHelper

...

How to check if IsNumeric

Other answers have suggested using TryParse, which might fit your needs, but the safest way to provide the functionality of the IsNumeric function is to reference the VB library and use the IsNumeric function.

IsNumeric is more flexible than TryParse. For example, IsNumeric returns true for the string "$100", while the TryParse methods all return false.

To use IsNumeric in C#, add a reference to Microsoft.VisualBasic.dll. The function is a static method of the Microsoft.VisualBasic.Information class, so assuming you have using Microsoft.VisualBasic;, you can do this:

if (Information.IsNumeric(txtMyText.Text.Trim())) //...

What is the problem with shadowing names defined in outer scopes?

The currently most up-voted and accepted answer and most answers here miss the point.

It doesn't matter how long your function is, or how you name your variable descriptively (to hopefully minimize the chance of potential name collision).

The fact that your function's local variable or its parameter happens to share a name in the global scope is completely irrelevant. And in fact, no matter how carefully you choose you local variable name, your function can never foresee "whether my cool name yadda will also be used as a global variable in future?". The solution? Simply don't worry about that! The correct mindset is to design your function to consume input from and only from its parameters in signature. That way you don't need to care what is (or will be) in global scope, and then shadowing becomes not an issue at all.

In other words, the shadowing problem only matters when your function need to use the same name local variable and the global variable. But you should avoid such design in the first place. The OP's code does not really have such design problem. It is just that PyCharm is not smart enough and it gives out a warning just in case. So, just to make PyCharm happy, and also make our code clean, see this solution quoting from silyevsk's answer to remove the global variable completely.

def print_data(data):
    print data

def main():
    data = [4, 5, 6]
    print_data(data)

main()

This is the proper way to "solve" this problem, by fixing/removing your global thing, not adjusting your current local function.

How to find length of dictionary values

To find all of the lengths of the values in a dictionary you can do this:

lengths = [len(v) for v in d.values()]

C# how to create a Guid value?

Guid.NewGuid() creates a new random guid.

Why does flexbox stretch my image rather than retaining aspect ratio?

Adding margin to align images:

Since we wanted the image to be left-aligned, we added:

img {
  margin-right: auto;
}

Similarly for image to be right-aligned, we can add margin-right: auto;. The snippet shows a demo for both types of alignment.

Good Luck...

_x000D_
_x000D_
div {_x000D_
  display:flex; _x000D_
  flex-direction:column;_x000D_
  border: 2px black solid;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  text-align: center;_x000D_
}_x000D_
hr {_x000D_
  border: 1px black solid;_x000D_
  width: 100%_x000D_
}_x000D_
img.one {_x000D_
  margin-right: auto;_x000D_
}_x000D_
_x000D_
img.two {_x000D_
  margin-left: auto;_x000D_
}
_x000D_
<div>_x000D_
  <h1>Flex Box</h1>_x000D_
  _x000D_
  <hr />_x000D_
  _x000D_
  <img src="https://via.placeholder.com/80x80" class="one" _x000D_
  />_x000D_
  _x000D_
  _x000D_
  <img src="https://via.placeholder.com/80x80" class="two" _x000D_
  />_x000D_
  _x000D_
  <hr />_x000D_
</div>
_x000D_
_x000D_
_x000D_

case-insensitive matching in xpath?

XPath 2 has a lower-case (and upper-case) string function. That's not quite the same as case-insensitive, but hopefully it will be close enough:

//CD[lower-case(@title)='empire burlesque']

If you are using XPath 1, there is a hack using translate.

Mongoose and multiple database in single node.js project

According to the fine manual, createConnection() can be used to connect to multiple databases.

However, you need to create separate models for each connection/database:

var conn      = mongoose.createConnection('mongodb://localhost/testA');
var conn2     = mongoose.createConnection('mongodb://localhost/testB');

// stored in 'testA' database
var ModelA    = conn.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testA database' }
}));

// stored in 'testB' database
var ModelB    = conn2.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testB database' }
}));

I'm pretty sure that you can share the schema between them, but you have to check to make sure.

Read XML Attribute using XmlDocument

I have an Xml File books.xml

<ParameterDBConfig>
    <ID Definition="1" />
</ParameterDBConfig>

Program:

XmlDocument doc = new XmlDocument();
doc.Load("D:/siva/books.xml");
XmlNodeList elemList = doc.GetElementsByTagName("ID");     
for (int i = 0; i < elemList.Count; i++)     
{
    string attrVal = elemList[i].Attributes["Definition"].Value;
}

Now, attrVal has the value of ID.

Error with multiple definitions of function

The problem is that if you include fun.cpp in two places in your program, you will end up defining it twice, which isn't valid.

You don't want to include cpp files. You want to include header files.

The header file should just have the class definition. The corresponding cpp file, which you will compile separately, will have the function definition.

fun.hpp:

#include <iostream>

class classA {
    friend void funct();
public:
    classA(int a=1,int b=2):propa(a),propb(b){std::cout<<"constructor\n";}
private:
    int propa;
    int propb;
    void outfun(){
        std::cout<<"propa="<<propa<<endl<<"propb="<<propb<< std::endl;
    }
};

fun.cpp:

#include "fun.hpp"

using namespace std;

void funct(){
    cout<<"enter funct"<<endl;
    classA tmp(1,2);
    tmp.outfun();
    cout<<"exit funct"<<endl;
}

mainfile.cpp:

#include <iostream>
#include "fun.hpp"
using namespace std;

int main(int nargin,char* varargin[]) {
    cout<<"call funct"<<endl;
    funct();
    cout<<"exit main"<<endl;
    return 0;
}

Note that it is generally recommended to avoid using namespace std in header files.

How to select all elements with a particular ID in jQuery?

$("div[id^=" + controlid + "]") will return all the controls with the same name but you need to ensure that the text should not present in any of the controls

How to iterate through property names of Javascript object?

Use for...in loop:

for (var key in obj) {
   console.log(' name=' + key + ' value=' + obj[key]);

   // do some more stuff with obj[key]
}

PHP header redirect 301 - what are the implications?

The effect of the 301 would be that the search engines will index /option-a instead of /option-x. Which is probably a good thing since /option-x is not reachable for the search index and thus could have a positive effect on the index. Only if you use this wisely ;-)

After the redirect put exit(); to stop the rest of the script to execute

header("HTTP/1.1 301 Moved Permanently"); 
header("Location: /option-a"); 
exit();

The total number of locks exceeds the lock table size

First, you can use sql command show global variables like 'innodb_buffer%'; to check the buffer size.

Solution is find your my.cnf file and add,

_x000D_
_x000D_
[mysqld]_x000D_
innodb_buffer_pool_size=1G # depends on your data and machine
_x000D_
_x000D_
_x000D_

DO NOT forget to add [mysqld], otherwise, it won't work.

In my case, ubuntu 16.04, my.cnf is located under the folder /etc/mysql/.

Best way to do multi-row insert in Oracle?

Here is a very useful step by step guideline for insert multi rows in Oracle:

https://livesql.oracle.com/apex/livesql/file/content_BM1LJQ87M5CNIOKPOWPV6ZGR3.html

The last step:

INSERT ALL
/* Everyone is a person, so insert all rows into people */
WHEN 1=1 THEN
INTO people (person_id, given_name, family_name, title)
VALUES (id, given_name, family_name, title)
/* Only people with an admission date are patients */
WHEN admission_date IS NOT NULL THEN
INTO patients (patient_id, last_admission_date)
VALUES (id, admission_date)
/* Only people with a hired date are staff */
WHEN hired_date IS NOT NULL THEN
INTO staff (staff_id, hired_date)
VALUES (id, hired_date)
  WITH names AS (
    SELECT 4 id, 'Ruth' given_name, 'Fox' family_name, 'Mrs' title,
           NULL hired_date, DATE'2009-12-31' admission_date
    FROM   dual UNION ALL
    SELECT 5 id, 'Isabelle' given_name, 'Squirrel' family_name, 'Miss' title ,
           NULL hired_date, DATE'2014-01-01' admission_date
    FROM   dual UNION ALL
    SELECT 6 id, 'Justin' given_name, 'Frog' family_name, 'Master' title,
           NULL hired_date, DATE'2015-04-22' admission_date
    FROM   dual UNION ALL
    SELECT 7 id, 'Lisa' given_name, 'Owl' family_name, 'Dr' title,
           DATE'2015-01-01' hired_date, NULL admission_date
    FROM   dual
  )
  SELECT * FROM names

Infinity symbol with HTML

According to this page, it's &infin;.

Dynamic constant assignment

Constants in ruby cannot be defined inside methods. See the notes at the bottom of this page, for example

How to make input type= file Should accept only pdf and xls

you can use this:

HTML

<input name="userfile" type="file" accept="application/pdf, application/vnd.ms-excel" />

support only .PDF and .XLS files

See line breaks and carriage returns in editor

I suggest you to edit your .vimrc file, for running a list of commands. Edit your .vimrc file, like this :

cat >> ~/.vimrc <<EOF
set ffs=unix
set encoding=utf-8
set fileencoding=utf-8
set listchars=eol:¶
set list
EOF

When you're executing vim, the commands into .vimrc are executed, and you can see this example :

My line with CRLF eol here ^M¶

Wrap text in <td> tag

This works really well:

<td><div style = "width:80px; word-wrap: break-word"> your text </div></td> 

You can use the same width for all your <div's, or adjust the width in each case to break your text wherever you like.

This way you do not have to fool around with fixed table widths, or complex css.

DateTime vs DateTimeOffset

This piece of code from Microsoft explains everything:

// Find difference between Date.Now and Date.UtcNow
  date1 = DateTime.Now;
  date2 = DateTime.UtcNow;
  difference = date1 - date2;
  Console.WriteLine("{0} - {1} = {2}", date1, date2, difference);

  // Find difference between Now and UtcNow using DateTimeOffset
  dateOffset1 = DateTimeOffset.Now;
  dateOffset2 = DateTimeOffset.UtcNow;
  difference = dateOffset1 - dateOffset2;
  Console.WriteLine("{0} - {1} = {2}", 
                    dateOffset1, dateOffset2, difference);
  // If run in the Pacific Standard time zone on 4/2/2007, the example
  // displays the following output to the console:
  //    4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
  //    4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00

Multi-key dictionary in c#?

I think you would need a Tuple2 like class. Be sure that it's GetHashCode() and Equals() is based upon the two contained elements.

See Tuples in C#

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

already had this type of problem.

my solution was:

delete the folder from svn but keep a copy of the folder somewhere, commit the changes. in the backup-copy, delete recursively all the .svn-folders in it. for this you might run

#!/bin/bash

find -name '.svn' | while read directory;
do
    echo $directory;
    rm -rf "$directory";
done;

delete the local repository and re-check out entire project. don't know whether partial deletion/checkout are sufficient.

regards

html button to send email

You can not directly send an email with a HTML form. You can however send the form to your web server and then generate the email with a server side program written in e.g. PHP.

The other solution is to create a link as you did with the "mailto:". This will open the local email program from the user. And he/she can then send the pre-populated email.

When you decided how you wanted to do it you can ask another (more specific) question on this site. (Or you can search for a solution somewhere on the internet.)

How to hide the border for specified rows of a table?

You can simply add these lines of codes here to hide a row,

Either you can write border:0 or border-style:hidden; border: none or it will happen the same thing

_x000D_
_x000D_
<style type="text/css">_x000D_
              table, th, td {_x000D_
               border: 1px solid;_x000D_
              }_x000D_
              _x000D_
              tr.hide_all > td, td.hide_all{_x000D_
                 border: 0;_x000D_
                _x000D_
              }_x000D_
          }_x000D_
        </style>_x000D_
    <table>_x000D_
      <tr>_x000D_
        <th>Firstname</th>_x000D_
        <th>Lastname</th>_x000D_
        <th>Savings</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Peter</td>_x000D_
        <td>Griffin</td>_x000D_
        <td>$100</td>_x000D_
      </tr>_x000D_
      <tr class= hide_all>_x000D_
        <td>Lois</td>_x000D_
        <td>Griffin</td>_x000D_
        <td>$150</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Joe</td>_x000D_
        <td>Swanson</td>_x000D_
        <td>$300</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Cleveland</td>_x000D_
        <td>Brown</td>_x000D_
        <td>$250</td>_x000D_
      </tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

running these lines of codes can solve the problem easily

MySQL: Delete all rows older than 10 minutes

The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"

Why can't I use a list as a dict key in python?

dict keys need to be hashable. Lists are Mutable and they do not provide a valid hash method.

Insert Data Into Tables Linked by Foreign Key

You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:

insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

If the customer does not exist, you'll get an sql exception which text will be something like:

null value in column "customer_id" violates not-null constraint

(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:

insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.

Compiling problems: cannot find crt1.o

This worked for me with Ubuntu 16.04

$ LIBRARY_PATH=/usr/lib/x86_64-linux-gnu
$ export LIBRARY_PATH

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

Probably you missing @SpringBootApplication in your spring boot starter class.

@SpringBootApplication
public class LoginSecurityAppApplication {

    public static void main(String[] args) {
        SpringApplication.run(LoginSecurityAppApplication.class, args);
    }

}

Clone() vs Copy constructor- which is recommended in java

Great sadness: neither Cloneable/clone nor a constructor are great solutions: I DON'T WANT TO KNOW THE IMPLEMENTING CLASS!!! (e.g. - I have a Map, which I want copied, using the same hidden MumbleMap implementation) I just want to make a copy, if doing so is supported. But, alas, Cloneable doesn't have the clone method on it, so there is nothing to which you can safely type-cast on which to invoke clone().

Whatever the best "copy object" library out there is, Oracle should make it a standard component of the next Java release (unless it already is, hidden somewhere).

Of course, if more of the library (e.g. - Collections) were immutable, this "copy" task would just go away. But then we would start designing Java programs with things like "class invariants" rather than the verdammt "bean" pattern (make a broken object and mutate until good [enough]).

Reliable method to get machine's MAC address in C#

IMHO returning first mac address isn't good idea, especially when virtual machines are hosted. Therefore i check send/received bytes sum and select most used connection, that is not perfect, but should be correct 9/10 times.

public string GetDefaultMacAddress()
{
    Dictionary<string, long> macAddresses = new Dictionary<string, long>();
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (nic.OperationalStatus == OperationalStatus.Up)
            macAddresses[nic.GetPhysicalAddress().ToString()] = nic.GetIPStatistics().BytesSent + nic.GetIPStatistics().BytesReceived;
    }
    long maxValue = 0;
    string mac = "";
    foreach(KeyValuePair<string, long> pair in macAddresses)
    {
        if (pair.Value > maxValue)
        {
            mac = pair.Key;
            maxValue = pair.Value;
        }
    }
    return mac;
}

.htaccess redirect http to https

Replace your domain with domainname.com , it's working with me .

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domainname\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domainname.com/$1 [R,L]

Convert LocalDateTime to LocalDateTime in UTC

There is an even simpler way

LocalDateTime.now(Clock.systemUTC())

Select row and element in awk

To print the second line:

awk 'FNR == 2 {print}'

To print the second field:

awk '{print $2}'

To print the third field of the fifth line:

awk 'FNR == 5 {print $3}'

Here's an example with a header line and (redundant) field descriptions:

awk 'BEGIN {print "Name\t\tAge"}  FNR == 5 {print "Name: "$3"\tAge: "$2}'

There are better ways to align columns than "\t\t" by the way.

Use exit to stop as soon as you've printed the desired record if there's no reason to process the whole file:

awk 'FNR == 2 {print; exit}'

Check if a given key already exists in a dictionary

in is the intended way to test for the existence of a key in a dict.

d = {"key1": 10, "key2": 23}

if "key1" in d:
    print("this will execute")

if "nonexistent key" in d:
    print("this will not")

If you wanted a default, you can always use dict.get():

d = dict()

for i in range(100):
    key = i % 10
    d[key] = d.get(key, 0) + 1

and if you wanted to always ensure a default value for any key you can either use dict.setdefault() repeatedly or defaultdict from the collections module, like so:

from collections import defaultdict

d = defaultdict(int)

for i in range(100):
    d[i % 10] += 1

but in general, the in keyword is the best way to do it.

How to get the url parameters using AngularJS

While routing is indeed a good solution for application-level URL parsing, you may want to use the more low-level $location service, as injected in your own service or controller:

var paramValue = $location.search().myParam; 

This simple syntax will work for http://example.com/path?myParam=paramValue. However, only if you configured the $locationProvider in the HTML 5 mode before:

$locationProvider.html5Mode(true);

Otherwise have a look at the http://example.com/#!/path?myParam=someValue "Hashbang" syntax which is a bit more complicated, but have the benefit of working on old browsers (non-HTML 5 compatible) as well.

Change default date time format on a single database in SQL Server

You can only change the language on the whole server, not individual databases. However if you need to support the UK you can run the following command before all inputs and outputs:

set language 'british english'

Or if you are having issues entering datatimes from your application you might want to consider a universal input type such as

1-Dec-2008

ReactJS: setTimeout() not working?

Try to use ES6 syntax of set timeout. Normal javascript setTimeout() won't work in react js

setTimeout(
      () => this.setState({ position: 100 }), 
      5000
    );

Call a function on click event in Angular 2

Exact transfer to Angular2+ is as below:

<button (click)="myFunc()"></button>

also in your component file:

import { Component, OnInit } from "@angular/core";

@Component({
  templateUrl:"button.html" //this is the component which has the above button html
})

export class App implements OnInit{
  constructor(){}

  ngOnInit(){

  }

  myFunc(){
    console.log("function called");
  }
}

ActivityCompat.requestPermissions not showing dialog box

I updated my target SDK version from 22 to 23 and it worked perfectly.

Doing a join across two databases with different collations on SQL Server and getting an error

You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)

select sone_field collate SQL_Latin1_General_CP850_CI_AI
  from table_1
    inner join table_2
      on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
  where whatever

How do I set the selected item in a comboBox to match my string using C#?

I used KeyValuePair for ComboBox data bind and I wanted to find item by value so this worked in my case:

comboBox.SelectedItem = comboBox.Items.Cast<KeyValuePair<string,string>>().First(item=> item.Value == "value to match");

How to get the background color of an HTML element?

Using JQuery:

var color = $('#myDivID').css("background-color");

Function to Calculate a CRC16 Checksum

for (pos = 0; pos < len; pos++) {
    crc ^= (uint16_t)buf[pos];     // XOR byte into least sig. byte of crc

    for (i = 8; i != 0; i--) {     // Loop over each bit
        if ((crc & 0x0001) != 0) { // If the LSB is set
            crc >>= 1;             // Shift right and XOR 0xA001
            crc ^= CRC16;
        } else {                   // Else LSB is not set
            crc >>= 1;             // Just shift right
        }
     }
}

return crc;

how to set the query timeout from SQL connection string

See:- ConnectionStrings content on this subject. There is no default command timeout property.

How to get list of all installed packages along with version in composer?

List installed dependencies:

  • Flat: composer show -i
  • Tree: composer show -i -t

-i short for --installed.

-t short for --tree.

ref: https://getcomposer.org/doc/03-cli.md#show

Split string into tokens and save them in an array

Why strtok() is a bad idea

Do not use strtok() in normal code, strtok() uses static variables which have some problems. There are some use cases on embedded microcontrollers where static variables make sense but avoid them in most other cases. strtok() behaves unexpected when more than 1 thread uses it, when it is used in a interrupt or when there are some other circumstances where more than one input is processed between successive calls to strtok(). Consider this example:

#include <stdio.h>
#include <string.h>

//Splits the input by the / character and prints the content in between
//the / character. The input string will be changed
void printContent(char *input)
{
    char *p = strtok(input, "/");
    while(p)
    {
        printf("%s, ",p);
        p = strtok(NULL, "/");
    }
}

int main(void)
{
    char buffer[] = "abc/def/ghi:ABC/DEF/GHI";
    char *p = strtok(buffer, ":");
    while(p)
    {
        printContent(p);
        puts(""); //print newline
        p = strtok(NULL, ":");
    }
    return 0;
}

You may expect the output:

abc, def, ghi,
ABC, DEF, GHI,

But you will get

abc, def, ghi,

This is because you call strtok() in printContent() resting the internal state of strtok() generated in main(). After returning, the content of strtok() is empty and the next call to strtok() returns NULL.

What you should do instead

You could use strtok_r() when you use a POSIX system, this versions does not need static variables. If your library does not provide strtok_r() you can write your own version of it. This should not be hard and Stackoverflow is not a coding service, you can write it on your own.

GLYPHICONS - bootstrap icon font hex value

Do you mean these hex values?

.glyphicon-asterisk:before{content:"\2a";}
.glyphicon-plus:before{content:"\2b";}
.glyphicon-euro:before{content:"\20ac";}
...

You can find these in glyphicons.css here:

http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css

(If you only want to know the Glyphicons classes: http://getbootstrap.com/components/#glyphicons)

setImmediate vs. nextTick

Some great answers here detailing how they both work.

Just adding one that answers the specific question asked:

When should I use nextTick and when should I use setImmediate?


Always use setImmediate.


The Node.js Event Loop, Timers, and process.nextTick() doc includes the following:

We recommend developers use setImmediate() in all cases because it's easier to reason about (and it leads to code that's compatible with a wider variety of environments, like browser JS.)


Earlier in the doc it warns that process.nextTick can lead to...

some bad situations because it allows you to "starve" your I/O by making recursive process.nextTick() calls, which prevents the event loop from reaching the poll phase.

As it turns out, process.nextTick can even starve Promises:

Promise.resolve().then(() => { console.log('this happens LAST'); });

process.nextTick(() => {
  console.log('all of these...');
  process.nextTick(() => {
    console.log('...happen before...');
    process.nextTick(() => {
      console.log('...the Promise ever...');
      process.nextTick(() => {
        console.log('...has a chance to resolve');
      })
    })
  })
})

On the other hand, setImmediate is "easier to reason about" and avoids these types of issues:

Promise.resolve().then(() => { console.log('this happens FIRST'); });

setImmediate(() => {
  console.log('this happens LAST');
})

So unless there is a specific need for the unique behavior of process.nextTick, the recommended approach is to "use setImmediate() in all cases".

How to generate List<String> from SQL query?

Or a nested List (okay, the OP was for a single column and this is for multiple columns..):

        //Base list is a list of fields, ie a data record
        //Enclosing list is then a list of those records, ie the Result set
        List<List<String>> ResultSet = new List<List<String>>();

        using (SqlConnection connection =
            new SqlConnection(connectionString))
        {
            // Create the Command and Parameter objects.
            SqlCommand command = new SqlCommand(qString, connection);

            // Create and execute the DataReader..
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                var rec = new List<string>();
                for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
                {                      
                    rec.Add(reader.GetString(i));
                }
                ResultSet.Add(rec);

            }
        }

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

CONSTRAINT vendor_tbfk_1 FOREIGN KEY (V_CODE) REFERENCES vendor (V_CODE) ON UPDATE CASCADE

this is how it could be... look at the referencing column part. (V_code)

How to integrate sourcetree for gitlab

This worked for me,

Step 1: Click on + New Repository> Clone from URL

Step 2: In Source URL provide URL followed by your user name,

Example:

  • GitLab Repo URL : http://git.zaid-labs.info/zaid/iosapp.git
  • GitLab User Name : zaid.pathan

So final URL should be http://[email protected]/zaid/iosapp.git

Note: zaid.pathan@ added before git.

Step 3: Enjoy cloning :).

How to get an object's property's value by property name?

$com1 = new-object PSobject                                                         #Task1
$com2 = new-object PSobject                                                         #Task1
$com3 = new-object PSobject                                                         #Task1



$com1 | add-member noteproperty -name user -value jindpal                           #Task2
$com1 | add-member noteproperty -name code -value IT01                              #Task2
$com1 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version}       #Task3


$com2 | add-member noteproperty -name user -value singh                             #Task2
$com2 | add-member noteproperty -name code -value IT02                              #Task2
$com2 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version}       #Task3


$com3 | add-member noteproperty -name user -value dhanoa                             #Task2
$com3 | add-member noteproperty -name code -value IT03                               #Task2
$com3 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version}        #Task3


$arr += $com1, $com2, $com3                                                          #Task4


write-host "windows version of computer1 is: "$com1.ver()                            #Task3
write-host "user name of computer1 is: "$com1.user                                   #Task6
write-host "code of computer1 is: "$com1,code                                        #Task5
write-host "windows version of computer2 is: "$com2.ver()                            #Task3
write-host "user name of computer2 is: "$com2.user                                   #Task6
write-host "windows version of computer3 is: "$com3.ver()                            #Task3
write-host "user name of computer3 is: "$com1.user                                   #Task6
write-host "code of computer3 is: "$com3,code                                        #Task5

read-host

list.clear() vs list = new ArrayList<Integer>();

The first one .clear(); will keep the same list just clear the list.

The second one new ArrayList<Integer>(); creates a new ArrayList in memory.

Suggestion: First one because that's what is is designed to do.

Case insensitive access for generic dictionary

For you LINQers out there that never use a regular dictionary constructor

myCollection.ToDictionary(x => x.PartNumber, x => x.PartDescription, StringComparer.OrdinalIgnoreCase)

How to use variables in SQL statement in Python?

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

Note that the parameters are passed as a tuple.

The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (%), because

  1. it does not do any escaping or quoting.
  2. it is prone to Uncontrolled string format attacks e.g. SQL injection.

How to run a cron job on every Monday, Wednesday and Friday?

Have you tried the following expression ..?

0 19 * * 1,3,5

How do I get a class instance of generic type T?

I wanted to pass T.class to a method which make use of Generics

The method readFile reads a .csv file specified by the fileName with fullpath. There can be csv files with different contents hence i need to pass the model file class so that i can get the appropriate objects. Since this is reading csv file i wanted to do in a generic way. For some reason or other none of the above solutions worked for me. I need to use Class<? extends T> type to make it work. I use opencsv library for parsing the CSV files.

private <T>List<T> readFile(String fileName, Class<? extends T> type) {

    List<T> dataList = new ArrayList<T>();
    try {
        File file = new File(fileName);

        Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        Reader headerReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

        CSVReader csvReader = new CSVReader(headerReader);
        // create csv bean reader
        CsvToBean<T> csvToBean = new CsvToBeanBuilder(reader)
                .withType(type)
                .withIgnoreLeadingWhiteSpace(true)
                .build();

        dataList = csvToBean.parse();
    }
    catch (Exception ex) {
        logger.error("Error: ", ex);
    }

    return dataList;
}

This is how the readFile method is called

List<RigSurfaceCSV> rigSurfaceCSVDataList = readSurfaceFile(surfaceFileName, RigSurfaceCSV.class);

How to do while loops with multiple conditions

Have you noticed that in the code you posted, condition2 is never set to False? This way, your loop body is never executed.

Also, note that in Python, not condition is preferred to condition == False; likewise, condition is preferred to condition == True.

Convert string to Color in C#

It depends on what you're looking for, if you need System.Windows.Media.Color (like in WPF) it's very easy:

System.Windows.Media.Color color = (Color)System.Windows.Media.ColorConverter.ConvertFromString("Red");//or hexadecimal color, e.g. #131A84

React.js: How to append a component on click?

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.

In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field

class HealthConditions extends React.Component {
  constructor(props) {
    super(props);


    this.state = {
      inputLinkClicked: false
    }
  }

  handleAddSecondInput() {
    this.setState({
      inputLinkClicked: true
    })
  }


  render() {
    return(
      <main id="wrapper" className="" data-reset-cookie-tab>
        <div id="content" role="main">
          <div className="inner-block">

            <H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>

            <InputField label="Name of condition"
              InputType="text"
              InputId="id-condition"
              InputName="condition"
            />

            {
              this.state.inputLinkClicked?

              <InputField label=""
                InputType="text"
                InputId="id-condition2"
                InputName="condition2"
              />

              :

              <div></div>
            }

            <button
              type="button"
              className="make-button-link"
              data-add-button=""
              href="#"
              onClick={this.handleAddSecondInput}
            >
              Add a condition
            </button>

            <FormButton buttonLabel="Next"
              handleSubmit={this.handleSubmit}
              linkto={
                this.state.illnessOrDisability === 'true' ?
                "/404"
                :
                "/add-your-details"
              }
            />

            <BackLink backLink="/add-your-details" />

          </div>
         </div>
      </main>
    );
  }
}

Share cookie between subdomain and domain

The 2 domains mydomain.com and subdomain.mydomain.com can only share cookies if the domain is explicitly named in the Set-Cookie header. Otherwise, the scope of the cookie is restricted to the request host. (This is referred to as a "host-only cookie". See What is a host only cookie?)

For instance, if you sent the following header from subdomain.mydomain.com, then the cookie won't be sent for requests to mydomain.com:

Set-Cookie: name=value

However if you use the following, it will be usable on both domains:

Set-Cookie: name=value; domain=mydomain.com

This cookie will be sent for any subdomain of mydomain.com, including nested subdomains like subsub.subdomain.mydomain.com.

In RFC 2109, a domain without a leading dot meant that it could not be used on subdomains, and only a leading dot (.mydomain.com) would allow it to be used across multiple subdomains (but not the top-level domain, so what you ask was not possible in the older spec).

However, all modern browsers respect the newer specification RFC 6265, and will ignore any leading dot, meaning you can use the cookie on subdomains as well as the top-level domain.

In summary, if you set a cookie like the second example above from mydomain.com, it would be accessible by subdomain.mydomain.com, and vice versa. This can also be used to allow sub1.mydomain.com and sub2.mydomain.com to share cookies.

See also:

TSQL select into Temp table from dynamic sql

A working example.

DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'YourTableName'

EXECUTE ('SELECT * INTO #TEMP  FROM ' + @TableName +'; SELECT * FROM #TEMP;')

Second solution with accessible temp table

DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'YOUR_TABLE_NAME'

EXECUTE ('CREATE VIEW vTemp AS
        SELECT *
        FROM ' + @TableName)
SELECT * INTO #TEMP  FROM vTemp 

--DROP THE VIEW HERE      
DROP VIEW vTemp

/*START USING TEMP TABLE
************************/
--EX:
SELECT * FROM #TEMP


--DROP YOUR TEMP TABLE HERE
DROP TABLE #TEMP

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

TableExport

TableExport - The simple, easy-to-implement library to export HTML tables to xlsx, xls, csv, and txt files.

To use this library, simple call the TableExport constructor:

new TableExport(document.getElementsByTagName("table"));

// OR simply

TableExport(document.getElementsByTagName("table"));

// OR using jQuery

$("table").tableExport(); 

Additional properties can be passed-in to customize the look and feel of your tables, buttons, and exported data. See here more info

How to access nested elements of json object using getJSONArray method

You can try this:

JSONObject result = new JSONObject("Your string here").getJSONObject("result");
JSONObject map = result.getJSONObject("map");
JSONArray entries= map.getJSONArray("entry");

I hope this helps.

Why do you use typedef when declaring an enum in C++?

Some people say C doesn't have namespaces but that is not technically correct. It has three:

  1. Tags (enum, union, and struct)
  2. Labels
  3. (everything else)

typedef enum { } XYZ; declares an anonymous enumeration and imports it into the global namespace with the name XYZ.

typedef enum ABC { } XYZ; declares an enum named ABC in the tag namespace, then imports it into the global namespace as XYZ.

Some people don't want to bother with the separate namespaces so they typedef everything. Others never typedef because they want the namespacing.

Jinja2 shorthand conditional

Alternative way (but it's not python style. It's JS style)

{{ files and 'Update' or 'Continue' }}

Change Schema Name Of Table In SQL

ALTER SCHEMA NewSchema TRANSFER [OldSchema].[TableName]

I always have to use the brackets when I use the ALTER SCHEMA query in SQL, or I get an error message.

Attach parameter to button.addTarget action in Swift

Swift 5.0 code

I use theButton.tag but if i have plenty type of option, its be very long switch case.

theButton.addTarget(self, action: #selector(theFunc), for: .touchUpInside) 
theButton.frame.name = "myParameter"

.

@objc func theFunc(sender:UIButton){ 
print(sender.frame.name)
}

Python Pandas : pivot table with aggfunc = count unique distinct

Since none of the answers are up to date with the last version of Pandas, I am writing another solution for this problem:

In [1]:
import pandas as pd

# Set exemple
df2 = pd.DataFrame({'X' : ['X1', 'X1', 'X1', 'X1'], 'Y' : ['Y2','Y1','Y1','Y1'], 'Z' : ['Z3','Z1','Z1','Z2']})

# Pivot
pd.crosstab(index=df2['Y'], columns=df2['Z'], values=df2['X'], aggfunc=pd.Series.nunique)

Out [1]:
Z   Z1  Z2  Z3
Y           
Y1  1.0 1.0 NaN
Y2  NaN NaN 1.0

Define css class in django Forms

Here is Simple way to alter in view. add below in view just before passing it into template.

form = MyForm(instance = instance.obj)
form.fields['email'].widget.attrs = {'class':'here_class_name'}

Difference between datetime and timestamp in sqlserver?

According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.


1 Assuming you use it properly, of course. See comments.

How to select data where a field has a min value in MySQL?

Efficient way (with any number of records):

SELECT id, name, MIN(price) FROM (select * from table order by price) as t group by id

jQuery AJAX single file upload

A. Grab file data from the file field

The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:

// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

This saves the file data to a file variable for later use.

B. Handle the file upload on submit

When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:

$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

// START A LOADING SPINNER HERE

// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
    data.append(key, value);
});

$.ajax({
    url: 'submit.php?files',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            submitForm(event, data);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
        // STOP LOADING SPINNER
    }
});
}

What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:

  • processData - Because jQuery will convert the files arrays into strings and the server can't pick it up.
  • contentType - Set this to false because jQuery defaults to application/x-www-form-urlencoded and doesn't send the files. Also setting it to multipart/form-data doesn't seem to work either.

C. Upload the files

Quick and dirty php script to upload the files and pass back some info:

<?php // You need to add server side validation and better error handling here

$data = array();

if(isset($_GET['files']))
{  
$error = false;
$files = array();

$uploaddir = './uploads/';
foreach($_FILES as $file)
{
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
    {
        $files[] = $uploaddir .$file['name'];
    }
    else
    {
        $error = true;
    }
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);

?>

IMP: Don't use this, write your own.

D. Handle the form submit

The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:

function submitForm(event, data)
{
  // Create a jQuery object from the form
$form = $(event.target);

// Serialize the form data
var formData = $form.serialize();

// You should sterilise the file names
$.each(data.files, function(key, value)
{
    formData = formData + '&filenames[]=' + value;
});

$.ajax({
    url: 'submit.php',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: 'json',
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
    },
    complete: function()
    {
        // STOP LOADING SPINNER
    }
});
}

Final note

This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Github if you want to see it working.

Referenced From

How do I find what Java version Tomcat6 is using?

/usr/local/tomcat6/bin/catalina.sh version