Programs & Examples On #Hudson plugin batch task

How can I open a link in a new window?

Microsoft IE does not support a name as second argument.

window.open('url', 'window name', 'window settings');

Problem is window name. This will work:

window.open('url', '', 'window settings')

Microsoft only allows the following arguments, If using that argument at all:

  • _blank
  • _media
  • _parent
  • _search
  • _self
  • _top

Check this Microsoft site

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

    import urllib2

Traceback (most recent call last):

File "", line 1, in

    import urllib2

ImportError: No module named 'urllib2' So urllib2 has been been replaced by the package : urllib.request.

Here is the PEP link (Python Enhancement Proposals )

http://www.python.org/dev/peps/pep-3108/#urllib-package

so instead of urllib2 you can now import urllib.request and then use it like this:

    >>>import urllib.request

    >>>urllib.request.urlopen('http://www.placementyogi.com')

Original Link : http://placementyogi.com/articles/python/importerror-no-module-named-urllib2-in-python-3-x

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

"SDK Platform Tools component is missing!"

I don't understand why the files were relocated to /platform-tools from /tools. It seems ALL development tools I have tried, appcelerator for one, have their setup software look for these files in /tools and fail setup. The "work around" involves a few different bits of trickery wherein you either...1) set up a soft link to tell the operating system "if you look for file "x" here it is really over here. or 2) simpler method ... make a copy of all the /platform-tools default (pre-additional android sdk installations) files and place them into the /tools folder. this circumvents the relocation that the newer sdk have done. Then of course YOU MUST SET PATH ENVIRONMENT VARIABLES TO POINT TO THE SDK LOCATION (sometimes to the Android-sdk-[operating system name:Android-sdk-windows or Android-sdk-mac_x86 ect. ] and to the /platform-tools and sometimes to /tools. it is a trial and error pain. But when it finally is working ...it works.

How do I put an already-running process under nohup?

Simple and easiest steps

  1. Ctrl + Z ----------> Suspends the process
  2. bg --------------> Resumes and runs background
  3. disown %1 -------------> required only if you need to detach from the terminal

What's the difference between “mod” and “remainder”?

sign of remainder will be same as the divisible and the sign of modulus will be same as divisor.

Remainder is simply the remaining part after the arithmetic division between two integer number whereas Modulus is the sum of remainder and divisor when they are oppositely signed and remaining part after the arithmetic division when remainder and divisor both are of same sign.

Example of Remainder:

10 % 3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]

-10 % 3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]

10 % -3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]

-10 % -3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]

Example of Modulus:

5 % 3 = 2 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is also positively signed. As both remainder and divisor are of same sign the result will be same as remainder]

-5 % 3 = 1 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is positively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor -2 + 3 = 1]

5 % -3 = -1 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is negatively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor 2 + -3 = -1]

-5 % -3 = -2 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is also negatively signed. As both remainder and divisor are of same sign the result will be same as remainder]

I hope this will clearly distinguish between remainder and modulus.

remove empty lines from text file with PowerShell

You can't do replacing, you have to replace SOMETHING with SOMETHING, and you neither have both.

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

In .Net 1.1 and earlier, Application.Exit was not a wise choice and the MSDN docs specifically recommended against it because all message processing stopped immediately.

In later versions however, calling Application.Exit will result in Form.Close being called on all open forms in the application, thus giving you a chance to clean up after yourself, or even cancel the operation all together.

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

It is indeed a foreign key error, you can find out using perror:

shell$ perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed

To find out more details about what failed, you can use SHOW ENGINE INNODB STATUS and look for the LATEST FOREIGN KEY ERROR section it contains details about what is wrong.

In your case, it is most likely cause something is referencing the country_id column.

Change status bar text color to light in iOS 9 with Objective-C

Add the key View controller-based status bar appearance to Info.plist file and make it boolean type set to NO.

Insert one line code in viewDidLoad (this works on specific class where it is mentioned)

 [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;

Should I use encodeURI or encodeURIComponent for encoding URLs?

encodeURIComponent() : assumes that its argument is a portion (such as the protocol, hostname, path, or query string) of a URI. Therefore it escapes the punctuation characters that are used to separate the portionsof a URI.

encodeURI(): is used for encoding existing url

Typescript: difference between String and string

The two types are distinct in JavaScript as well as TypeScript - TypeScript just gives us syntax to annotate and check types as we go along.

String refers to an object instance that has String.prototype in its prototype chain. You can get such an instance in various ways e.g. new String('foo') and Object('foo'). You can test for an instance of the String type with the instanceof operator, e.g. myString instanceof String.

string is one of JavaScript's primitive types, and string values are primarily created with literals e.g. 'foo' and "bar", and as the result type of various functions and operators. You can test for string type using typeof myString === 'string'.

The vast majority of the time, string is the type you should be using - almost all API interfaces that take or return strings will use it. All JS primitive types will be wrapped (boxed) with their corresponding object types when using them as objects, e.g. accessing properties or calling methods. Since String is currently declared as an interface rather than a class in TypeScript's core library, structural typing means that string is considered a subtype of String which is why your first line passes compilation type checks.

Call break in nested if statements

To make multiple checking statements more readable (and avoid nested ifs):

var tmp = 'Test[[email protected]]';

var posStartEmail = undefined;
var posEndEmail = undefined;
var email = undefined;

do {
    if (tmp.toLowerCase().substring(0,4) !== 'test') { break; }

    posStartEmail = tmp.toLowerCase().substring(4).indexOf('[');
    posEndEmail = tmp.toLowerCase().substring(4).indexOf(']');

    if (posStartEmail === -1 || posEndEmail === -1) { break; }

    email = tmp.substring(posStartEmail+1+4,posEndEmail);

    if (email.indexOf('@') === -1) { break; }

// all checks are done - do what you intend to do

    alert ('All checks are ok')

    break; // the most important break of them all

} while(true);

Convert RGBA PNG to RGB with PIL

Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building RGBA -> JPG + BG support for sorl thumbnails.

from PIL import Image

png = Image.open(object.logo.path)
png.load() # required for png.split()

background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel

background.save('foo.jpg', 'JPEG', quality=80)

Result @80%

enter image description here

Result @ 50%
enter image description here

Programmatically generate video or animated GIF in Python?

It's really incredible ... All are proposing some special package for playing an animated GIF, at the moment that it can be done with Tkinter and the classic PIL module!

Here is my own GIF animation method (I created a while ago). Very simple:

from Tkinter import * 
from PIL import Image, ImageTk
from time import sleep

def stop(event):
  global play
  play = False
  exit() 

root = Tk()
root.bind("<Key>", stop) # Press any key to stop
GIFfile = {path_to_your_GIF_file}    
im = Image.open(GIFfile); img = ImageTk.PhotoImage(im)
delay = float(im.info['duration'])/1000; # Delay used in the GIF file 
lbl = Label(image=img); lbl.pack() # Create a label where to display images
play = True; frame = 0
while play:
  sleep(delay);
  frame += 1
  try:
    im.seek(frame); img = ImageTk.PhotoImage(im)
    lbl.config(image=img); root.update() # Show the new frame/image
  except EOFError:
    frame = 0 # Restart

root.mainloop()

You can set your own means to stop the animation. Let me know if you like to get the full version with play/pause/quit buttons.

Note: I am not sure if the consecutive frames are read from memory or from the file (disk). In the second case it would be more efficient if they all read at once and saved into an array (list). (I'm not so interested to find out! :)

Openssl : error "self signed certificate in certificate chain"

If you're running Charles and trying to build a container then you'll most likely get this error.

Make sure to disable Charles (macos) proxy under proxy -> macOS proxy

Charles is an

HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet.

So anything similar may cause the same issue.

How can I use jQuery to make an input readonly?

These days with jQuery 1.6.1 or above it is recommended that .prop() be used when setting boolean attributes/properties.

$("#fieldName").prop("readonly", true);

"Unmappable character for encoding UTF-8" error

The compiler is using the UTF-8 character encoding to read your source file. But the file must have been written by an editor using a different encoding. Open your file in an editor set to the UTF-8 encoding, fix the quote mark, and save it again.

Alternatively, you can find the Unicode point for the character and use a Unicode escape in the source code. For example, the character A can be replaced with the Unicode escape \u0041.

By the way, you don't need to use the begin- and end-line anchors ^ and $ when using the matches() method. The entire sequence must be matched by the regular expression when using the matches() method. The anchors are only useful with the find() method.

How do I get the difference between two Dates in JavaScript?

<html>
<head>
<script>
function dayDiff()
{
     var start = document.getElementById("datepicker").value;
     var end= document.getElementById("date_picker").value;
     var oneDay = 24*60*60*1000; 
     var firstDate = new Date(start);
     var secondDate = new Date(end);    
     var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
    document.getElementById("leave").value =diffDays ;
 }
</script>
</head>
<body>
<input type="text" name="datepicker"value=""/>
<input type="text" name="date_picker" onclick="function dayDiff()" value=""/>
<input type="text" name="leave" value=""/>
</body>
</html>

.jar error - could not find or load main class

You can always run this:

java -cp HelloWorld.jar HelloWorld

-cp HelloWorld.jar adds the jar to the classpath, then HelloWorld runs the class you wrote.

To create a runnable jar with a main class with no package, add Class-Path: . to the manifest:

Manifest-Version: 1.0
Class-Path: .
Main-Class: HelloWorld

I would advise using a package to give your class its own namespace. E.g.

package com.stackoverflow.user.blrp;

public class HelloWorld {
    ...
}

Get selected key/value of a combo box using jQuery

<select name="foo" id="foo">
 <option value="1">a</option>
 <option value="2">b</option>
 <option value="3">c</option>
  </select>
  <input type="button" id="button" value="Button" />
  });
  <script> ("#foo").val() </script>

which returns 1 if you have selected a and so on..

Kill process by name?

import psutil
pid_list=psutil.get_pid_list()
print pid_list
p = psutil.Process(1052)
print p.name
for i in pid_list:
    p = psutil.Process(i)
    p_name=p.name
    print str(i)+" "+str(p.name)
    if p_name=="PerfExp.exe":
        print "*"*20+" mam ho "+"*"*20
        p.kill()

Is System.nanoTime() completely useless?

Java is crossplatform, and nanoTime is platform-dependent. If you use Java - when don't use nanoTime. I found real bugs across different jvm implementations with this function.

Update statement using with clause

You can always do something like this:

update  mytable t
set     SomeColumn = c.ComputedValue
from    (select *, 42 as ComputedValue from mytable where id = 1) c
where t.id = c.id 

You can now also use with statement inside update

update  mytable t
set     SomeColumn = c.ComputedValue
from    (with abc as (select *, 43 as ComputedValue_new from mytable where id = 1
         select *, 42 as ComputedValue, abc.ComputedValue_new  from mytable n1
           inner join abc on n1.id=abc.id) c
where t.id = c.id 

Proxies with Python 'Requests' module

I share some code how to fetch proxies from the site "https://free-proxy-list.net" and store data to a file compatible with tools like "Elite Proxy Switcher"(format IP:PORT):

##PROXY_UPDATER - get free proxies from https://free-proxy-list.net/

from lxml.html import fromstring
import requests
from itertools import cycle
import traceback
import re

######################FIND PROXIES#########################################
def get_proxies():
    url = 'https://free-proxy-list.net/'
    response = requests.get(url)
    parser = fromstring(response.text)
    proxies = set()
    for i in parser.xpath('//tbody/tr')[:299]:   #299 proxies max
        proxy = ":".join([i.xpath('.//td[1]/text()') 
        [0],i.xpath('.//td[2]/text()')[0]])
        proxies.add(proxy)
    return proxies



######################write to file in format   IP:PORT######################
try:
    proxies = get_proxies()
    f=open('proxy_list.txt','w')
    for proxy in proxies:
        f.write(proxy+'\n')
    f.close()
    print ("DONE")
except:
    print ("MAJOR ERROR")

Generate a random number in the range 1 - 10

(trunc(random() * 10) % 10) + 1

C# SQL Server - Passing a list to a stored procedure

If you prefer splitting a CSV list in SQL, there's a different way to do it using Common Table Expressions (CTEs). See Efficient way to string split using CTE.

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

Matlab is good at doing number crunching. Also Matrix and matrix manipulation. It has many helpful built in libraries(depends on the what version) I think it is easier to use than python if you are going to be calculating equations.

Java - Writing strings to a CSV file

 private static final String FILE_HEADER ="meter_Number,latestDate";
    private static final String COMMA_DELIMITER = ",";
    private static final String NEW_LINE_SEPARATOR = "\n";
    static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:m m:ss");

    private void writeToCsv(Map<String, Date> meterMap) {
        try {
            Iterator<Map.Entry<String, Date>> iter = meterMap.entrySet().iterator();
            FileWriter fw = new FileWriter("smaple.csv");
            fw.append(FILE_HEADER.toString());
            fw.append(NEW_LINE_SEPARATOR);
            while (iter.hasNext()) {
                Map.Entry<String, Date> entry = iter.next();
                try {
                    fw.append(entry.getKey());
                    fw.append(COMMA_DELIMITER);
                    fw.append(formatter.format(entry.getValue()));
                    fw.append(NEW_LINE_SEPARATOR);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    iter.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

How do I kill background processes / jobs when my shell script exits?

jobs -p does not work in all shells if called in a sub-shell, possibly unless its output is redirected into a file but not a pipe. (I assume it was originally intended for interactive use only.)

What about the following:

trap 'while kill %% 2>/dev/null; do jobs > /dev/null; done' INT TERM EXIT [...]

The call to "jobs" is needed with Debian's dash shell, which fails to update the current job ("%%") if it is missing.

sh: 0: getcwd() failed: No such file or directory on cited drive

In Ubuntu 16.04.3 LTS, the next command works for me:

exit

Then I've login again.

Binding Combobox Using Dictionary as the Datasource

If this doesn't work why not simply do a foreach loop over the dictionary adding all the items to the combobox?

foreach(var item in userCache)
{
    userListComboBox.Items.Add(new ListItem(item.Key, item.Value));
}

Import CSV file with mixed data types

In R2013b or later you can use a table:

>> table = readtable('myfile.txt','Delimiter',';','ReadVariableNames',false)
>> table = 

    Var1    Var2     Var3     Var4     Var5        Var6          Var7         Var8      Var9    Var10
    ____    _____    _____    _____    _____    __________    __________    ________    ____    _____

      4     'abc'    'def'    'ghj'    'klm'    ''            ''            ''          NaN     NaN  
    NaN     ''       ''       ''       ''       'Test'        'text'        '0xFF'      NaN     NaN  
    NaN     ''       ''       ''       ''       'asdfhsdf'    'dsafdsag'    '0x0F0F'    NaN     NaN  

Here is more info.

Global Variable in app.js accessible in routes?

As others have already shared, app.set('config', config) is great for this. I just wanted to add something that I didn't see in existing answers that is quite important. A Node.js instance is shared across all requests, so while it may be very practical to share some config or router object globally, storing runtime data globally will be available across requests and users. Consider this very simple example:

var express = require('express');
var app = express();

app.get('/foo', function(req, res) {
    app.set('message', "Welcome to foo!");
    res.send(app.get('message'));
});

app.get('/bar', function(req, res) {
    app.set('message', "Welcome to bar!");

    // some long running async function
    var foo = function() {
        res.send(app.get('message'));
    };
    setTimeout(foo, 1000);
});

app.listen(3000);

If you visit /bar and another request hits /foo, your message will be "Welcome to foo!". This is a silly example, but it gets the point across.

There are some interesting points about this at Why do different node.js sessions share variables?.

Integrating the ZXing library directly into my Android application

Much Easier approach.

Just include dependency in your app level gradle file

compile 'com.journeyapps:zxing-android-embedded:3.0.1@aar'
compile 'com.google.zxing:core:3.2.0'  

Define one button in your xml file and and write below code in Java file in OnCreate()and inside the OnClick listener of button

new IntentIntegrator(this).initiateScan();

And write below code after OnCreate() of the Java file

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if(result != null) {
        if(result.getContents() == null) {
            Log.d("MainActivity", "Cancelled scan");
            Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
        } else {
            Log.d("MainActivity", "Scanned");
            String st_scanned_result = result.getContents();
            Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();

        }
    }

}

Imshow: extent and aspect

You can do it by setting the aspect of the image manually (or by letting it auto-scale to fill up the extent of the figure).

By default, imshow sets the aspect of the plot to 1, as this is often what people want for image data.

In your case, you can do something like:

import matplotlib.pyplot as plt
import numpy as np

grid = np.random.random((10,10))

fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))

ax1.imshow(grid, extent=[0,100,0,1])
ax1.set_title('Default')

ax2.imshow(grid, extent=[0,100,0,1], aspect='auto')
ax2.set_title('Auto-scaled Aspect')

ax3.imshow(grid, extent=[0,100,0,1], aspect=100)
ax3.set_title('Manually Set Aspect')

plt.tight_layout()
plt.show()

enter image description here

Xcode - ld: library not found for -lPods

This problem-related to lPods can be fixed by following the steps below

  • Select your Project Target.
  • Go to "Build Phases" in "Link Binary With Libraries".
  • Now remove ".a" file of that library which is creating the problem.
  • Clean and Build.

This will work.

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

How to clear radio button in Javascript?

This should work. Make sure each button has a unique ID. (Replace Choose_Yes and Choose_No with the IDs of your two radio buttons)

document.getElementById("Choose_Yes").checked = false;
document.getElementById("Choose_No").checked = false;

An example of how the radio buttons should be named:

<input type="radio" name="Choose" id="Choose_Yes" value="1" /> Yes
<input type="radio" name="Choose" id="Choose_No" value="2" /> No

curl POST format for CURLOPT_POSTFIELDS

One other major difference that is not yet mentioned here is that CURLOPT_POSTFIELDS can't handle nested arrays.

If we take the nested array ['a' => 1, 'b' => [2, 3, 4]] then this should be be parameterized as a=1&b[]=2&b[]=3&b[]=4 (the [ and ] will be/should be URL encoded). This will be converted back automatically into a nested array on the other end (assuming here the other end is also PHP).

This will work:

var_dump(http_build_query(['a' => 1, 'b' => [2, 3, 4]]));
// output: string(36) "a=1&b%5B0%5D=2&b%5B1%5D=3&b%5B2%5D=4"

This won't work:

curl_setopt($ch, CURLOPT_POSTFIELDS, ['a' => 1, 'b' => [2, 3, 4]]);

This will give you a notice. Code execution will continue and your endpoint will receive parameter b as string "Array":

PHP Notice: Array to string conversion in ... on line ...

Show a child form in the centre of Parent form in C#

If you want to calculate your own location, then first set StartPosition to FormStartPosition.Manual:

Form Child = new Form();
Child.StartPosition = FormStartPosition.Manual;
Child.Location = new Point(Location.X + (Width - Child.Width) / 2, Location.Y + (Height - Child.Height) / 2);
Child.Show(this);

Where this is the main/parent form, just like Location.X.

Default value for StartPosition is FormStartPosition.CenterParent and therefore it changes the child's location after showing.

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

Compiling PIL on Windows x64 is apparently a bit of a pain. (Well, compiling anything on Windows is a bit of a pain in my experience. But still.) As well as PIL itself you'll need to build many dependencies. See these notes from the mailing list too.

There's an unofficial precompiled binary for x64 linked from this message, but I haven't tried it myself. Might be worth a go if you don't mind the download being from one of those slightly dodgy file-upload sites. Other than that... well, you could always give up and instead the 32-bit Python binary instead.

Scrolling to element using webdriver?

It's not a direct answer on question (its not about Actions), but it also allow you to scroll easily to required element:

element = driver.find_element_by_id('some_id')
element.location_once_scrolled_into_view

This actually intend to return you coordinates (x, y) of element on page, but also scroll down right to target element

"Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010

While the project was in debug mode, the solution was not. When I changed it, it worked.

eloquent laravel: How to get a row count from a ->get()

Direct get a count of row

Using Eloquent

 //Useing Eloquent
 $count = Model::count();    

 //example            
 $count1 = Wordlist::count();

Using query builder

 //Using query builder
 $count = \DB::table('table_name')->count();

 //example
 $count2 = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count();

How do I use the built in password reset/change views with my own templates

If you take a look at the sources for django.contrib.auth.views.password_reset you'll see that it uses RequestContext. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.

The b-list has a good introduction to context processors.

Edit (I seem to have been confused about what the actual question was):

You'll notice that password_reset takes a named parameter called template_name:

def password_reset(request, is_admin_site=False, 
            template_name='registration/password_reset_form.html',
            email_template_name='registration/password_reset_email.html',
            password_reset_form=PasswordResetForm, 
            token_generator=default_token_generator,
            post_reset_redirect=None):

Check password_reset for more information.

... thus, with a urls.py like:

from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset

urlpatterns = patterns('',
     (r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
     ...
)

django.contrib.auth.views.password_reset will be called for URLs matching '/accounts/password/reset' with the keyword argument template_name = 'my_templates/password_reset.html'.

Otherwise, you don't need to provide any context as the password_reset view takes care of itself. If you want to see what context you have available, you can trigger a TemplateSyntax error and look through the stack trace find the frame with a local variable named context. If you want to modify the context then what I said above about context processors is probably the way to go.

In summary: what do you need to do to use your own template? Provide a template_name keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.

Default password of mysql in ubuntu server 16.04

I think another place to look is /var/lib. If you go there you can see three mysql folders with 'interesting' permissions:

user   group 
mysql  mysql

Here is what I did to solve my problem with root password:

after running

sudo apt-get purge mysql*
sudo rm -rf /etc/mysql

I also ran the following (instead of my_username put yours):

cd /var/lib
sudo chown --from=mysql <my_username> mysql* -R
sudo rm -rf mysql*

And then:

sudo apt-get install mysql-server

which prompted me to select a new root password. I hope it helps

Ruby: How to convert a string to boolean

h = { "true"=>true, true=>true, "false"=>false, false=>false }

["true", true, "false", false].map { |e| h[e] }
  #=> [true, true, false, false] 

Simple way to copy or clone a DataRow?

But to make sure that your new row is accessible in the new table, you need to close the table:

DataTable destination = new DataTable(source.TableName);
destination = source.Clone();
DataRow sourceRow = source.Rows[0];
destination.ImportRow(sourceRow);

How to get time (hour, minute, second) in Swift 3 using NSDate?

Swift 4

    let calendar = Calendar.current
    let time=calendar.dateComponents([.hour,.minute,.second], from: Date())
    print("\(time.hour!):\(time.minute!):\(time.second!)")

Python DNS module import error

I installed DNSpython 2.0.0 from the github source, but running 'pip list' showed the old version of dnspython 1.2.0

It only worked after I ran 'pip uninstall dnspython' which removed the old version leaving just 2.0.0 and then 'import dns' ran smoothly

How to add Tomcat Server in eclipse

Do as this:

Windows -> Show View -> Servers

Then in the Servers view, right-click and add new. It will show a pop up containing many server vendors. Under Apache select Tomcat v7.0 (Depending upon your downloaded server version). And in the run time configuration point it to the Tomcat folder you have downloaded.

You can try this article. It has the info you want !!

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

(CI 3) For me, what worked was changing:

'hostname' => 'localhost' to 'hostname' => '127.0.0.1'

How to slice an array in Bash

Array slicing like in Python (From the rebash library):

array_slice() {
    local __doc__='
    Returns a slice of an array (similar to Python).

    From the Python documentation:
    One way to remember how slices work is to think of the indices as pointing
    between elements, with the left edge of the first character numbered 0.
    Then the right edge of the last element of an array of length n has
    index n, for example:
    ```
    +---+---+---+---+---+---+
    | 0 | 1 | 2 | 3 | 4 | 5 |
    +---+---+---+---+---+---+
    0   1   2   3   4   5   6
    -6  -5  -4  -3  -2  -1
    ```

    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 1:-2 "${a[@]}")
    1 2 3
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 0:1 "${a[@]}")
    0
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice 1:1 "${a[@]}")" ] && echo empty
    empty
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice 2:1 "${a[@]}")" ] && echo empty
    empty
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice -2:-3 "${a[@]}")" ] && echo empty
    empty
    >>> [ -z "$(array.slice -2:-2 "${a[@]}")" ] && echo empty
    empty

    Slice indices have useful defaults; an omitted first index defaults to
    zero, an omitted second index defaults to the size of the string being
    sliced.
    >>> local a=(0 1 2 3 4 5)
    >>> # from the beginning to position 2 (excluded)
    >>> echo $(array.slice 0:2 "${a[@]}")
    >>> echo $(array.slice :2 "${a[@]}")
    0 1
    0 1

    >>> local a=(0 1 2 3 4 5)
    >>> # from position 3 (included) to the end
    >>> echo $(array.slice 3:"${#a[@]}" "${a[@]}")
    >>> echo $(array.slice 3: "${a[@]}")
    3 4 5
    3 4 5

    >>> local a=(0 1 2 3 4 5)
    >>> # from the second-last (included) to the end
    >>> echo $(array.slice -2:"${#a[@]}" "${a[@]}")
    >>> echo $(array.slice -2: "${a[@]}")
    4 5
    4 5

    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -4:-2 "${a[@]}")
    2 3

    If no range is given, it works like normal array indices.
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -1 "${a[@]}")
    5
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -2 "${a[@]}")
    4
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 0 "${a[@]}")
    0
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 1 "${a[@]}")
    1
    >>> local a=(0 1 2 3 4 5)
    >>> array.slice 6 "${a[@]}"; echo $?
    1
    >>> local a=(0 1 2 3 4 5)
    >>> array.slice -7 "${a[@]}"; echo $?
    1
    '
    local start end array_length length
    if [[ $1 == *:* ]]; then
        IFS=":"; read -r start end <<<"$1"
        shift
        array_length="$#"
        # defaults
        [ -z "$end" ] && end=$array_length
        [ -z "$start" ] && start=0
        (( start < 0 )) && let "start=(( array_length + start ))"
        (( end < 0 )) && let "end=(( array_length + end ))"
    else
        start="$1"
        shift
        array_length="$#"
        (( start < 0 )) && let "start=(( array_length + start ))"
        let "end=(( start + 1 ))"
    fi
    let "length=(( end - start ))"
    (( start < 0 )) && return 1
    # check bounds
    (( length < 0 )) && return 1
    (( start < 0 )) && return 1
    (( start >= array_length )) && return 1
    # parameters start with $1, so add 1 to $start
    let "start=(( start + 1 ))"
    echo "${@: $start:$length}"
}
alias array.slice="array_slice"

How to Calculate Execution Time of a Code Snippet in C++

#include <omp.h>

double start = omp_get_wtime();

// code 

double finish = omp_get_wtime();

double total_time = finish - start;

What happens to C# Dictionary<int, int> lookup if the key does not exist?

If you're just checking before trying to add a new value, use the ContainsKey method:

if (!openWith.ContainsKey("ht"))
{
    openWith.Add("ht", "hypertrm.exe");
}

If you're checking that the value exists, use the TryGetValue method as described in Jon Skeet's answer.

How to find tag with particular text with Beautiful Soup?

Since Beautiful Soup 4.4.0. a parameter called string does the work that text used to do in the previous versions.

string is for finding strings, you can combine it with arguments that find tags: Beautiful Soup will find all tags whose .string matches your value for the string. This code finds the tags whose .string is “Elsie”:

soup.find_all("td", string="Elsie")

For more information about string have a look this section https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-string-argument

Get top n records for each group of grouped results

Try this:

SELECT a.person, a.group, a.age FROM person AS a WHERE 
(SELECT COUNT(*) FROM person AS b 
WHERE b.group = a.group AND b.age >= a.age) <= 2 
ORDER BY a.group ASC, a.age DESC

DEMO

Apply CSS Style to child elements

div.test td, div.test caption, div.test th 

works for me.

The child selector > does not work in IE6.

Convert SVG to image (JPEG, PNG, etc.) in the browser

The solution to convert SVG to blob URL and blob URL to png image

_x000D_
_x000D_
const svg=`<svg version="1.1" baseProfile="full" width="300" height="200"_x000D_
xmlns="http://www.w3.org/2000/svg">_x000D_
   <rect width="100%" height="100%" fill="red" />_x000D_
   <circle cx="150" cy="100" r="80" fill="green" />_x000D_
   <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text></svg>`_x000D_
svgToPng(svg,(imgData)=>{_x000D_
    const pngImage = document.createElement('img');_x000D_
    document.body.appendChild(pngImage);_x000D_
    pngImage.src=imgData;_x000D_
});_x000D_
 function svgToPng(svg, callback) {_x000D_
    const url = getSvgUrl(svg);_x000D_
    svgUrlToPng(url, (imgData) => {_x000D_
        callback(imgData);_x000D_
        URL.revokeObjectURL(url);_x000D_
    });_x000D_
}_x000D_
function getSvgUrl(svg) {_x000D_
    return  URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));_x000D_
}_x000D_
function svgUrlToPng(svgUrl, callback) {_x000D_
    const svgImage = document.createElement('img');_x000D_
    // imgPreview.style.position = 'absolute';_x000D_
    // imgPreview.style.top = '-9999px';_x000D_
    document.body.appendChild(svgImage);_x000D_
    svgImage.onload = function () {_x000D_
        const canvas = document.createElement('canvas');_x000D_
        canvas.width = svgImage.clientWidth;_x000D_
        canvas.height = svgImage.clientHeight;_x000D_
        const canvasCtx = canvas.getContext('2d');_x000D_
        canvasCtx.drawImage(svgImage, 0, 0);_x000D_
        const imgData = canvas.toDataURL('image/png');_x000D_
        callback(imgData);_x000D_
        // document.body.removeChild(imgPreview);_x000D_
    };_x000D_
    svgImage.src = svgUrl;_x000D_
 }
_x000D_
_x000D_
_x000D_

Local file access with JavaScript

UPDATE This feature is removed since Firefox 17 (see https://bugzilla.mozilla.org/show_bug.cgi?id=546848).


On Firefox you (the programmer) can do this from within a JavaScript file:

netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");

and you (the browser user) will be prompted to allow access. (for Firefox you just need to do this once every time the browser is started)

If the browser user is someone else, they have to grant permission.

What are the differences between B trees and B+ trees?

Define "much faster". Asymptotically they're about the same. The differences lie in how they make use of secondary storage. The Wikipedia articles on B-trees and B+trees look pretty trustworthy.

How can I write text on a HTML5 canvas element?

I found a good tutorial on oreilly.com.

Example code:

<canvas id="canvas" width ='600px'></canvas><br />
Enter your Text here .The Text will get drawn on the canvas<br />
<input type="text" id="text" onKeydown="func();"></input><br />
</body><br />
<script>
function func(){
var e=document.getElementById("text"),t=document.getElementById("canvas"),n=t.getContext("2d");
n.fillStyle="#990000";n.font="30px futura";n.textBaseline="top";n.fillText(e.value,150,0);n.fillText("thank you, ",200,100);
n.fillText("Created by ashish",250,120)
}
</script>

courtesy: @Ashish Nautiyal

Pagination response payload from a RESTful API

just add in your backend API new property's into response body. from example .net core:

[Authorize]
[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
{
  var users = await _repo.GetUsers(userParams);
  var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);


  // create new object and add into it total count param etc
  var UsersListResult = new
  {
    usersToReturn,
    currentPage = users.CurrentPage,
    pageSize = users.PageSize,
    totalCount = users.TotalCount,
    totalPages = users.TotalPages
  };

  return Ok(UsersListResult);
}

In body response it look like this

{
"usersToReturn": [
    {
        "userId": 1,
        "username": "[email protected]",
        "firstName": "Joann",
        "lastName": "Wilson",
        "city": "Armstrong",
        "phoneNumber": "+1 (893) 515-2172"
    },
    {
        "userId": 2,
        "username": "[email protected]",
        "firstName": "Booth",
        "lastName": "Drake",
        "city": "Franks",
        "phoneNumber": "+1 (800) 493-2168"
    }
],
// metadata to pars in client side
"currentPage": 1,
"pageSize": 2,
"totalCount": 87,
"totalPages": 44

}

What is the difference between "screen" and "only screen" in media queries?

The following is from Adobe docs.


The media queries specification also provides the keyword only, which is intended to hide media queries from older browsers. Like not, the keyword must come at the beginning of the declaration. For example:

media="only screen and (min-width: 401px) and (max-width: 600px)"

Browsers that don't recognize media queries expect a comma-separated list of media types, and the specification says they should truncate each value immediately before the first nonalphanumeric character that isn't a hyphen. So, an old browser should interpret the preceding example as this:

media="only"

Because there is no such media type as only, the stylesheet is ignored. Similarly, an old browser should interpret

media="screen and (min-width: 401px) and (max-width: 600px)"

as

media="screen"

In other words, it should apply the style rules to all screen devices, even though it doesn't know what the media queries mean.

Unfortunately, IE 6–8 failed to implement the specification correctly.

Instead of applying the styles to all screen devices, it ignores the style sheet altogether.

In spite of this behavior, it's still recommended to prefix media queries with only if you want to hide the styles from other, less common browsers.


So, using

media="only screen and (min-width: 401px)"

and

media="screen and (min-width: 401px)"

will have the same effect in IE6-8: both will prevent those styles from being used. They will, however, still be downloaded.

Also, in browsers that support CSS3 media queries, both versions will load the styles if the viewport width is larger than 401px and the media type is screen.

I'm not entirely sure which browsers that don't support CSS3 media queries would need the only version

media="only screen and (min-width: 401px)" 

as opposed to

media="screen and (min-width: 401px)"

to make sure it is not interpreted as

media="screen"

It would be a good test for someone with access to a device lab.

How can I sort a List alphabetically?

Here is what you are looking for

listOfCountryNames.sort(String::compareToIgnoreCase)

Delete a database in phpMyAdmin

On phpMyAdmin 4.1.9:

database_name > Operations > Remove database

enter image description here

New line in JavaScript alert box

_x000D_
_x000D_
 alert("some text\nmore text in a new line");
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
alert("Line 1\nLine 2\nLine 3\nLine 4\nLine 5");
_x000D_
_x000D_
_x000D_

Bootstrap - 5 column layout

_x000D_
_x000D_
.col-xs-2{_x000D_
    background:#00f;_x000D_
    color:#FFF;_x000D_
}_x000D_
.col-half-offset{_x000D_
    margin-left:4.166666667%_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
    <div class="row" style="border: 1px solid red">_x000D_
        <div class="col-xs-2" id="p1">One</div>_x000D_
        <div class="col-xs-2 col-half-offset" id="p2">Two</div>_x000D_
        <div class="col-xs-2 col-half-offset" id="p3">Three</div>_x000D_
        <div class="col-xs-2 col-half-offset" id="p4">Four</div>_x000D_
        <div class="col-xs-2 col-half-offset" id="p5">Five</div>_x000D_
        <div>lorem</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This should be ok.

VBA Subscript out of range - error 9

Suggest the following simplification: capture return value from Workbooks.Add instead of subscripting Windows() afterward, as follows:

Set wkb = Workbooks.Add
wkb.SaveAs ...

wkb.Activate ' instead of Windows(expression).Activate


General Philosophy Advice:

Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.

Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.

Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection

During and within macros do not rely on these built-in names, instead capture return values, e.g.

Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate

Also, try to use qualified expressions, e.g.

wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"

or

Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"

Use qualified expressions, e.g.

newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar" 

These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.

Also please note that you'll likely find that you don't need to .Activate nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate could simply be eliminated instead of even being replaced by wkb.Activate.

(Also note: I think the .Select statements you show are not contributing and can be omitted.)

(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)

Selecting with complex criteria from pandas.DataFrame

And remember to use parenthesis!

Keep in mind that & operator takes a precedence over operators such as > or < etc. That is why

4 < 5 & 6 > 4

evaluates to False. Therefore if you're using pd.loc, you need to put brackets around your logical statements, otherwise you get an error. That's why do:

df.loc[(df['A'] > 10) & (df['B'] < 15)]

instead of

df.loc[df['A'] > 10 & df['B'] < 15]

which would result in

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

MySQL: Error dropping database (errno 13; errno 17; errno 39)

This was how I solved it:

mysql> DROP DATABASE mydatabase;
ERROR 1010 (HY000): Error dropping database (can't rmdir '.\mydatabase', errno: 13)
mysql> 

I went to delete this directory: C:\...\UniServerZ\core\mysql\data\mydatabase.

mysql> DROP DATABASE mydatabase;
ERROR 1008 (HY000): Can't drop database 'mydatabase'; database doesn't exist

HTTP status code for update and delete?

In June 2014 RFC7231 obsoletes RFC2616. If you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE

Detect if user is scrolling

Use an interval to check

You can setup an interval to keep checking if the user has scrolled then do something accordingly.

Borrowing from the great John Resig in his article.

Example:

    let didScroll = false;

    window.onscroll = () => didScroll = true;

    setInterval(() => {
        if ( didScroll ) {
            didScroll = false;
            console.log('Someone scrolled me!')
        }
    }, 250);

See live example

Search File And Find Exact Match And Print Line?

To check for an exact match you would use num == line. But line has an end-of-line character \n or \r\n which will not be in num since raw_input strips the trailing newline. So it may be convenient to remove all whitespace at the end of line with

line = line.rstrip()

with open("file.txt") as search:
    for line in search:
        line = line.rstrip()  # remove '\n' at end of line
        if num == line:
            print(line )

Set a button background image iPhone programmatically

Complete code:

+ (UIButton *)buttonWithTitle:(NSString *)title
                       target:(id)target
                     selector:(SEL)selector
                        frame:(CGRect)frame
                        image:(UIImage *)image
                 imagePressed:(UIImage *)imagePressed
                darkTextColor:(BOOL)darkTextColor
{
    UIButton *button = [[UIButton alloc] initWithFrame:frame];

    button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];


    UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
    [button setBackgroundImage:newImage forState:UIControlStateNormal];

    UIImage *newPressedImage = [imagePressed stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
    [button setBackgroundImage:newPressedImage forState:UIControlStateHighlighted];

    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];

    // in case the parent view draws with a custom color or gradient, use a transparent color
    button.backgroundColor = [UIColor clearColor];

    return button;
}

UIImage *buttonBackground = UIImage imageNamed:@"whiteButton.png";
UIImage *buttonBackgroundPressed = UIImage imageNamed:@"blueButton.png";

CGRect frame = CGRectMake(0.0, 0.0, kStdButtonWidth, kStdButtonHeight);

UIButton *button = [FinishedStatsView buttonWithTitle:title
                                               target:target
                                             selector:action
                                                frame:frame
                                                image:buttonBackground
                                         imagePressed:buttonBackgroundPressed
                                        darkTextColor:YES];

[self addSubview:button]; 

To set an image:

UIImage *buttonImage = [UIImage imageNamed:@"Home.png"];
[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:myButton];

To remove an image:

[button setBackgroundImage:nil forState:UIControlStateNormal];

Using jq to parse and display multiple fields in a json serially

You can use addition to concatenate strings.

Strings are added by being joined into a larger string.

jq '.users[] | .first + " " + .last'

The above works when both first and last are string. If you are extracting different datatypes(number and string), then we need to convert to equivalent types. Referring to solution on this question. For example.

jq '.users[] | .first + " " + (.number|tostring)'

C++: Where to initialize variables in constructor

Although it doesn't apply to this specific example, Option 1 allows you to initialize member variables of reference type (or const type, as pointed out below). Option 2 doesn't. In general, Option 1 is the more powerful approach.

How to set the text color of TextView in code?

holder.text.setTextColor(Color.rgb(200,0,0));

or

myTextView.setTextColor(0xAARRGGBB);

Redirect on Ajax Jquery Call

JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm page.

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery:

$(document).ready(function(){ 
    jQuery.ajax({ 
        type: "GET", 
        url: "populateData.htm", 
        dataType:"json", 
        data:"userId=SampleUser", 
        success:function(response){ 
            if (response.redirect) {
                window.location.href = response.redirect;
            }
            else {
                // Process the expected results...
            }
        }, 
     error: function(xhr, textStatus, errorThrown) { 
            alert('Error!  Status = ' + xhr.status); 
         } 

    }); 
}); 

You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1") and in JQuery you do on success(!):

//....
        success:function(response){ 
            if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
                window.location.href = 'login.htm'; 
            }
            else {
                // Process the expected results...
            }
        }
//....

Hope that helps.

My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.

How to get Activity's content view?

The best option I found and the less intrusive, is to set a tag param in your xml, like

PHONE XML LAYOUT

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:tag="phone"/>

TABLET XML LAYOUT

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:tag="tablet">

    ...

</RelativeLayout>

and then call this in your activity class:

View viewPager = findViewById(R.id.pager);
Log.d(getClass().getSimpleName(), String.valueOf(viewPager.getTag()));

Hope it works for u.

What is the difference between C# and .NET?

When people talk about the ".net framework" they tend to be combining two main areas - the runtime library and the virtual machine that actually runs the .net code.

When you create a class library in Visual Studio in C#, the DLL follows a prescribed format - very roughly, there is section that contains meta data that describes what classes are included in it and what functions they have, etc.. and that describes where in the binary those objects exist. This common .net format is what allows libraries to be shared between .net languages (C#, VB.Net, F# and others) easily. Although much of the .net "runtime library" is written in C# now (I believe), you can imagine how many of them could have been written in unmanaged languages but arranged in this prescribed format so that they could be consumed by .net languages.

The real "meat" of the library that you build consists of CIL ("Common Intermediate Language") which is a bit like the assembly language of .net - again, this language is the common output of all .net languages, which is what makes .net libraries consumable by any .net language.

Using the tool "ildasm.exe", which is freely available in Microsoft SDKs (and might already be on your computer), you can see how C# code is converted into meta data and IL. I've included a sample at the bottom of this answer as an example.

When you run execute .net code, what is commonly happening is the .net virtual machine is reading that IL and processing it. This is the other side of .net and, again, you can likely imagine that this could easily be written in an unmanaged language - it "only" needs to read VM instructions and run them (and integrate with the garbage collector, which also need not be .net code).

What I've described is (again, roughly) what happens when you build an executable in Visual Studio (for more information, I highly recommend the book "CLR via C# by Jeffrey Richter" - it's very detailed and excellently written).

However, there are times that you might write C# that will not be executed within a .net environment - for example, Bridge.NET "compiles" C# code into JavaScript which is then run in the browser (the team that produce it have gone to the effort of writing versions of the .net runtime library that are written in JavaScript and so the power and flexibility of the .net library is available to the generated JavaScript). This is a perfect example of the separation between C# and .net - it's possible to write C# for different "targets"; you might target the .net runtime environment (when you build an executable) or you might target the browser environment (when you use Bridge.NET).

A (very) simple example class:

using System;

namespace Example
{
    public class Class1
    {
        public void SayHello()
        {
            Console.WriteLine("Hello");
        }
    }
}

The resulting meta data and IL (retrieved via ildasm.exe):

// Metadata version: v4.0.30319
.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..
  .ver 4:0:0:0
}
.assembly Example
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78   // ....T..WrapNonEx
                                                                                                            63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 )       // ceptionThrows.

  // --- The following custom attribute is added automatically, do not uncomment -------
  //  .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 07 01 00 00 00 00 ) 

  .custom instance void [mscorlib]System.Reflection.AssemblyTitleAttribute::.ctor(string) = ( 01 00 0A 54 65 73 74 49 4C 44 41 53 4D 00 00 )    // ...TestILDASM..
  .custom instance void [mscorlib]System.Reflection.AssemblyDescriptionAttribute::.ctor(string) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Reflection.AssemblyConfigurationAttribute::.ctor(string) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Reflection.AssemblyCompanyAttribute::.ctor(string) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Reflection.AssemblyProductAttribute::.ctor(string) = ( 01 00 0A 54 65 73 74 49 4C 44 41 53 4D 00 00 )    // ...TestILDASM..
  .custom instance void [mscorlib]System.Reflection.AssemblyCopyrightAttribute::.ctor(string) = ( 01 00 12 43 6F 70 79 72 69 67 68 74 20 C2 A9 20   // ...Copyright .. 
                                                                                                  20 32 30 31 36 00 00 )                            //  2016..
  .custom instance void [mscorlib]System.Reflection.AssemblyTrademarkAttribute::.ctor(string) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Runtime.InteropServices.ComVisibleAttribute::.ctor(bool) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 39 33 32 61 32 30 65 2D 61 37 36 64   // ..$1932a20e-a76d
                                                                                                  2D 34 36 33 35 2D 62 36 38 66 2D 36 63 35 66 36   // -4635-b68f-6c5f6
                                                                                                  32 36 36 31 36 37 62 00 00 )                      // 266167b..
  .custom instance void [mscorlib]System.Reflection.AssemblyFileVersionAttribute::.ctor(string) = ( 01 00 07 31 2E 30 2E 30 2E 30 00 00 )             // ...1.0.0.0..
  .custom instance void [mscorlib]System.Runtime.Versioning.TargetFrameworkAttribute::.ctor(string) = ( 01 00 1C 2E 4E 45 54 46 72 61 6D 65 77 6F 72 6B   // ....NETFramework
                                                                                                        2C 56 65 72 73 69 6F 6E 3D 76 34 2E 35 2E 32 01   // ,Version=v4.5.2.
                                                                                                        00 54 0E 14 46 72 61 6D 65 77 6F 72 6B 44 69 73   // .T..FrameworkDis
                                                                                                        70 6C 61 79 4E 61 6D 65 14 2E 4E 45 54 20 46 72   // playName..NET Fr
                                                                                                        61 6D 65 77 6F 72 6B 20 34 2E 35 2E 32 )          // amework 4.5.2
  .hash algorithm 0x00008004
  .ver 1:0:0:0
}
.module Example.dll
// MVID: {80A91E4C-0994-4773-9B73-2C4977BB1F17}
.imagebase 0x10000000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003       // WINDOWS_CUI
.corflags 0x00000001    //  ILONLY
// Image base: 0x05DB0000

// =============== CLASS MEMBERS DECLARATION ===================

.class public auto ansi beforefieldinit Example.Class1
       extends [mscorlib]System.Object
{
  .method public hidebysig instance void 
          SayHello() cil managed
  {
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      "Hello"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  } // end of method Class1::SayHello

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       8 (0x8)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  nop
    IL_0007:  ret
  } // end of method Class1::.ctor

} // end of class Example.Class1

// =============================================================

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

Set the buildToolsVersion '26.0.2' then change classpath 'com.android.tools.build:gradle:3.0.1'.

Make sure you set compileSdkVersion to 26 whiles targetSdkVersion is also set 26.

It is also appropriate to sent set compile 'com.android.support:appcompat-v7:26.0.2'.

Finding Variable Type in JavaScript

To be a little more ECMAScript-5.1-precise than the other answers (some might say pedantic):

In JavaScript, variables (and properties) don't have types: values do. Further, there are only 6 types of values: Undefined, Null, Boolean, String, Number, and Object. (Technically, there are also 7 "specification types", but you can't store values of those types as properties of objects or values of variables--they are only used within the spec itself, to define how the language works. The values you can explicitly manipulate are of only the 6 types I listed.)

The spec uses the notation "Type(x)" when it wants to talk about "the type of x". This is only a notation used within the spec: it is not a feature of the language.

As other answers make clear, in practice you may well want to know more than the type of a value--particularly when the type is Object. Regardless, and for completeness, here is a simple JavaScript implementation of Type(x) as it is used in the spec:

function Type(x) { 
    if (x === null) {
        return 'Null';
    }

    switch (typeof x) {
    case 'undefined': return 'Undefined';
    case 'boolean'  : return 'Boolean';
    case 'number'   : return 'Number';
    case 'string'   : return 'String';
    default         : return 'Object';
    }
}

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

I had to use a slightly extended version @Erwin Brandstetter used:

DO
$do$
DECLARE
  _db TEXT := 'some_db';
  _user TEXT := 'postgres_user';
  _password TEXT := 'password';
BEGIN
  CREATE EXTENSION IF NOT EXISTS dblink; -- enable extension 
  IF EXISTS (SELECT 1 FROM pg_database WHERE datname = _db) THEN
    RAISE NOTICE 'Database already exists';
  ELSE
    PERFORM dblink_connect('host=localhost user=' || _user || ' password=' || _password || ' dbname=' || current_database());
    PERFORM dblink_exec('CREATE DATABASE ' || _db);
  END IF;
END
$do$

I had to enable the dblink extension, plus i had to provide the credentials for dblink. Works with Postgres 9.4.

How do I replicate a \t tab space in HTML?

This simple formula should work. Give the element whose text will contain a tab the following CSS property: white-space:pre. Otherwise your html may not render tabs at all. Then, wherever you want to have a tab in your text, type &#9;.

Since you didn't mention CSS, if you want to do this without a CSS file, just use

<tag-name style="white-space:pre">text in element&#9;more text</tag-name>

in your HTML.

Python exit commands - why so many and when should each be used?

Different Means of Exiting

os._exit():

  • Exit the process without calling the cleanup handlers.

exit(0):

  • a clean exit without any errors / problems.

exit(1):

  • There was some issue / error / problem and that is why the program is exiting.

sys.exit():

  • When the system and python shuts down; it means less memory is being used after the program is run.

quit():

  • Closes the python file.

Summary

Basically they all do the same thing, however, it also depends on what you are doing it for.

I don't think you left anything out and I would recommend getting used to quit() or exit().

You would use sys.exit() and os._exit() mainly if you are using big files or are using python to control terminal.

Otherwise mainly use exit() or quit().

Getting A File's Mime Type In Java

I tried several ways to do it, including the first ones said by @Joshua Fox. But some don't recognize frequent mimetypes like for PDF files, and other could not be trustable with fake files (I tried with a RAR file with extension changed to TIF). The solution I found, as also is said by @Joshua Fox in a superficial way, is to use MimeUtil2, like this:

MimeUtil2 mimeUtil = new MimeUtil2();
mimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
String mimeType = MimeUtil2.getMostSpecificMimeType(mimeUtil.getMimeTypes(file)).toString();

Create Directory When Writing To File In Node.js

With node-fs-extra you can do it easily.

Install it

npm install --save fs-extra

Then use the outputFile method. Its documentation says:

Almost the same as writeFile (i.e. it overwrites), except that if the parent directory does not exist, it's created.

You can use it in three ways:

Callback style

const fse = require('fs-extra');

fse.outputFile('tmp/test.txt', 'Hey there!', err => {
  if(err) {
    console.log(err);
  } else {
    console.log('The file was saved!');
  }
})

Using Promises

If you use promises, and I hope so, this is the code:

fse.outputFile('tmp/test.txt', 'Hey there!')
   .then(() => {
       console.log('The file was saved!');
   })
   .catch(err => {
       console.error(err)
   });

Sync version

If you want a sync version, just use this code:

fse.outputFileSync('tmp/test.txt', 'Hey there!')

For a complete reference, check the outputFile documentation and all node-fs-extra supported methods.

Detect & Record Audio in Python

The pyaudio website has many examples that are pretty short and clear: http://people.csail.mit.edu/hubert/pyaudio/

Update 14th of December 2019 - Main example from the above linked website from 2017:


"""PyAudio Example: Play a WAVE file."""

import pyaudio
import wave
import sys

CHUNK = 1024

if len(sys.argv) < 2:
    print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

p = pyaudio.PyAudio()

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)

data = wf.readframes(CHUNK)

while data != '':
    stream.write(data)
    data = wf.readframes(CHUNK)

stream.stop_stream()
stream.close()

p.terminate()

Check whether a string contains a substring

Another possibility is to use regular expressions which is what Perl is famous for:

if ($mystring =~ /s1\.domain\.com/) {
   print qq("$mystring" contains "s1.domain.com"\n);
}

The backslashes are needed because a . can match any character. You can get around this by using the \Q and \E operators.

my $substring = "s1.domain.com";
    if ($mystring =~ /\Q$substring\E/) {
   print qq("$mystring" contains "$substring"\n);
}

Or, you can do as eugene y stated and use the index function. Just a word of warning: Index returns a -1 when it can't find a match instead of an undef or 0.

Thus, this is an error:

my $substring = "s1.domain.com";
if (not index($mystring, $substr)) {
    print qq("$mystring" doesn't contains "$substring"\n";
} 

This will be wrong if s1.domain.com is at the beginning of your string. I've personally been burned on this more than once.

Rails: FATAL - Peer authentication failed for user (PG::Error)

If you installed postresql on your server then just host: localhost to database.yml, I usually throw it in around where it says pool: 5. Otherwise if it's not localhost definitely tell that app where to find its database.

development:
  adapter: postgresql
  encoding: unicode
  database: kickrstack_development
  host: localhost
  pool: 5
  username: kickrstack
  password: secret

Make sure your user credentials are set correctly by creating a database and assigning ownership to your app's user to establish the connection. To create a new user in postgresql 9 run:

sudo -u postgres psql

set the postgresql user password if you haven't, it's just backslash password.

postgres=# \password

Create a new user and password and the user's new database:

postgres=# create user "guy_on_stackoverflow" with password 'keepitonthedl';
postgres=# create database "dcaclab_development" owner "guy_on_stackoverflow"; 

Now update your database.yml file after you've confirmed creating the database, user, password and set these privileges. Don't forget host: localhost.

6 digits regular expression

You could try

^[0-9]{1,6}$

it should work.

Why maven settings.xml file is not there?

As per the maven's documentation, there are two possible settings.xml locations

One is the global maven's repo (Your initial download and subsequent unzipped files from apache maven) $M2_HOME/conf/settings.xml

And the second is the user created one (Your local copy) ${user.home}/.m2/settings.xml

The local copy takes precedence over the global copy in terms of settings information. But it is said that they both get merged during "runtime". If you need to have your local copy of the settings.xml, simply copy from the global copy and paste in your .m2 folder and adjust the details as needed

How to sort a Pandas DataFrame by index?

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

Gives me:

     A
1    4
29   2
100  1
150  5
234  3

How To Upload Files on GitHub

To upload files to your repo without using the command-line, simply type this after your repository name in the browser:

https://github.com/yourname/yourrepositoryname/upload/master

and then drag and drop your files.(provided you are on github and the repository has been created beforehand)

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

Git push error '[remote rejected] master -> master (branch is currently checked out)'

You should only be pushing to a bare repository. A bare repository is a repository that has no checked out branches. If you were to cd to a bare repository directory, you'd only see the contents of a .git directory.

Apple Cover-flow effect using jQuery or other library?

Not sure if you're talking about Coverflow (scroll through images) or Quicklook (preview files in lightbox), try editing your question.

Here's some JS Coverflow implementations:

jQuery: How to get the event object in an event handler function without passing it as an argument?

in IE you can get the event object by window.event in other browsers with no 'use strict' directive, it is possible to get by arguments.callee.caller.arguments[0].

function myFunc(p1, p2, p3) {
    var evt = window.event || arguments.callee.caller.arguments[0];
}

How to exit from the application and show the home screen?

Add following lines after finish(); in onDestroy():

android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();

angularjs - ng-repeat: access key and value from JSON array object

I have just started checking out Angular(so im quite sure there are other ways to get it done which are more optimum), and i came across this question while searching for examples of ng-repeat.

The requirement by the poser(with the update):

"...but my real requirement is display the items as shown below.."

looked real-world enough (and simple), so i thought ill give it a spin and attempt to get the exact desired structure.

_x000D_
_x000D_
angular.module('appTest', [])_x000D_
  .controller("repeatCtrl", function($scope) {_x000D_
    $scope.items = [{_x000D_
      Name: "Soap",_x000D_
      Price: "25",_x000D_
      Quantity: "10"_x000D_
    }, {_x000D_
      Name: "Bag",_x000D_
      Price: "100",_x000D_
      Quantity: "15"_x000D_
    }, {_x000D_
      Name: "Pen",_x000D_
      Price: "15",_x000D_
      Quantity: "13"_x000D_
    }];_x000D_
  })
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<body ng-app="appTest">_x000D_
  <section ng-controller="repeatCtrl">_x000D_
    <table>_x000D_
      <thead>_x000D_
        <tr ng-repeat="item in items | limitTo:1">_x000D_
          <th ng-repeat="(key, val) in item">_x000D_
            {{key}}_x000D_
          </th>_x000D_
        </tr>_x000D_
      </thead>_x000D_
      <tbody>_x000D_
        <tr ng-repeat="item in items">_x000D_
          <td ng-repeat="(key, val) in item">_x000D_
            {{val}}_x000D_
          </td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
  </section>_x000D_
</body>
_x000D_
_x000D_
_x000D_

The limitTo:(n) filter is the key. Im still not sure if having multiple ng-repeat is an optimum way to go about it, but can't think of another alternative currently.

JavaScript: filter() for Objects

ES6 approach...

Imagine you have this object below:

const developers = {
  1: {
   id: 1,
   name: "Brendan", 
   family: "Eich"
  },
  2: {
   id: 2,
   name: "John", 
   family: "Resig"
  },  
  3: {
   id: 3,
   name: "Alireza", 
   family: "Dezfoolian"
 }
};

Create a function:

const filterObject = (obj, filter, filterValue) => 
   Object.keys(obj).reduce((acc, val) => 
   (obj[val][filter] === filterValue ? acc : {
       ...acc,
       [val]: obj[val]
   }                                        
), {});

And call it:

filterObject(developers, "name", "Alireza");

and will return:

{
  1: {
  id: 1,
  name: "Brendan", 
  family: "Eich"
  },
  2: {
   id: 2,
   name: "John", 
   family: "Resig"
  }
}

how to execute php code within javascript

If you do not want to include the jquery library you can simple do the following

a) ad an iframe, size 0px so it is not visible, href is blank

b) execute this within your js code function

 window.frames['iframename'].location.replace('http://....your.php');

This will execute the php script and you can for example make a database update...

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

Replace a value in a data frame based on a conditional (`if`) statement

You have created a factor variable in nm so you either need to avoid doing so or add an additional level to the factor attributes. You should also avoid using <- in the arguments to data.frame()

Option 1:

junk <- data.frame(x = rep(LETTERS[1:4], 3), y =letters[1:12], stringsAsFactors=FALSE)
junk$nm[junk$nm == "B"] <- "b"

Option 2:

levels(junk$nm) <- c(levels(junk$nm), "b")
junk$nm[junk$nm == "B"] <- "b"
junk

Angular ForEach in Angular4/Typescript?

arrayData.forEach((key : any, val: any) => {
                        key['index'] = val + 1;

                        arrayData2.forEach((keys : any, vals :any) => {
                            if (key.group_id == keys.id) {
                                key.group_name = keys.group_name;
                            }
                        })
                    })

How do you get the length of a string?

same way you do it in javascript:

"something".length

Execution sequence of Group By, Having and Where clause in SQL Server?

SELECT
FROM
JOINs
WHERE
GROUP By
HAVING
ORDER BY

React-router: How to manually invoke Link?

React Router v5 - React 16.8+ with Hooks (updated 09/23/2020)

If you're leveraging React Hooks, you can take advantage of the useHistory API that comes from React Router v5.

import React, {useCallback} from 'react';
import {useHistory} from 'react-router-dom';

export default function StackOverflowExample() {
  const history = useHistory();
  const handleOnClick = useCallback(() => history.push('/sample'), [history]);

  return (
    <button type="button" onClick={handleOnClick}>
      Go home
    </button>
  );
}

Another way to write the click handler if you don't want to use useCallback

const handleOnClick = () => history.push('/sample');

React Router v4 - Redirect Component

The v4 recommended way is to allow your render method to catch a redirect. Use state or props to determine if the redirect component needs to be shown (which then trigger's a redirect).

import { Redirect } from 'react-router';

// ... your class implementation

handleOnClick = () => {
  // some action...
  // then redirect
  this.setState({redirect: true});
}

render() {
  if (this.state.redirect) {
    return <Redirect push to="/sample" />;
  }

  return <button onClick={this.handleOnClick} type="button">Button</button>;
}

Reference: https://reacttraining.com/react-router/web/api/Redirect

React Router v4 - Reference Router Context

You can also take advantage of Router's context that's exposed to the React component.

static contextTypes = {
  router: PropTypes.shape({
    history: PropTypes.shape({
      push: PropTypes.func.isRequired,
      replace: PropTypes.func.isRequired
    }).isRequired,
    staticContext: PropTypes.object
  }).isRequired
};

handleOnClick = () => {
  this.context.router.push('/sample');
}

This is how <Redirect /> works under the hood.

Reference: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Redirect.js#L46,L60

React Router v4 - Externally Mutate History Object

If you still need to do something similar to v2's implementation, you can create a copy of BrowserRouter then expose the history as an exportable constant. Below is a basic example but you can compose it to inject it with customizable props if needed. There are noted caveats with lifecycles, but it should always rerender the Router, just like in v2. This can be useful for redirects after an API request from an action function.

// browser router file...
import createHistory from 'history/createBrowserHistory';
import { Router } from 'react-router';

export const history = createHistory();

export default class BrowserRouter extends Component {
  render() {
    return <Router history={history} children={this.props.children} />
  }
}

// your main file...
import BrowserRouter from './relative/path/to/BrowserRouter';
import { render } from 'react-dom';

render(
  <BrowserRouter>
    <App/>
  </BrowserRouter>
);

// some file... where you don't have React instance references
import { history } from './relative/path/to/BrowserRouter';

history.push('/sample');

Latest BrowserRouter to extend: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/BrowserRouter.js

React Router v2

Push a new state to the browserHistory instance:

import {browserHistory} from 'react-router';
// ...
browserHistory.push('/sample');

Reference: https://github.com/reactjs/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md

How to set locale in DatePipe in Angular 2?

You do something like this:

{{ dateObj | date:'shortDate' }}

or

{{ dateObj | date:'ddmmy' }}

See: https://angular.io/docs/ts/latest/api/common/index/DatePipe-pipe.html

How to add a form load event (currently not working)

Three ways you can do this - from the form designer, select the form, and where you normally see the list of properties, just above it there should be a little lightning symbol - this shows you all the events of the form. Find the form load event in the list, and you should be able to pick ProgramViwer_Load from the dropdown.

A second way to do it is programmatically - somewhere (constructor maybe) you'd need to add it, something like: ProgramViwer.Load += new EventHandler(ProgramViwer_Load);

A third way using the designer (probably the quickest) - when you create a new form, double click on the middle of it on it in design mode. It'll create a Form load event for you, hook it in, and take you to the event handler code. Then you can just add your two lines and you're good to go!

Iterating through a JSON object

for iterating through JSON you can use this:

json_object = json.loads(json_file)
for element in json_object: 
    for value in json_object['Name_OF_YOUR_KEY/ELEMENT']:
        print(json_object['Name_OF_YOUR_KEY/ELEMENT']['INDEX_OF_VALUE']['VALUE'])

Query an XDocument for elements by name at any depth

I am using XPathSelectElements extension method which works in the same way to XmlDocument.SelectNodes method:

using System;
using System.Xml.Linq;
using System.Xml.XPath; // for XPathSelectElements

namespace testconsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument xdoc = XDocument.Parse(
                @"<root>
                    <child>
                        <name>john</name>
                    </child>
                    <child>
                        <name>fred</name>
                    </child>
                    <child>
                        <name>mark</name>
                    </child>
                 </root>");

            foreach (var childElem in xdoc.XPathSelectElements("//child"))
            {
                string childName = childElem.Element("name").Value;
                Console.WriteLine(childName);
            }
        }
    }
}

How to use jQuery in AngularJS

Ideally you would put that in a directive, but you can also just put it in the controller. http://jsfiddle.net/tnq86/15/

  angular.module('App', [])
    .controller('AppCtrl', function ($scope) {

      $scope.model = 0;

      $scope.initSlider = function () {
          $(function () {
            // wait till load event fires so all resources are available
              $scope.$slider = $('#slider').slider({
                  slide: $scope.onSlide
              });
          });

          $scope.onSlide = function (e, ui) {
             $scope.model = ui.value;
             $scope.$digest();
          };
      };

      $scope.initSlider();
  });

The directive approach:

HTML

<div slider></div>

JS

  angular.module('App', [])
    .directive('slider', function (DataModel) {
      return {
         restrict: 'A',
         scope: true,
         controller: function ($scope, $element, $attrs) {
            $scope.onSlide = function (e, ui) {
              $scope.model = ui.value;
              // or set it on the model
              // DataModel.model = ui.value;
              // add to angular digest cycle
              $scope.$digest();
            };
         },
         link: function (scope, el, attrs) {

            var options = {
              slide: scope.onSlide  
            };

            // set up slider on load
            angular.element(document).ready(function () {
              scope.$slider = $(el).slider(options);
            });
         }
      }
  });

I would also recommend checking out Angular Bootstrap's source code: https://github.com/angular-ui/bootstrap/blob/master/src/tooltip/tooltip.js

You can also use a factory to create the directive. This gives you ultimate flexibility to integrate services around it and whatever dependencies you need.

Pointer to incomplete class type is not allowed

You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:

namespace X
{
  namespace Y
  {
    class A;

    void func(A* a) { ... } // incomplete type here!
  }
}

...but, in class A was defined like this:

namespace X
{
  class A { ... };
}

Thus, A was defined as X::A, but I was using it as X::Y::A.

The fix obviously is to move the forward reference to its proper place like so:

namespace X
{
  class A;
  namespace Y
  {
    void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
  }
}

How to find current transaction level?

just run DBCC useroptions and you'll get something like this:

Set Option                  Value
--------------------------- --------------
textsize                    2147483647
language                    us_english
dateformat                  mdy
datefirst                   7
lock_timeout                -1
quoted_identifier           SET
arithabort                  SET
ansi_null_dflt_on           SET
ansi_warnings               SET
ansi_padding                SET
ansi_nulls                  SET
concat_null_yields_null     SET
isolation level             read committed

Is there a simple way to use button to navigate page as a link does in angularjs

If you're OK with littering your markup a bit, you could do it the easy way and just wrap your <button> with an anchor (<a>) link.

<a href="#/new-page.html"><button>New Page<button></a>

Also, there is nothing stopping you from styling an anchor link to look like a <button>


as pointed out in the comments by @tronman, this is not technically valid html5, but it should not cause any problems in practice

How to convert a date String to a Date or Calendar object?

In brief:

DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
try {
  Date date = formatter.parse("01/29/02");
} catch (ParseException e) {
  e.printStackTrace();
}

See SimpleDateFormat javadoc for more.

And to turn it into a Calendar, do:

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

addClass and removeClass in jQuery - not removing class

I think you're almost there. The thing is, your $(this) in the "close button" listener is not the clickable div. So you want to search it first. try to replace $(this) with $(this).closest(".clickable") . And don't forget the e.stopPropagation() as Guilherme is suggesting. that should be something like:

$( document ).ready(function() {   
    $(document).on("click", ".close_button", function () { 
        alert ("oi");
        e.stopPropagation()
        $(this).closest(".clickable").addClass("spot");
        $(this).closest(".clickable").removeClass("grown");
    });  


    $(document).on("click", ".clickable", function () {
        if ($(this).hasClass("spot")){
            $(this).addClass("grown");
            $(this).removeClass("spot");
        }
    });
});

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

Just in case if you are using Telerik components and you have a reference in your javascript with <%= .... %> then wrap your script tag with a RadScriptBlock.

 <telerik:RadScriptBlock ID="radSript1" runat="server">
   <script type="text/javascript">
        //Your javascript
   </script>
</telerik>

Regards Örvar

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

Firstly in general tab -> signing section -> select a development team, manage signings

Similarly if you are working with multiple pod files select each pod target separately and go to general tab -> signing section -> select a development team, manage signings

repeat the same process for all pods in your project

Clean -> Build the project.

This worked for me

Can I delete data from the iOS DeviceSupport directory?

The ~/Library/Developer/Xcode/iOS DeviceSupport folder is basically only needed to symbolicate crash logs.

You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.

I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.

How to remove the arrows from input[type="number"] in Opera

I've been using some simple CSS and it seems to remove them and work fine.

_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button, _x000D_
input[type=number]::-webkit-outer-spin-button { _x000D_
    -webkit-appearance: none;_x000D_
    -moz-appearance: none;_x000D_
    appearance: none;_x000D_
    margin: 0; _x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
_x000D_
_x000D_

This tutorial from CSS Tricks explains in detail & also shows how to style them

Android: Changing Background-Color of the Activity (Main View)

I just want to add my 2 cents. I had the same goal (to change the background color from the .java class). But none of the above methods worked for me.

Issue was, that I set the background color inside the layout .xml file with android:background="@color/colorGray":

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/colorGray">

So I just deleted particular line:

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

Now I (you) can set the color from the code with:

getWindow().getDecorView().setBackgroundColor(Color.GRAY);

ProcessStartInfo hanging on "WaitForExit"? Why?

I solved it this way:

            Process proc = new Process();
            proc.StartInfo.FileName = batchFile;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.RedirectStandardInput = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;      
            proc.Start();
            StreamWriter streamWriter = proc.StandardInput;
            StreamReader outputReader = proc.StandardOutput;
            StreamReader errorReader = proc.StandardError;
            while (!outputReader.EndOfStream)
            {
                string text = outputReader.ReadLine();                    
                streamWriter.WriteLine(text);
            }

            while (!errorReader.EndOfStream)
            {                   
                string text = errorReader.ReadLine();
                streamWriter.WriteLine(text);
            }

            streamWriter.Close();
            proc.WaitForExit();

I redirected both input, output and error and handled reading from output and error streams. This solution works for SDK 7- 8.1, both for Windows 7 and Windows 8

How to refresh app upon shaking the device?

I have written a small example for detecting vertical and horizontal shakes and showing a Toast.

public class Accelerometerka2Activity extends Activity implements SensorEventListener { 
    private float mLastX, mLastY, mLastZ;
    private boolean mInitialized;
    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private final float NOISE = (float) 8.0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mInitialized = false;
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(this, mAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
    }

    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }

    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }


    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // can be safely ignored for this demo
    }


    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
        if (!mInitialized) {
            mLastX = x;
            mLastY = y;
            mLastZ = z;
            mInitialized = true;
        } else {
            float deltaX = Math.abs(mLastX - x);
            float deltaY = Math.abs(mLastY - y);
            float deltaZ = Math.abs(mLastZ - z);
            if (deltaX < NOISE) deltaX = (float)0.0;
            if (deltaY < NOISE) deltaY = (float)0.0;
            if (deltaZ < NOISE) deltaZ = (float)0.0;
            mLastX = x;
            mLastY = y;
            mLastZ = z;
            if (deltaX > deltaY) {
                Toast.makeText(getBaseContext(), "Horizental", Toast.LENGTH_SHORT).show();
            } else if (deltaY > deltaX) {
                Toast.makeText(getBaseContext(), "Vertical", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Send auto email programmatically

It might be an easiest way-

    String recipientList = mEditTextTo.getText().toString();
    String[] recipients = recipientList.split(",");

    String subject = mEditTextSubject.getText().toString();
    String message = mEditTextMessage.getText().toString();

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_EMAIL, recipients);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, message);

    intent.setType("message/rfc822");
    startActivity(Intent.createChooser(intent, "Choose an email client"));

How we can bold only the name in table td tag not the value

Surround what you want to be bold with:

<span style="font-weight:bold">Your bold text</span>

This would go inside your <td> tag.

How to determine whether a Pandas Column contains a particular value

Use

df[df['id']==x].index.tolist()

If x is present in id then it'll return the list of indices where it is present, else it gives an empty list.

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

C# - What does the Assert() method do? Is it still useful?

First of all Assert() method is available for Trace and Debug classes.
Debug.Assert() is executing only in Debug mode.
Trace.Assert() is executing in Debug and Release mode.

Here is an example:

        int i = 1 + 3;
        // Debug.Assert method in Debug mode fails, since i == 4
        Debug.Assert(i == 3);
        Debug.WriteLine(i == 3, "i is equal to 3");

        // Trace.Assert method in Release mode is not failing.
        Trace.Assert(i == 4);
        Trace.WriteLine(i == 4, "i is equla to 4");

        Console.WriteLine("Press a key to continue...");
        Console.ReadLine();

Run this code in Debug mode and then in Release mode.

enter image description here

You will notice that during Debug mode your code Debug.Assert statement fails, you get a message box showing the current stack trace of the application. This is not happening in Release mode since Trace.Assert() condition is true (i == 4).

WriteLine() method simply gives you an option of logging the information to Visual Studio output. enter image description here

Connection Strings for Entity Framework

Silverlight applications do not have direct access to machine.config.

jQuery click not working for dynamically created items

Do this:

 $( '#wrapper' ).on( 'click', 'a', function () { ... });

where #wrapper is a static element in which you add the dynamic links.

So, you have a wrapper which is hard-coded into the HTML source code:

<div id="wrapper"></div>

and you fill it with dynamic content. The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.


Btw, I recommend Backbone.js - it gives structure to this process:

var YourThing = Backbone.View.extend({

    // the static wrapper (the root for event delegation)
    el: $( '#wrapper' ),

    // event bindings are defined here 
    events: {
        'click a': 'anchorClicked'
    },

    // your DOM event handlers
    anchorClicked: function () {
        // handle click event 
    }

});

new YourThing; // initializing your thing

How do I undo a checkout in git?

You probably want git checkout master, or git checkout [branchname].

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

find . -type f -exec chmod 644 {} ;

A good alternative is this:

find . -type f | xargs chmod -v 644

and for directories:

find . -type d | xargs chmod -v 755

and to be more explicit:

find . -type f | xargs -I{} chmod -v 644 {}

Should I use alias or alias_method?

The rubocop gem contributors propose in their Ruby Style Guide:

Prefer alias when aliasing methods in lexical class scope as the resolution of self in this context is also lexical, and it communicates clearly to the user that the indirection of your alias will not be altered at runtime or by any subclass unless made explicit.

class Westerner
  def first_name
   @names.first
  end

 alias given_name first_name
end

Always use alias_method when aliasing methods of modules, classes, or singleton classes at runtime, as the lexical scope of alias leads to unpredictability in these cases

module Mononymous
  def self.included(other)
    other.class_eval { alias_method :full_name, :given_name }
  end
end

class Sting < Westerner
  include Mononymous
end

How to get a .csv file into R?

As Dirk said, the function you are after is 'read.csv' or one of the other read.table variants. Given your sample data above, I think you will want to do something like this:

setwd("c:/random/directory")

df <- read.csv("myRandomFile.csv", header=TRUE)

All we did in the above was set the directory to where your .csv file is and then read the .csv into a dataframe named df. You can check that the data loaded properly by checking the structure of the object with:

str(df)

Assuming the data loaded properly, you can think go on to perform any number of statistical methods with the data in your data frame. I think summary(df) would be a good place to start. Learning how to use the help in R will be immensely useful, and a quick read through the help on CRAN will save you lots of time in the future: http://cran.r-project.org/

What is so bad about singletons?

There is nothing inherently wrong with the pattern, assuming it is being used for some aspect of your model which is truly single.

I believe the backlash is due to its overuse which, in turn, is due to the fact that it's the easiest pattern to understand and implement.

Inject service in app.config

You can use $inject service to inject a service in you config

app.config(function($provide){

    $provide.decorator("$exceptionHandler", function($delegate, $injector){
        return function(exception, cause){
            var $rootScope = $injector.get("$rootScope");
            $rootScope.addError({message:"Exception", reason:exception});
            $delegate(exception, cause);
        };
    });

});

Source: http://odetocode.com/blogs/scott/archive/2014/04/21/better-error-handling-in-angularjs.aspx

Proper way to use **kwargs in Python

Here's another approach:

def my_func(arg1, arg2, arg3):
    ... so something ...

kwargs = {'arg1': 'Value One', 'arg2': 'Value Two', 'arg3': 'Value Three'}
# Now you can call the function with kwargs like this:

my_func(**kwargs)

How to convert a ruby hash object to JSON?

You should include json in your file

For Example,

require 'json'

your_hash = {one: "1", two: "2"}
your_hash.to_json

For more knowledge about json you can visit below link. Json Learning

Authenticate with GitHub using a token

First, you need to create a personal access token (PAT). This is described here: https://help.github.com/articles/creating-an-access-token-for-command-line-use/

Laughably, the article tells you how to create it, but gives absolutely no clue what to do with it. After about an hour of trawling documentation and Stack Overflow, I finally found the answer:

$ git clone https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>

I was actually forced to enable two-factor authentication by company policy while I was working remotely and still had local changes, so in fact it was not clone I needed, but push. I read in lots of places that I needed to delete and recreate the remote, but in fact my normal push command worked exactly the same as the clone above, and the remote did not change:

$ git push https://github.com/user-or-organisation/myrepo.git
Username: <my-username>
Password: <my-personal-access-token>

(@YMHuang put me on the right track with the documentation link.)

What is an 'undeclared identifier' error and how do I fix it?

These error meassages

1.For the Visual Studio compiler: error C2065: 'printf' : undeclared identifier
2.For the GCC compiler: `printf' undeclared (first use in this function)

mean that you use name printf but the compiler does not see where the name was declared and accordingly does not know what it means.

Any name used in a program shall be declared before its using. The compiler has to know what the name denotes.

In this particular case the compiler does not see the declaration of name printf . As we know (but not the compiler) it is the name of standard C function declared in header <stdio.h> in C or in header <cstdio> in C++ and placed in standard (std::) and global (::) (not necessarily) name spaces.

So before using this function we have to provide its name declaration to the compiler by including corresponding headers.

For example C:

#include <stdio.h>

int main( void )
{
   printf( "Hello World\n" );
}

C++:

#include <cstdio>

int main()
{
   std::printf( "Hello World\n" );
   // or printf( "Hello World\n" );
   // or ::printf( "Hello World\n" );
}

Sometimes the reason of such an error is a simple typo. For example let's assume that you defined function PrintHello

void PrintHello()
{
    std::printf( "Hello World\n" );
}

but in main you made a typo and instead of PrintHello you typed printHello with lower case letter 'p'.

#include <cstdio>

void PrintHello()
{
    std::printf( "Hello World\n" );
}

int main()
{
   printHello();
}

In this case the compiler will issue such an error because it does not see the declaration of name printHello. PrintHello and printHello are two different names one of which was declared and other was not declared but used in the body of main

jquery get height of iframe content when loaded

I found the following to work on Chrome, Firefox and IE11:

$('iframe').load(function () {
    $('iframe').height($('iframe').contents().height());
});

When the Iframes content is done loading the event will fire and it will set the IFrames height to that of its content. This will only work for pages within the same domain as that of the IFrame.

Java: Casting Object to Array type

What you've got (according to the debug image) is an object array containing a string array. So you need something like:

Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];

You haven't shown the type of values - if this is already Object[] then you could just use (String[])values[0].

Of course even with the cast to Object[] you could still do it in one statement, but it's ugly:

String[] strings = (String[]) ((Object[])values)[0];

How to print the current Stack Trace in .NET without any exception?

You can also do this in the Visual Studio debugger without modifying the code.

  1. Create a breakpoint where you want to see the stack trace.
  2. Right-click the breakpoint and select "Actions..." in VS2015. In VS2010, select "When Hit...", then enable "Print a message".
  3. Make sure "Continue execution" is selected.
  4. Type in some text you would like to print out.
  5. Add $CALLSTACK wherever you want to see the stack trace.
  6. Run the program in the debugger.

Of course, this doesn't help if you're running the code on a different machine, but it can be quite handy to be able to spit out a stack trace automatically without affecting release code or without even needing to restart the program.

How to round a floating point number up to a certain decimal place?

If you round 8.8333333333339 to 2 decimals, the correct answer is 8.83, not 8.84. The reason you got 8.83000000001 is because 8.83 is a number that cannot be correctly reprecented in binary, and it gives you the closest one. If you want to print it without all the zeros, do as VGE says:

print "%.2f" % 8.833333333339   #(Replace number with the variable?)

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

Convert string to variable name in python

This is the best way, I know of to create dynamic variables in python.

my_dict = {}
x = "Buffalo"
my_dict[x] = 4

I found a similar, but not the same question here Creating dynamically named variables from user input

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

How to have click event ONLY fire on parent DIV, not children?

There's another way that works if you don't mind only targeting newer browsers. Just add the CSS

pointer-events: none;

to any children of the div you want to capture the click. Here's the support tables

http://caniuse.com/#feat=pointer-events

open link in iframe

Assuming the iFrame has a name attribute of "myIframe":

<a href="http://www.google.com" target="myIframe">Link Text</a> 

You can also accomplish this with the use of Javascript. The iFrame has a src attribute which specifies the location it shows. As such, it's a simple matter of binding the click of a link to changing that src attribute.

Change first commit of project with Git?

If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?

And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful http://git-scm.com/book/en/Git-Tools-Rewriting-History

Typescript empty object for a typed variable

user: USER

this.user = ({} as USER)

Simple way to query connected USB devices info in Python?

If you just need the name of the device here is a little hack which i wrote in bash. To run it in python you need the following snippet. Just replace $1 and $2 with Bus number and Device number eg 001 or 002.

import os
os.system("lsusb | grep \"Bus $1 Device $2\" | sed 's/\// /' | awk '{for(i=7;i<=NF;++i)print $i}'")

Alternately you can save it as a bash script and run it from there too. Just save it as a bash script like foo.sh make it executable.

#!/bin/bash
myvar=$(lsusb | grep "Bus $1 Device $2" | sed 's/\// /' | awk '{for(i=7;i<=NF;++i)print $i}')
echo $myvar

Then call it in python script as

import os
os.system('foo.sh')

How to decode viewstate

You can ignore the URL field and simply paste the viewstate into the Viewstate string box.

It does look like you have an old version; the serialisation methods changed in ASP.NET 2.0, so grab the 2.0 version

Write a formula in an Excel Cell using VBA

The correct character to use in this case is a full colon (:), not a semicolon (;).

How can I switch themes in Visual Studio 2012

Try the steps in here: If you don't have Visual Studio 2010 installed, some icons are provided.

http://supunlivera.blogspot.com/2012/09/visual-studio-2012-theme-change-get-vs.html

number of values in a list greater than a certain number

I'll add a map and filter version because why not.

sum(map(lambda x:x>5, j))
sum(1 for _ in filter(lambda x:x>5, j))

Performing user authentication in Java EE / JSF using j_security_check

The issue HttpServletRequest.login does not set authentication state in session has been fixed in 3.0.1. Update glassfish to the latest version and you're done.

Updating is quite straightforward:

glassfishv3/bin/pkg set-authority -P dev.glassfish.org
glassfishv3/bin/pkg image-update

Does return stop a loop?

Yes, once the return statement is executed, the entire function is exited at that very point.

Just imagine what would happen if it did not and continued looping, and executing that return statement each time? It would invalidate it's meaning of returning a value when you think about it.

Get full query string in C# ASP.NET

Try Request.Url.Query if you want the raw querystring as a string.

Regex for parsing directory and filename

Try this:

^(.+)\/([^\/]+)$

EDIT: escaped the forward slash to prevent problems when copy/pasting the Regex

PHP PDO returning single row

Did you try:

$DBH = new PDO( "connection string goes here" );
$row = $DBH->query( "select figure from table1" )->fetch();
echo $row["figure"];
$DBH = null;

Transparent CSS background color

To achieve it, you have to modify the background-color of the element.

Ways to create a (semi-) transparent color:

  • The CSS color name transparent creates a completely transparent color.

    Usage:

      .transparent{
        background-color: transparent;
      }
    
  • Using rgba or hsla color functions, that allow you to add the alpha channel (opacity) to the rgb and hsl functions. Their alpha values range from 0 - 1.

    Usage:

      .semi-transparent-yellow{
        background-color: rgba(255, 255, 0, 0.5);
      }
      .transparent{
        background-color:  hsla(0, 0%, 0%, 0);
      }
    
  • Besides the already mentioned solutions, you can also use the HEX format with alpha value (#RRGGBBAA or #RGBA notation).

    That's pretty new (contained by CSS Color Module Level 4), but already implemented in larger browsers (sorry, no IE).

    This differs from the other solutions, as this treats the alpha channel (opacity) as a hexadecimal value as well, making it range from 0 - 255 (FF).

    Usage:

      .semi-transparent-yellow{
        background-color: #FFFF0080;
      }
      .transparent{
        background-color: #0000;
      }
    

You can try them out as well:

  • transparent:

_x000D_
_x000D_
div {
  position: absolute;
  top: 50px;
  left: 100px;
  height: 100px;
  width: 200px;
  text-align: center;
  line-height: 100px;
  border: 1px dashed grey;
  
  background-color: transparent;
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
  Using `transparent`
</div>
_x000D_
_x000D_
_x000D_

  • rgba():

_x000D_
_x000D_
div {
  position: absolute;
  top: 50px;
  left: 100px;
  height: 100px;
  width: 200px;
  text-align: center;
  line-height: 100px;
  border: 1px dashed grey;
  
  background-color: rgba(0, 255, 0, 0.3);
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
  Using `rgba()`
</div>
_x000D_
_x000D_
_x000D_

  • #RRGGBBAA:

_x000D_
_x000D_
div {
  position: absolute;
  top: 50px;
  left: 100px;
  height: 100px;
  width: 200px;
  text-align: center;
  line-height: 100px;
  border: 1px dashed grey;
  
  background-color: #FF000060
}
_x000D_
<img src="https://via.placeholder.com/200x100">
<div>
  Using `#RRGGBBAA`
</div>
_x000D_
_x000D_
_x000D_

How to get absolute value from double - c-language

I have found that using cabs(double), cabsf(float), cabsl(long double), __cabsf(float), __cabs(double), __cabsf(long double) is the solution

How to shift a column in Pandas DataFrame

Lets define the dataframe from your example by

>>> df = pd.DataFrame([[206, 214], [226, 234], [245, 253], [265, 272], [283, 291]], 
    columns=[1, 2])
>>> df
     1    2
0  206  214
1  226  234
2  245  253
3  265  272
4  283  291

Then you could manipulate the index of the second column by

>>> df[2].index = df[2].index+1

and finally re-combine the single columns

>>> pd.concat([df[1], df[2]], axis=1)
       1      2
0  206.0    NaN
1  226.0  214.0
2  245.0  234.0
3  265.0  253.0
4  283.0  272.0
5    NaN  291.0

Perhaps not fast but simple to read. Consider setting variables for the column names and the actual shift required.

Edit: Generally shifting is possible by df[2].shift(1) as already posted however would that cut-off the carryover.

jQuery's .on() method combined with the submit event

The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:

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

createNewForm();

// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);

Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:

function bindItems(){
    $('form').off('submit').on('submit',doFormStuff); 
    $('button').off('click').on('click',doButtonStuff);
}   

So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.

createNewButton();
bindItems();

I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.

Accessing all items in the JToken

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

Then you can call its something like this...

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info

Can you use CSS to mirror/flip text?

There's also the rotateY for a real mirror one:

transform: rotateY(180deg);

Which, perhaps, is even more clear and understandable.

EDIT: Doesn't seem to work on Opera though… sadly. But it works fine on Firefox. I guess it might required to implicitly say that we are doing some kind of translate3d perhaps? Or something like that.

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

How to extract code of .apk file which is not working?

Note: All of the following instructions apply universally (aka to all OSes) unless otherwise specified.


Prerequsites

You will need:

  • A working Java installation
  • A working terminal/command prompt
  • A computer
  • An APK file

Steps

Step 1: Changing the file extension of the APK file

  1. Change the file extension of the .apk file by either adding a .zip extension to the filename, or to change .apk to .zip.

    For example, com.example.apk becomes com.example.zip, or com.example.apk.zip. Note that on Windows and macOS, it may prompt you whether you are sure you want to change the file extension. Click OK or Add if you're using macOS:

macOS add extension confirm dialog

Step 2: Extracting Java files from APK

  1. Extract the renamed APK file in a specific folder. For example, let that folder be demofolder.

    • If it didn't work, try opening the file in another application such as WinZip or 7-Zip.

    • For macOS, you can try running unzip in Terminal (available at /Applications/Terminal.app), where it takes one or more arguments: the file to unzip + optional arguments. See man unzip for documentation and arguments.

  2. Download dex2jar (see all releases on GitHub) and extract that zip file in the same folder as stated in the previous point.

  3. Open command prompt (or a terminal) and change your current directory to the folder created in the previous point and type the command d2j-dex2jar.bat classes.dex and press enter. This will generate classes-dex2jar.jar file in the same folder.

    • macOS/Linux users: Replace d2j-dex2jar.bat with d2j-dex2jar.sh. In other words, run d2j-jar2dex.sh classes.dex in the terminal and press enter.
  4. Download Java Decompiler (see all releases on Github) and extract it and start (aka double click) the executable/application.

  5. From the JD-GUI window, either drag and drop the generated classes-dex2jar.jar file into it, or go to File > Open File... and browse for the jar.

  6. Next, in the menu, go to File > Save All Sources (Windows: Ctrl+Alt+S, macOS: ?+?+S). This should open a dialog asking you where to save a zip file named `classes-dex2jar.jar.src.zip" consisting of all packages and java files. (You can rename the zip file to be saved)

  7. Extract that zip file (classes-dex2jar.jar.src.zip) and you should get all java files of the application.

Step 3: Getting xml files from APK

  • For more info, see the apktool website for installation instructions and more
  • Windows:

    1. Download the wrapper script (optional) and the apktool jar (required) and place it in the same folder (for example, myxmlfolder).
    2. Change your current directory to the myxmlfolder folder and rename the apktool jar file to apktool.jar.
    3. Place the .apk file in the same folder (i.e myxmlfolder).
    4. Open the command prompt (or terminal) and change your current directory to the folder where apktool is stored (in this case, myxmlfolder). Next, type the command apktool if framework-res.apk.

      What we're doing here is that we are installing a framework. For more info, see the docs.

    5. The above command should result in "Framework installed ..."
    6. In the command prompt, type the command apktool d filename.apk (where filename is the name of apk file). This should decode the file. For more info, see the docs.

      This should result in a folder filename.out being outputted, where filename is the original name of the apk file without the .apk file extension. In this folder are all the XML files such as layout, drawables etc.

Source: How to get source code from APK file - Comptech Blogspot

Android: How can I validate EditText input?

If you want nice validation popups and images when an error occurs you can use the setError method of the EditText class as I describe here

Screenshot of the use of setError taken from Donn Felker, the author of the linked post

relative path to CSS file

You have to move the css folder into your web folder. It seems that your web folder on the hard drive equals the /ServletApp folder as seen from the www. Other content than inside your web folder cannot be accessed from the browsers.

The url of the CSS link is then

 <link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>

How do I set a cookie on HttpClient's HttpRequestMessage

The accepted answer is the correct way to do this in most cases. However, there are some situations where you want to set the cookie header manually. Normally if you set a "Cookie" header it is ignored, but that's because HttpClientHandler defaults to using its CookieContainer property for cookies. If you disable that then by setting UseCookies to false you can set cookie headers manually and they will appear in the request, e.g.

var baseAddress = new Uri("http://example.com");
using (var handler = new HttpClientHandler { UseCookies = false })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var message = new HttpRequestMessage(HttpMethod.Get, "/test");
    message.Headers.Add("Cookie", "cookie1=value1; cookie2=value2");
    var result = await client.SendAsync(message);
    result.EnsureSuccessStatusCode();
}

How to use Python's pip to download and keep the zipped files for a package?

Use pip download <package1 package2 package n> to download all the packages including dependencies

Use pip install --no-index --find-links . <package1 package2 package n> to install all the packages including dependencies. It gets all the files from CWD. It will not download anything

Creating a data frame from two vectors using cbind

Vectors and matrices can only be of a single type and cbind and rbind on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.

(Note that in your rbind example, the promotion happens within the c call:

> c(10, "[]", "[[1,2]]")
[1] "10"      "[]"      "[[1,2]]"

If you want a rectangular structure where the columns can be different types, you want a data.frame. Any of the following should get you what you want:

> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
  v1 v2      v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ v1: num  10 20
 $ v2: Factor w/ 1 level "[]": 1 1
 $ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using specifically the data.frame version of cbind)

> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c(10, 20)              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using cbind, but making the first a data.frame so that it combines as data.frames do):

> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c.10..20.              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

How to get the previous url using PHP

Use the $_SERVER['HTTP_REFERER'] header, but bear in mind anybody can spoof it at anytime regardless of whether they clicked on a link.

Genymotion error at start 'Unable to load virtualbox'

Try closing Android Studio/Eclipse if it's open. It worked for me.

Java 8 lambdas, Function.identity() or t->t

As of the current JRE implementation, Function.identity() will always return the same instance while each occurrence of identifier -> identifier will not only create its own instance but even have a distinct implementation class. For more details, see here.

The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x, equivalent to return identifier;) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.

So using Function.identity() instead of x -> x might save some memory but that shouldn’t drive your decision if you really think that x -> x is more readable than Function.identity().

You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function instance while debugging. In contrast, when encountering the instance returned by Function.identity() during debugging an operation, you won’t know who has called that method and passed the instance to the operation.

Reverse of JSON.stringify?

http://jsbin.com/tidob/1/edit?js,console,output

The native JSON object includes two key methods.

1. JSON.parse()
2. JSON.stringify() 
  1. The JSON.parse() method parses a JSON string - i.e. reconstructing the original JavaScript object

    var jsObject = JSON.parse(jsonString);

  2. JSON.stringify() method accepts a JavaScript object and returns its JSON equivalent.

    var jsonString = JSON.stringify(jsObject);

What does the symbol \0 mean in a string-literal?

What is the length of str array, and with how much 0s it is ending?

Let's find out:

int main() {
  char str[] = "Hello\0";
  int length = sizeof str / sizeof str[0];
  // "sizeof array" is the bytes for the whole array (must use a real array, not
  // a pointer), divide by "sizeof array[0]" (sometimes sizeof *array is used)
  // to get the number of items in the array
  printf("array length: %d\n", length);
  printf("last 3 bytes: %02x %02x %02x\n",
         str[length - 3], str[length - 2], str[length - 1]);
  return 0;
}

Could not reliably determine the server's fully qualified domain name

  1. sudo vim /etc/apache2/httpd.conf
  2. Insert the following line at the httpd.conf: ServerName localhost
  3. Just restart the Apache: sudo /etc/init.d/apache2 restart

Display alert message and redirect after click on accept

echo "<script>
alert('There are no fields to generate a report');
window.location.href='admin/ahm/panel';
</script>";

and get rid of redirect line below.

You were mixing up two different worlds.

How to sort an ArrayList in Java

Use a Comparator like this:

List<Fruit> fruits= new ArrayList<Fruit>();

Fruit fruit;
for(int i = 0; i < 100; i++)
{
  fruit = new Fruit();
  fruit.setname(...);
  fruits.add(fruit);
}

// Sorting
Collections.sort(fruits, new Comparator<Fruit>() {
        @Override
        public int compare(Fruit fruit2, Fruit fruit1)
        {

            return  fruit1.fruitName.compareTo(fruit2.fruitName);
        }
    });

Now your fruits list is sorted based on fruitName.

Watch multiple $scope attributes

Starting from AngularJS 1.3 there's a new method called $watchGroup for observing a set of expressions.

$scope.foo = 'foo';
$scope.bar = 'bar';

$scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
  // newValues array contains the current values of the watch expressions
  // with the indexes matching those of the watchExpression array
  // i.e.
  // newValues[0] -> $scope.foo 
  // and 
  // newValues[1] -> $scope.bar 
});

how to filter out a null value from spark dataframe

A good solution for me was to drop the rows with any null values:

Dataset<Row> filtered = df.filter(row => !row.anyNull);

In case one is interested in the other case, just call row.anyNull. (Spark 2.1.0 using Java API)

Javascript: Extend a Function

There are several ways to go about this, it depends what your purpose is, if you just want to execute the function as well and in the same context, you can use .apply():

function init(){
  doSomething();
}
function myFunc(){
  init.apply(this, arguments);
  doSomethingHereToo();
}

If you want to replace it with a newer init, it'd look like this:

function init(){
  doSomething();
}
//anytime later
var old_init = init;
init = function() {
  old_init.apply(this, arguments);
  doSomethingHereToo();
};

How do I get the function name inside a function in PHP?

The accurate way is to use the __FUNCTION__ predefined magic constant.

Example:

class Test {
    function MethodA(){
        echo __FUNCTION__;
    }
}

Result: MethodA.

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

Find records with a date field in the last 24 hours

SELECT * FROM news WHERE date < DATEADD(Day, -1, date)

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

Maintain aspect ratio of div but fill screen width and height in CSS?

Use a CSS media query @media together with the CSS viewport units vw and vh to adapt to the aspect ratio of the viewport. This has the benefit of updating other properties, like font-size, too.

This fiddle demonstrates the fixed aspect ratio for the div, and the text matching its scale exactly.

Initial size is based on full width:

div {
  width: 100vw; 
  height: calc(100vw * 9 / 16);

  font-size: 10vw;

  /* align center */
  margin: auto;
  position: absolute;
  top: 0px; right: 0px; bottom: 0px; left: 0px;

  /* visual indicators */
  background:
    url(data:image/gif;base64,R0lGODlhAgAUAIABAB1ziv///yH5BAEAAAEALAAAAAACABQAAAIHhI+pa+EPCwA7) repeat-y center top,
    url(data:image/gif;base64,R0lGODlhFAACAIABAIodZP///yH5BAEAAAEALAAAAAAUAAIAAAIIhI8Zu+nIVgEAOw==) repeat-x left center,
    silver;
}

Then, when the viewport is wider than the desired aspect ratio, switch to height as base measure:

/* 100 * 16/9 = 177.778 */
@media (min-width: 177.778vh) {
  div {
    height: 100vh;
    width: calc(100vh * 16 / 9);

    font-size: calc(10vh * 16 / 9);
  }
}

This is very similar in vein to the max-width and max-height approach by @Danield, just more flexible.

Check if Cell value exists in Column, and then get the value of the NEXT Cell

How about this?

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", INDIRECT(ADDRESS(MATCH(A1,B:B, 0), 3)))

The "3" at the end means for column C.

how do I get a new line, after using float:left?

Another approach that's a little more semantic is to have a UL defined as your total 6 image width, each LI defined as float left and width defined - so that when LI #7 hits, it runs into the boundry of the UL, and is pushed down to the new row. You'll still have an open float that you'll want to clear after the /UL - but that can be done on the next element of the page, or as a clear div. Here's sort of the idea, you may have to mess with actual values, but this should give you the idea. The code is a little cleaner.

 <style type="text/css"> 
ul#imageSet { width: 600px; margin: 0; padding:0; }
ul#imageSet li { float: left; width: 100px;  height: 188px; margin: 0; padding:0; position: relative; list-style-type: none; }
.cornerimage { position: absolute; bottom: 0; right: 0; } 
h3.nextelement { clear: both; }
</style>


<ul id="imageSet">
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
     <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
</ul>


<h3 class="nextelement">Next Element in Doc</h3>

jQuery-- Populate select from json

fiddle

var $select = $('#down'); 
$select.find('option').remove();  
$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});