Programs & Examples On #Application security

How to import Angular Material in project?

Import all Angular Material modules in Angular 9.

Create material.module.ts file in your_project/src/app/ directory and paste this code.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';


import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatMenuModule } from '@angular/material/menu';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatBadgeModule } from '@angular/material/badge';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatListModule } from '@angular/material/list';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatCardModule } from '@angular/material/card';
import { MatStepperModule } from '@angular/material/stepper';
import { MatTabsModule } from '@angular/material/tabs';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatChipsModule } from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatDialogModule } from '@angular/material/dialog';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatSortModule } from '@angular/material/sort';
import { MatPaginatorModule } from '@angular/material/paginator';


@NgModule( {
    imports: [
        CommonModule,
        BrowserAnimationsModule,
        MatCheckboxModule,
        MatCheckboxModule,
        MatButtonModule,
        MatInputModule,
        MatAutocompleteModule,
        MatDatepickerModule,
        MatFormFieldModule,
        MatRadioModule,
        MatSelectModule,
        MatSliderModule,
        MatSlideToggleModule,
        MatMenuModule,
        MatSidenavModule,
        MatBadgeModule,
        MatToolbarModule,
        MatListModule,
        MatGridListModule,
        MatCardModule,
        MatStepperModule,
        MatTabsModule,
        MatExpansionModule,
        MatButtonToggleModule,
        MatChipsModule,
        MatIconModule,
        MatProgressSpinnerModule,
        MatProgressBarModule,
        MatDialogModule,
        MatTooltipModule,
        MatSnackBarModule,
        MatTableModule,
        MatSortModule,
        MatPaginatorModule

    ],
    exports: [
        MatButtonModule,
        MatToolbarModule,
        MatIconModule,
        MatSidenavModule,
        MatBadgeModule,
        MatListModule,
        MatGridListModule,
        MatInputModule,
        MatFormFieldModule,
        MatSelectModule,
        MatRadioModule,
        MatDatepickerModule,
        MatChipsModule,
        MatTooltipModule,
        MatTableModule,
        MatPaginatorModule
    ],
    providers: [
        MatDatepickerModule,
    ]
} )

export class AngularMaterialModule { }

How to add "Maven Managed Dependencies" library in build path eclipse?

You can install M2Eclipse and open the project as maven project in Eclipse. It will create the necessary configuration and entries.

This is also useful for subsequent updates to the pom. With maven eclipse plugin, you will need to manually regenerate the eclipse configuration for each changes.

Finding moving average from data points in Python

A moving average is a convolution, and numpy will be faster than most pure python operations. This will give you the 10 point moving average.

import numpy as np
smoothed = np.convolve(data, np.ones(10)/10)

I would also strongly suggest using the great pandas package if you are working with timeseries data. There are some nice moving average operations built in.

What is the equivalent of Java's final in C#?

The final keyword has several usages in Java. It corresponds to both the sealed and readonly keywords in C#, depending on the context in which it is used.

Classes

To prevent subclassing (inheritance from the defined class):

Java

public final class MyFinalClass {...}

C#

public sealed class MyFinalClass {...}

Methods

Prevent overriding of a virtual method.

Java

public class MyClass
{
    public final void myFinalMethod() {...}
}

C#

public class MyClass : MyBaseClass
{
    public sealed override void MyFinalMethod() {...}
}

As Joachim Sauer points out, a notable difference between the two languages here is that Java by default marks all non-static methods as virtual, whereas C# marks them as sealed. Hence, you only need to use the sealed keyword in C# if you want to stop further overriding of a method that has been explicitly marked virtual in the base class.

Variables

To only allow a variable to be assigned once:

Java

public final double pi = 3.14; // essentially a constant

C#

public readonly double pi = 3.14; // essentially a constant

As a side note, the effect of the readonly keyword differs from that of the const keyword in that the readonly expression is evaluated at runtime rather than compile-time, hence allowing arbitrary expressions.

How to get last key in an array?

Just use : echo $array[count($array) - 1];

Div 100% height works on Firefox but not in IE

I've been successful in getting this to work when I set the margins of the container to 0:

#container
{
   margin: 0 px;
}

in addition to all your other styles

How to get Selected Text from select2 when using <input>

This one is working fine using V 4.0.3

var vv = $('.mySelect2');     
var label = $(vv).children("option[value='"+$(vv).select2("val")+"']").first().html();
console.log(label); 

Using "label for" on radio buttons

You almost got it. It should be this:

_x000D_
_x000D_
<input type="radio" name="group1" id="r1" value="1" />_x000D_
<label for="r1"> button one</label>
_x000D_
_x000D_
_x000D_

The value in for should be the id of the element you are labeling.

Pure CSS to make font-size responsive based on dynamic amount of characters

calc(42px + (60 - 42) * (100vw - 768px) / (1440 - 768));

use this equation.

For anything larger or smaller than 1440 and 768, you can either give it a static value, or apply the same approach.

The drawback with vw solution is that you cannot set a scale ratio, say a 5vw at screen resolution 1440 may ended up being 60px font-size, your idea font size, but when you shrink the window width down to 768, it may ended up being 12px, not the minimal you want. With this approach, you can set your upper boundary and lower boundary, and the font will scale itself in between.

How to return the output of stored procedure into a variable in sql server

Use this code, Working properly

CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT

AS
Begin
 DECLARE @cnt int;
 DECLARE @status int =0;
 SET NOCOUNT OFF
 SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
 if(@cnt = 1)
   Begin
     return @status;
   End
 else
  Begin
   SET @status =1;
    return @status;
 End
END

Execute SP

DECLARE @statuss bit;
EXECUTE  [dbo].[sp_delete_item] 6, @statuss output;
PRINT @statuss;

Recommended SQL database design for tags or tagging

I would suggest following design : Item Table: Itemid, taglist1, taglist2
this will be fast and make easy saving and retrieving the data at item level.

In parallel build another table: Tags tag do not make tag unique identifier and if you run out of space in 2nd column which contains lets say 100 items create another row.

Now while searching for items for a tag it will be super fast.

Getting date format m-d-Y H:i:s.u from milliseconds

I benched a few different ways:

1) microtime + sscanf + date:

sscanf(microtime(), '0.%6s00 %s', $usec, $sec);
$date = date('Y-m-d H:i:s.', $sec) . $usec;

I'm not sure why microtime() returns 10 chars (0.dddddd00) for the microseconds part but maybe someone can tell me ?

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { sscanf(microtime(), '0.%6s00 %s', $usec, $sec); $date = date('Y-m-d H:i:s.', $sec) . $usec; } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "22372.335910797 ms" // macOS PHP 5.6.30
string(18) "16772.964000702 ms" // Linux PHP 5.4.16
string(18) "10382.229089737 ms" // Linux PHP 7.3.11 (same linux box as above)

2) DateTime::createFromFormat + Datetime->format:

$now = new DateTime('NOW');
$date = $now->format('Y-m-d H:i:s.u');

not working in PHP 5.x ...

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $now = new DateTime('NOW'); $date = $now->format('Y-m-d H:i:s.u'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "45801.825046539 ms" // macOS PHP 5.6.30 (ms not working)
string(18) "21180.155038834 ms" // Linux PHP 5.4.16 (ms not working)
string(18) "11879.796028137 ms" // Linux PHP 7.3.11 (same linux box as above)

3) gettimeofday + date:

$time = gettimeofday();
$date = date('Y-m-d H:i:s.', $time['sec']) . $time['usec'];

-

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $time = gettimeofday(); $date = date('Y-m-d H:i:s.', $time['sec']) . $time['usec']; } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "23706.788063049 ms" // macOS PHP 5.6.30
string(18) "14984.534025192 ms" // Linux PHP 5.4.16
string(18) "7799.1390228271 ms" // Linux PHP 7.3.11 (same linux box as above)

4) microtime + number_format + DateTime::createFromFormat + DateTime->format:

$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));
$date = $now->format('Y-m-d H:i:s.u');

-

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', '')); $date = $now->format('Y-m-d H:i:s.u'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "83326.496124268 ms" // macOS PHP 5.6.30
string(18) "61982.603788376 ms" // Linux PHP 5.4.16
string(16) "19107.1870327 ms" // Linux PHP 7.3.11 (same linux box as above)

5) microtime + sprintf + DateTime::createFromFormat + DateTime->format:

$now = DateTime::createFromFormat('U.u', sprintf('%.6f', microtime(true)));
$date = $now->format('Y-m-d H:i:s.u');

-

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $now = DateTime::createFromFormat('U.u', sprintf('%.6f', microtime(true))); $date = $now->format('Y-m-d H:i:s.u'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "79387.331962585 ms" // macOS PHP 5.6.30
string(18) "60734.437942505 ms" // Linux PHP 5.4.16
string(18) "18594.941139221 ms" // Linux PHP 7.3.11 (same linux box as above)

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

it's well documented here:

https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6

How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:

http://tomcat.apache.org/tomcat-7.0-doc/config/http.html

Standard Implementation -> address

"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."

Intellij Cannot resolve symbol on import

I found the source cause!

In my case, I add a jar file include some java source file, but I think the java source is bad, in Intellij Idea dependency library it add the source automatic, so in Editor the import is BAD, JUST remove the source code in "Project Structure" -> "Library", it works for me.

Pygame mouse clicking detection

The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event.

Use the rect attribute of the pygame.sprite.Sprite object and the collidepoint method to see if the Sprite was clicked. Pass the list of events to the update method of the pygame.sprite.Group so that you can process the events in the Sprite class:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseClick

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.click_image, color, (25, 25), 25)
        pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.clicked = False

    def update(self, event_list):
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    self.clicked = not self.clicked

        self.image = self.click_image if self.clicked else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

See further Creating multiple sprites with different update()'s from the same sprite class in Pygame


The current position of the mouse can be determined via pygame.mouse.get_pos(). The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed() returns a list of Boolean values ??that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.

Detect evaluate the mouse states in the Update method of the pygame.sprite.Sprite object:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        if  self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
            # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseHover

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.hover_image, color, (25, 25), 25)
        pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.hover = False

    def update(self):
        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        #self.hover = self.rect.collidepoint(mouse_pos)
        self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)

        self.image = self.hover_image if self.hover else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    group.update()

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

MySQL - select data from database between two dates

SELECT users.* FROM users WHERE created_at BETWEEN '2011-12-01' AND '2011-12-07';

How to create an Array, ArrayList, Stack and Queue in Java?

Just a small correction to the first answer in this thread.

Even for Stack, you need to create new object with generics if you are using Stack from java util packages.

Right usage:
    Stack<Integer> s = new Stack<Integer>();
    Stack<String> s1 = new Stack<String>();

    s.push(7);
    s.push(50);

    s1.push("string");
    s1.push("stack");

if used otherwise, as mentioned in above post, which is:

    /*
    Stack myStack = new Stack();
    // add any type of elements (String, int, etc..)
    myStack.push("Hello");
    myStack.push(1);
    */

Although this code works fine, has unsafe or unchecked operations which results in error.

Android ImageView's onClickListener does not work

Same Silly thing happed with me.

I just copied one activity and pasted. Defined in Manifest.

Open from MainActivity.java but I was forgot that Copied Activity is getting some params in bundle and If I don't pass any params, just finished.

So My Activity is getting started but finished at same moment.

I had written Toast and found this silly mistake. :P

How to debug apk signed for release?

Besides Manuel's way, you can still use the Manifest.

In Android Studio stable, you have to add the following 2 lines to application in the AndroidManifest file:

    android:debuggable="true"
    tools:ignore="HardcodedDebugMode"

The first one will enable debugging of signed APK, and the second one will prevent compile-time error.

After this, you can attach to the process via "Attach debugger to Android process" button.

How to create a zip archive of a directory in Python?

For anyone else delving into this question and trying to archive the very same directory their program is in and is getting both very deep tree structures and ending up with recursion due to the zip file zipping itself, try this.

It's a combination of Mark's answer and some extra checks to ensure that there's no recursive zipping of the zipfile itself, and no unnecessarily deep folder structures.

import os
import zipfile

def zipdir(path, ziph, ignored_directories, ignored_files):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
      for file in files:
        if not any(ignored_dir in root for ignored_dir in ignored_directories):
          if not any(ignored_fname in file for ignored_fname in ignored_files):
            ziph.write(os.path.join(root, file))

# current working directory
this_dir = os.path.dirname(os.path.abspath(__file__))

# the directory within the working directory the zip will be created in (build/archives).
zip_dest_dir = os.path.join('build', 'archives')

# verify zip_dest_dir exists: if not, create it
if not os.path.isdir(zip_dest_dir):
    os.makedirs(zip_dest_dir, exist_ok=True)

# leave zip_dest_dir blank (or set dist_dir = this_dir) if you want the zip file in the working directory (same directory as the script)
dest_dir = os.path.join(this_dir, zip_dest_dir)

# name the zip file: remember the file extension
zip_filename = 'zipped_directory.zip'

# zip file's path
zip_path = os.path.join(dest_dir, zip_filename)

# create the zipfile handle: you can change ZIP_STORED to any other compression algorithm of your choice, like ZIP_DEFLATED, if you need actual compression
zipf = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_STORED)

# ignored files and directories: I personally wanted to ignore the "build" directory, alongside with "node_modules", so those would be listed here.
ignored_dirs = []

# ignore any specific files: in my case, I was ignoring the script itself, so I'd include 'deploy.py' here
ignored_files = [zip_filename]

# zip directory contents
zipdir('.', zipf, ignored_dirs, ignored_files)
zipf.close()

The resulting zip file should only include directories starting from the working directory: so no Users/user/Desktop/code/.../working_directory/.../etc. kind of file structure.

Creating SVG elements dynamically with javascript inside HTML

To facilitate svg editing you can use an intermediate function:

function getNode(n, v) {
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v)
    n.setAttributeNS(null, p, v[p]);
  return n
}

Now you can write:

svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );

Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):

_x000D_
_x000D_
function getNode(n, v) {_x000D_
  n = document.createElementNS("http://www.w3.org/2000/svg", n);_x000D_
  for (var p in v)_x000D_
    n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);_x000D_
  return n_x000D_
}_x000D_
_x000D_
var svg = getNode("svg");_x000D_
document.body.appendChild(svg);_x000D_
_x000D_
var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });_x000D_
svg.appendChild(r);_x000D_
_x000D_
var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });_x000D_
svg.appendChild(r);
_x000D_
_x000D_
_x000D_

How to add a new row to datagridview programmatically

If you are binding a List

List<Student> student = new List<Student>();

dataGridView1.DataSource = student.ToList();
student .Add(new Student());

//Reset the Datasource
dataGridView1.DataSource = null;
dataGridView1.DataSource = student;

If you are binding DataTable

DataTable table = new DataTable();

 DataRow newRow = table.NewRow();

// Add the row to the rows collection.
table.Rows.Add(newRow);

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

It's looking for the file in the current directory.

First, go to that directory

cd /users/gcameron/Desktop/map

And then try to run it

python colorize_svg.py

How to Convert an int to a String?

Use the Integer class' static toString() method.

int sdRate=5;
text_Rate.setText(Integer.toString(sdRate));

String compare in Perl with "eq" vs "=="

Maybe the condition you are using is incorrect:

$str1 == "taste" && $str2 == "waste"

The program will enter into THEN part only when both of the stated conditions are true.

You can try with $str1 == "taste" || $str2 == "waste". This will execute the THEN part if anyone of the above conditions are true.

Multi-line strings in PHP

Another solution is to use output buffering, you can collect everything that is being outputted/echoed and store it in a variable.

<?php
ob_start(); 

?>line1
line2
line3<?php 

$xml = ob_get_clean();

Please note that output buffering might not be the best solution in terms of performance and code cleanliness for this exact case but worth leaving it here for reference.

ASP.NET MVC: Custom Validation by DataAnnotation

Background:

Model validations are required for ensuring that the received data we receive is valid and correct so that we can do the further processing with this data. We can validate a model in an action method. The built-in validation attributes are Compare, Range, RegularExpression, Required, StringLength. However we may have scenarios wherein we required validation attributes other than the built-in ones.

Custom Validation Attributes

public class EmployeeModel 
{
    [Required]
    [UniqueEmailAddress]
    public string EmailAddress {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int OrganizationId {get;set;}
}

To create a custom validation attribute, you will have to derive this class from ValidationAttribute.

public class UniqueEmailAddress : ValidationAttribute
{
    private IEmployeeRepository _employeeRepository;
    [Inject]
    public IEmployeeRepository EmployeeRepository
    {
        get { return _employeeRepository; }
        set
        {
            _employeeRepository = value;
        }
    }
    protected override ValidationResult IsValid(object value,
                        ValidationContext validationContext)
    {
        var model = (EmployeeModel)validationContext.ObjectInstance;
        if(model.Field1 == null){
            return new ValidationResult("Field1 is null");
        }
        if(model.Field2 == null){
            return new ValidationResult("Field2 is null");
        }
        if(model.Field3 == null){
            return new ValidationResult("Field3 is null");
        }
        return ValidationResult.Success;
    }
}

Hope this helps. Cheers !

References

Simple export and import of a SQLite database on Android

This is a simple method to export the database to a folder named backup folder you can name it as you want and a simple method to import the database from the same folder a

    public class ExportImportDB extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
//creating a new folder for the database to be backuped to
            File direct = new File(Environment.getExternalStorageDirectory() + "/Exam Creator");

               if(!direct.exists())
                {
                    if(direct.mkdir()) 
                      {
                       //directory is created;
                      }

                }
            exportDB();
            importDB();

        }
    //importing database
        private void importDB() {
            // TODO Auto-generated method stub

            try {
                File sd = Environment.getExternalStorageDirectory();
                File data  = Environment.getDataDirectory();

                if (sd.canWrite()) {
                    String  currentDBPath= "//data//" + "PackageName"
                            + "//databases//" + "DatabaseName";
                    String backupDBPath  = "/BackupFolder/DatabaseName";
                    File  backupDB= new File(data, currentDBPath);
                    File currentDB  = new File(sd, backupDBPath);

                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                    Toast.makeText(getBaseContext(), backupDB.toString(),
                            Toast.LENGTH_LONG).show();

                }
            } catch (Exception e) {

                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                        .show();

            }
        }
    //exporting database 
        private void exportDB() {
            // TODO Auto-generated method stub

            try {
                File sd = Environment.getExternalStorageDirectory();
                File data = Environment.getDataDirectory();

                if (sd.canWrite()) {
                    String  currentDBPath= "//data//" + "PackageName"
                            + "//databases//" + "DatabaseName";
                    String backupDBPath  = "/BackupFolder/DatabaseName";
                    File currentDB = new File(data, currentDBPath);
                    File backupDB = new File(sd, backupDBPath);

                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                    Toast.makeText(getBaseContext(), backupDB.toString(),
                            Toast.LENGTH_LONG).show();

                }
            } catch (Exception e) {

                Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                        .show();

            }
        }

    }

Dont forget to add this permission to proceed it

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
    </uses-permission>

Enjoy

How can I pass a parameter to a t-sql script?

SQL*Plus uses &1, &2... &n to access the parameters.

Suppose you have the following script test.sql:

SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off

you could call this script like this for example:

$ sqlplus login/pw @test Hello World!

Edit:

In a UNIX script you would usually call a SQL script like this:

sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF

so that your login/password won't be visible with another session's ps

Angular and debounce

Updated for RC.5

With Angular 2 we can debounce using RxJS operator debounceTime() on a form control's valueChanges observable:

import {Component}   from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable}  from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/throttleTime';
import 'rxjs/add/observable/fromEvent';

@Component({
  selector: 'my-app',
  template: `<input type=text [value]="firstName" [formControl]="firstNameControl">
    <br>{{firstName}}`
})
export class AppComponent {
  firstName        = 'Name';
  firstNameControl = new FormControl();
  formCtrlSub: Subscription;
  resizeSub:   Subscription;
  ngOnInit() {
    // debounce keystroke events
    this.formCtrlSub = this.firstNameControl.valueChanges
      .debounceTime(1000)
      .subscribe(newValue => this.firstName = newValue);
    // throttle resize events
    this.resizeSub = Observable.fromEvent(window, 'resize')
      .throttleTime(200)
      .subscribe(e => {
        console.log('resize event', e);
        this.firstName += '*';  // change something to show it worked
      });
  }
  ngDoCheck() { console.log('change detection'); }
  ngOnDestroy() {
    this.formCtrlSub.unsubscribe();
    this.resizeSub  .unsubscribe();
  }
} 

Plunker

The code above also includes an example of how to throttle window resize events, as asked by @albanx in a comment below.


Although the above code is probably the Angular-way of doing it, it is not efficient. Every keystroke and every resize event, even though they are debounced and throttled, results in change detection running. In other words, debouncing and throttling do not affect how often change detection runs. (I found a GitHub comment by Tobias Bosch that confirms this.) You can see this when you run the plunker and you see how many times ngDoCheck() is being called when you type into the input box or resize the window. (Use the blue "x" button to run the plunker in a separate window to see the resize events.)

A more efficient technique is to create RxJS Observables yourself from the events, outside of Angular's "zone". This way, change detection is not called each time an event fires. Then, in your subscribe callback methods, manually trigger change detection – i.e., you control when change detection is called:

import {Component, NgZone, ChangeDetectorRef, ApplicationRef, 
        ViewChild, ElementRef} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/throttleTime';
import 'rxjs/add/observable/fromEvent';

@Component({
  selector: 'my-app',
  template: `<input #input type=text [value]="firstName">
    <br>{{firstName}}`
})
export class AppComponent {
  firstName = 'Name';
  keyupSub:  Subscription;
  resizeSub: Subscription;
  @ViewChild('input') inputElRef: ElementRef;
  constructor(private ngzone: NgZone, private cdref: ChangeDetectorRef,
    private appref: ApplicationRef) {}
  ngAfterViewInit() {
    this.ngzone.runOutsideAngular( () => {
      this.keyupSub = Observable.fromEvent(this.inputElRef.nativeElement, 'keyup')
        .debounceTime(1000)
        .subscribe(keyboardEvent => {
          this.firstName = keyboardEvent.target.value;
          this.cdref.detectChanges();
        });
      this.resizeSub = Observable.fromEvent(window, 'resize')
        .throttleTime(200)
        .subscribe(e => {
          console.log('resize event', e);
          this.firstName += '*';  // change something to show it worked
          this.cdref.detectChanges();
        });
    });
  }
  ngDoCheck() { console.log('cd'); }
  ngOnDestroy() {
    this.keyupSub .unsubscribe();
    this.resizeSub.unsubscribe();
  }
} 

Plunker

I use ngAfterViewInit() instead of ngOnInit() to ensure that inputElRef is defined.

detectChanges() will run change detection on this component and its children. If you would rather run change detection from the root component (i.e., run a full change detection check) then use ApplicationRef.tick() instead. (I put a call to ApplicationRef.tick() in comments in the plunker.) Note that calling tick() will cause ngDoCheck() to be called.

Validation of file extension before uploading file

we can check it on submit or we can make change event of that control

var fileInput = document.getElementById('file');
    var filePath = fileInput.value;
    var allowedExtensions = /(\.jpeg|\.JPEG|\.gif|\.GIF|\.png|\.PNG)$/;
    if (filePath != "" && !allowedExtensions.exec(filePath)) {
    alert('Invalid file extention pleasse select another file');
    fileInput.value = '';
    return false;
    }

How to add parameters to HttpURLConnection using POST using NameValuePair

One solution is to make your own params string.

This is the actual method I've been using for my latest project. You need to change args from hashtable to namevaluepair's:

private static String getPostParamString(Hashtable<String, String> params) {
    if(params.size() == 0)
        return "";

    StringBuffer buf = new StringBuffer();
    Enumeration<String> keys = params.keys();
    while(keys.hasMoreElements()) {
        buf.append(buf.length() == 0 ? "" : "&");
        String key = keys.nextElement();
        buf.append(key).append("=").append(params.get(key));
    }
    return buf.toString();
}

POSTing the params:

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(getPostParamString(req.getPostParams()));

Android Studio suddenly cannot resolve symbols

I had a similar problem when I rebuilt an aar file and replaced the older one in my project with the new one. I went through all the solutions here and none solved my issue. I later realised that minifyEnabled had been set to true in the library project which effectively removed a lot of dead code that was not being used in the library project.

My solution was to set minifyEnabled to false in the library project, assemble the aar, copied it into my project, invalidated caches and synced the grade project and everything worked fine.

How do I auto-submit an upload form when a file is selected?

JavaScript with onchange event:

_x000D_
_x000D_
<form action="upload.php" method="post" enctype="multipart/form-data">_x000D_
     <input type="file" name="filename" onchange="javascript:this.form.submit();">_x000D_
</form>
_x000D_
_x000D_
_x000D_

jQuery .change() and .submit():

_x000D_
_x000D_
$('#fileInput').change(function() {_x000D_
  $('#myForm').submit();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
<form action="upload.php" id="myForm">_x000D_
     <input type="file" id="fileInput">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Dialog to pick image from gallery or from camera

I have merged some solutions to make a complete util for picking an image from Gallery or Camera. These are the features of ImagePicker util gist (also in a Github lib):

  • Merged intents for Gallery and Camera resquests.
  • Resize selected big images (e.g.: 2500 x 1600)
  • Rotate image if necesary

Screenshot:

ImagePicker starting intent

Edit: Here is a fragment of code to get a merged Intent for Gallery and Camera apps together. You can see the full code at ImagePicker util gist (also in a Github lib):

public static Intent getPickImageIntent(Context context) {
    Intent chooserIntent = null;

    List<Intent> intentList = new ArrayList<>();

    Intent pickIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePhotoIntent.putExtra("return-data", true);
    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
    intentList = addIntentsToList(context, intentList, pickIntent);
    intentList = addIntentsToList(context, intentList, takePhotoIntent);

    if (intentList.size() > 0) {
        chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
                context.getString(R.string.pick_image_intent_text));
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
    }

    return chooserIntent;
}

private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
    List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resInfo) {
        String packageName = resolveInfo.activityInfo.packageName;
        Intent targetedIntent = new Intent(intent);
        targetedIntent.setPackage(packageName);
        list.add(targetedIntent);
    }
    return list;
}

Get random item from array

Use PHP Rand function

<?php
  $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
  $rand_keys = array_rand($input, 2);
  echo $input[$rand_keys[0]] . "\n";
  echo $input[$rand_keys[1]] . "\n";
?>

More Help

Move SQL Server 2008 database files to a new folder location

To add the privileges needed to the files add and grant right to the following local user: SQLServerMSSQLUser$COMPUTERNAME$INSTANCENAME, where COMPUTERNAME and INSTANCENAME has to be replaced with name of computer and MSSQL instance respectively.

batch file Copy files with certain extensions from multiple directories into one directory

Just use the XCOPY command with recursive option

xcopy c:\*.doc k:\mybackup /sy

/s will make it "recursive"

Kill process by name?

this worked for me in windows 7

import subprocess
subprocess.call("taskkill /IM geckodriver.exe")

Add new item in existing array in c#.net

string str = "string ";
List<string> li_str = new List<string>();
    for (int k = 0; k < 100; i++ )
         li_str.Add(str+k.ToString());
string[] arr_str = li_str.ToArray();

Rotate image with javascript

var angle = 0;
$('#button').on('click', function() {
    angle += 90;
    $('#image').css('transform','rotate(' + angle + 'deg)');
});

Try this code.

Experimental decorators warning in TypeScript compilation

If you are using cli to compile *.ts files, you can set experimentalDecorators using the following command:

 tsc filename.ts --experimentalDecorators "true"

insert data into database using servlet and jsp in eclipse

String user = request.getParameter("uname");
out.println(user); 
String pass = request.getParameter("pass");
out.println(pass); 
Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;
out.println("hello");
Statement st = conn.createStatement();
String sql = "insert into login (user,pass) values('" + user + "','" + pass + "')";
st.executeUpdate(sql);

How to do a for loop in windows command line?

The commandline interpreter does indeed have a FOR construct that you can use from the command prompt or from within a batch file.

For your purpose, you probably want something like:

FOR %i IN (*.ext) DO my-function %i

Which will result in the name of each file with extension *.ext in the current directory being passed to my-function (which could, for example, be another .bat file).

The (*.ext) part is the "filespec", and is pretty flexible with how you specify sets of files. For example, you could do:

FOR %i IN (C:\Some\Other\Dir\*.ext) DO my-function %i

To perform an operation in a different directory.

There are scores of options for the filespec and FOR in general. See

HELP FOR

from the command prompt for more information.

How to print out the method name and line number and conditionally disable NSLog?

building on top of above answers, here is what I plagiarized and came up with. Also added memory logging.

#import <mach/mach.h>

#ifdef DEBUG
#   define DebugLog(fmt, ...) NSLog((@"%s(%d) " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DebugLog(...)
#endif


#define AlwaysLog(fmt, ...) NSLog((@"%s(%d) " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);


#ifdef DEBUG
#   define AlertLog(fmt, ...)  { \
    UIAlertView *alert = [[UIAlertView alloc] \
            initWithTitle : [NSString stringWithFormat:@"%s(Line: %d) ", __PRETTY_FUNCTION__, __LINE__]\
                  message : [NSString stringWithFormat : fmt, ##__VA_ARGS__]\
                 delegate : nil\
        cancelButtonTitle : @"Ok"\
        otherButtonTitles : nil];\
    [alert show];\
}
#else
#   define AlertLog(...)
#endif



#ifdef DEBUG
#   define DPFLog NSLog(@"%s(%d)", __PRETTY_FUNCTION__, __LINE__);//Debug Pretty Function Log
#else
#   define DPFLog
#endif


#ifdef DEBUG
#   define MemoryLog {\
    struct task_basic_info info;\
    mach_msg_type_number_t size = sizeof(info);\
    kern_return_t e = task_info(mach_task_self(),\
                                   TASK_BASIC_INFO,\
                                   (task_info_t)&info,\
                                   &size);\
    if(KERN_SUCCESS == e) {\
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; \
        [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; \
        DebugLog(@"%@ bytes", [formatter stringFromNumber:[NSNumber numberWithInteger:info.resident_size]]);\
    } else {\
        DebugLog(@"Error with task_info(): %s", mach_error_string(e));\
    }\
}
#else
#   define MemoryLog
#endif

Background color in input and text fields

You want to restrict to input fields that are of type text so use the selector input[type=text] rather than input (which will apply to all input fields (e.g. those of type submit as well)).

Merge development branch with master

I generally like to merge master into the development first so that if there are any conflicts, I can resolve in the development branch itself and my master remains clean.

(on branch development)$ git merge master
(resolve any merge conflicts if there are any)
git checkout master
git merge development (there won't be any conflicts now)

There isn't much of a difference in the two approaches, but I have noticed sometimes that I don't want to merge the branch into master yet, after merging them, or that there is still more work to be done before these can be merged, so I tend to leave master untouched until final stuff.

EDIT: From comments

If you want to keep track of who did the merge and when, you can use --no-ff flag while merging to do so. This is generally useful only when merging development into the master (last step), because you might need to merge master into development (first step) multiple times in your workflow, and creating a commit node for these might not be very useful.

git merge --no-ff development

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

Using setImageDrawable dynamically to set image in an ImageView

Construct a POJO.java class and create "constructor, getter & setter methods"

class POJO{
        public POJO(Drawable proImagePath) {
                setProductImagePath(proImagePath);
        }

        public Drawable getProductImagePath() {
                return productImagePath;
        }

        public void setProductImagePath(Drawable productImagePath) {
                this.productImagePath = productImagePath;
        }
}

Then setup the adapters through image drawable resources to CustomAdapter.java

    class CustomAdapter extends ArrayAdapter<POJO>{

       private ArrayList<POJO> cartList = new ArrayList<POJO>();
       public MyCartAdapter(Context context, int resource) {
          super(context, resource);
       }

       public MyCartAdapter(Context context, ArrayList<POJO> cartList) {
          super(context, 0, cartList);
          this.context = context;
          this.cartList = cartList;

       }

       @Override
       public View getView(int position, View convertView, ViewGroup parent) {
          /*
          *Here you can setup your layout and references.
          **/
          ImageView productImage = (ImageView) rootView.findViewById(R.id.cart_pro_image);
          productImage.setImageDrawable(POJO.getProductImagePath());
        }
    }

Then pass the references through ActivityClass.java

public class MyCartActivity extends AppCompatActivity{
       POJO pojo;
       CustomAdapter customAdapter;
       ArrayList<POJO> cartList = new ArrayList<POJO>();

       @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.your_layout);

          customAdapter = new CustomAdapter(this, cartList);

          pojo = new POJO(getResources().getDrawable(R.drawable.help_green));

    }
}

What is the difference between README and README.md in GitHub projects?

README.md or .mkdn or .markdown denotes that the file is markdown formatted. Markdown is a markup language. With it you can easily display headers or have italic words, or bold or almost anything that can be done to text

Are members of a C++ struct initialized to 0 by default?

I believe the correct answer is that their values are undefined. Often, they are initialized to 0 when running debug versions of the code. This is usually not the case when running release versions.

Folder is locked and I can't unlock it

This was the first time I had this issue. I even tried to restart PC, without effect. This solves my problem:

Solution for me:

  1. Right Click on Project Working Directory.
  2. Navigate TortoiseSVN.
  3. Navigate To Clean Up.
  4. Leave all default options, and check Break Locks
  5. Click OK

This works for me. I was able to commit changes.

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

Simply go to /opt/lampp/var/mysql

There You can find your database name. Open that folder. Remove if any files in it

Now come to phpmyadmin and drop that database

How to add link to flash banner

If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.

on (release) {
  getURL("http://someurl/");
}

To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.

I think it would go too far to explain into depth with pictures how to go about in stackoverflow.

How do I get the name of a Ruby class?

Both result.class.to_s and result.class.name work.

Adding values to a C# array

one approach is to fill an array via LINQ

if you want to fill an array with one element you can simply write

string[] arrayToBeFilled;
arrayToBeFilled= arrayToBeFilled.Append("str").ToArray();

furthermore, If you want to fill an array with multiple elements you can use the previous code in a loop

//the array you want to fill values in
string[] arrayToBeFilled;
//list of values that you want to fill inside an array
List<string> listToFill = new List<string> { "a1", "a2", "a3" };
//looping through list to start filling the array

foreach (string str in listToFill){
// here are the LINQ extensions
arrayToBeFilled= arrayToBeFilled.Append(str).ToArray();
}

How do I set a value in CKEditor with Javascript?

Use the CKEditor method setData():

CKEDITOR.instances[**fieldname**].setData(**your data**)

How do I install the OpenSSL libraries on Ubuntu?

I found a detailed solution here: Install OpenSSL Manually On Linux

From the blog post...:

Steps to download, compile, and install are as follows (I'm installing version 1.0.1g below; please replace "1.0.1g" with your version number):

Step – 1 : Downloading OpenSSL:

Run the command as below :

$ wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz

Also, download the MD5 hash to verify the integrity of the downloaded file for just varifacation purpose. In the same folder where you have downloaded the OpenSSL file from the website :

$ wget http://www.openssl.org/source/openssl-1.0.1g.tar.gz.md5
$ md5sum openssl-1.0.1g.tar.gz
$ cat openssl-1.0.1g.tar.gz.md5

Step – 2 : Extract files from the downloaded package:

$ tar -xvzf openssl-1.0.1g.tar.gz

Now, enter the directory where the package is extracted like here is openssl-1.0.1g

$ cd openssl-1.0.1g

Step – 3 : Configuration OpenSSL

Run below command with optional condition to set prefix and directory where you want to copy files and folder.

$ ./config --prefix=/usr/local/openssl --openssldir=/usr/local/openssl

You can replace “/usr/local/openssl” with the directory path where you want to copy the files and folders. But make sure while doing this steps check for any error message on terminal.

Step – 4 : Compiling OpenSSL

To compile openssl you will need to run 2 command : make, make install as below :

$ make

Note: check for any error message for verification purpose.

Step -5 : Installing OpenSSL:

$ sudo make install

Or without sudo,

$ make install

That’s it. OpenSSL has been successfully installed. You can run the version command to see if it worked or not as below :

$ /usr/local/openssl/bin/openssl version

OpenSSL 1.0.1g 7 Apr 2014

CSS Background image not loading

I found the problem was you can't use short URL for image "img/image.jpg"

you should use the full URL "http://www.website.com/img/image.jpg", yet I don't know why !!

How to add a Java Properties file to my Java Project in Eclipse

To create a property class please select your package where you wants to create your property file.

Right click on the package and select other. Now select File and type your file name with (.properties) suffix. For example: db.properties. Than click finish. Now you can write your code inside this property file.

Getting a 'source: not found' error when using source in a bash script

If you're writing a bash script, call it by name:

#!/bin/bash

/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).

The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.

Get String in YYYYMMDD format from JS date object?

Altered piece of code I often use:

Date.prototype.yyyymmdd = function() {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();

  return [this.getFullYear(),
          (mm>9 ? '' : '0') + mm,
          (dd>9 ? '' : '0') + dd
         ].join('');
};

var date = new Date();
date.yyyymmdd();

Static class initializer in PHP

I am posting this as an answer because this is very important as of PHP 7.4.

The opcache.preload mechanism of PHP 7.4 makes it possible to preload opcodes for classes. If you use it to preload a file that contains a class definition and some side effects, then classes defined in that file will "exist" for all subsequent scripts executed by this FPM server and its workers, but the side effects will not be in effect, and the autoloader will not require the file containing them because the class already "exists". This completely defeats any and all static initialization techniques that rely on executing top-level code in the file that contains the class definition.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

If you use rails, you can use the asset pipeline to compile and shove all your haml/erb templates into a template module which can be appended to your application.js file. Checkout http://minhajuddin.com/2013/04/28/angularjs-templates-and-rails-with-eager-loading

Select 50 items from list at random to write to file

If the list is in random order, you can just take the first 50.

Otherwise, use

import random
random.sample(the_list, 50)

random.sample help text:

sample(self, population, k) method of random.Random instance
    Chooses k unique random elements from a population sequence.

    Returns a new list containing elements from the population while
    leaving the original population unchanged.  The resulting list is
    in selection order so that all sub-slices will also be valid random
    samples.  This allows raffle winners (the sample) to be partitioned
    into grand prize and second place winners (the subslices).

    Members of the population need not be hashable or unique.  If the
    population contains repeats, then each occurrence is a possible
    selection in the sample.

    To choose a sample in a range of integers, use xrange as an argument.
    This is especially fast and space efficient for sampling from a
    large population:   sample(xrange(10000000), 60)

c# dictionary one key many values

Use this:

Dictionary<TKey, Tuple<TValue1, TValue2, TValue3, ...>>

phpmyadmin "no data received to import" error, how to fix?

Change your upload settings in php.ini configuration file

Change the below settings to these values:

Change to:

post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M

Processing Symbol Files in Xcode

In Xcode Version 6.1.1 (6A2008a), after "Processing Symbol Files", a folder containing symbols associated with the device (including iOS version and CPU type) was created in ~/Library/Developer/Xcode/iOS DeviceSupport/ like this:

enter image description here

Flattening a shallow list in Python

If you're looking for a built-in, simple, one-liner you can use:

a = [[1, 2, 3], [4, 5, 6]
b = [i[x] for i in a for x in range(len(i))]
print b

returns

[1, 2, 3, 4, 5, 6]

Extension mysqli is missing, phpmyadmin doesn't work

I have encountered the same error on ubuntu and what worked for me was editing 2 lines in /etc/php/7.3/apache2/php.ini

  ;extension=mysqli to   extension=mysqli

and gave the extension variable location to mysqli.so after uncommenting it

   extension=/usr/lib/php/20170718/mysqli.so

then restart the service just to make sure

systemctl start mysql

android activity has leaked window com.android.internal.policy.impl.phonewindow$decorview Issue

Thank you Guys to give me many suggestions. Finally I got a solution. That is i have started the NetErrorPage intent two times. One time, i have checked the net connection availability and started the intent in page started event. second time, if the page has error, then i have started the intent in OnReceivedError event. So the first time dialog is not closed, before that the second dialog is called. So that i got a error.

Reason for the Error: I have called the showInfoMessageDialog method two times before closing the first one.

Now I have removed the second call and Cleared error :-).

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

JavaScript: Create and save file

_x000D_
_x000D_
function download(text, name, type) {_x000D_
  var a = document.getElementById("a");_x000D_
  var file = new Blob([text], {type: type});_x000D_
  a.href = URL.createObjectURL(file);_x000D_
  a.download = name;_x000D_
}
_x000D_
<a href="" id="a">click here to download your file</a>_x000D_
<button onclick="download('file text', 'myfilename.txt', 'text/plain')">Create file</button>
_x000D_
_x000D_
_x000D_

And you would then download the file by putting the download attribute on the anchor tag.

The reason I like this better than creating a data url is that you don't have to make a big long url, you can just generate a temporary url.

In Git, how do I figure out what my current revision is?

There are many ways git log -1 is the easiest and most common, I think

Removing "bullets" from unordered list <ul>

In my case

li {
  list-style-type : none;
}

It doesn't show the bullet but leaved some space for the bullet.

I use

li {
  list-style-type : '';
}

It works perfectly.

Error "initializer element is not constant" when trying to initialize variable with const

In C language, objects with static storage duration have to be initialized with constant expressions, or with aggregate initializers containing constant expressions.

A "large" object is never a constant expression in C, even if the object is declared as const.

Moreover, in C language, the term "constant" refers to literal constants (like 1, 'a', 0xFF and so on), enum members, and results of such operators as sizeof. Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.

For example, this is NOT a constant

const int N = 5; /* `N` is not a constant in C */

The above N would be a constant in C++, but it is not a constant in C. So, if you try doing

static int j = N; /* ERROR */

you will get the same error: an attempt to initialize a static object with a non-constant.

This is the reason why, in C language, we predominantly use #define to declare named constants, and also resort to #define to create named aggregate initializers.

Finding and removing non ascii characters from an Oracle Varchar2

The following also works:

select dump(a,1016), a from (
SELECT REGEXP_REPLACE (
          CONVERT (
             '3735844533120%$03  ',
             'US7ASCII',
             'WE8ISO8859P1'),
          '[^!@/\.,;:<>#$%&()_=[:alnum:][:blank:]]') a
  FROM DUAL);

Input and output numpy arrays to h5py

A cleaner way to handle file open/close and avoid memory leaks:

Prep:

import numpy as np
import h5py

data_to_write = np.random.random(size=(100,20)) # or some such

Write:

with h5py.File('name-of-file.h5', 'w') as hf:
    hf.create_dataset("name-of-dataset",  data=data_to_write)

Read:

with h5py.File('name-of-file.h5', 'r') as hf:
    data = hf['name-of-dataset'][:]

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

How to remove space from string?

Try doing this in a shell:

var="  3918912k"
echo ${var//[[:blank:]]/}

That uses parameter expansion (it's a non feature)

[[:blank:]] is a POSIX regex class (remove spaces, tabs...), see http://www.regular-expressions.info/posixbrackets.html

how to check the version of jar file?

If you have winrar, open the jar with winrar, double-click to open folder META-INF. Extract MANIFEST.MF and CHANGES files to any location (say desktop).

Open the extracted files in a text editor: You will see Implementation-Version or release version.

Reading json files in C++

You can use c++ boost::property_tree::ptree for parsing json data. here is the example for your json data. this would be more easy if you shift name inside each child nodes

#include <iostream>                                                             
#include <string>                                                               
#include <tuple>                                                                

#include <boost/property_tree/ptree.hpp>                                        
#include <boost/property_tree/json_parser.hpp> 
 int main () {

    namespace pt = boost::property_tree;                                        
    pt::ptree loadPtreeRoot;                                                    

    pt::read_json("example.json", loadPtreeRoot);                               
    std::vector<std::tuple<std::string, std::string, std::string>> people;      

    pt::ptree temp ;                                                            
    pt::ptree tage ;                                                            
    pt::ptree tprofession ;                                                     

    std::string age ;                                                           
    std::string profession ;                                                    
    //Get first child                                                           
    temp = loadPtreeRoot.get_child("Anna");                                     
    tage = temp.get_child("age");                                               
    tprofession = temp.get_child("profession");                                 

    age =  tage.get_value<std::string>();                                       
    profession =  tprofession.get_value<std::string>();                         
    std::cout << "age: " << age << "\n" << "profession :" << profession << "\n" ;
    //push tuple to vector                                                      
    people.push_back(std::make_tuple("Anna", age, profession));                 

    //Get Second child                                                          
    temp = loadPtreeRoot.get_child("Ben");                                      
    tage = temp.get_child("age");                                               
    tprofession = temp.get_child("profession");                                 

    age =  tage.get_value<std::string>();                                       
    profession  =  tprofession.get_value<std::string>();                        
    std::cout << "age: " << age << "\n" << "profession :" << profession << "\n" ;
    //push tuple to vector                                                      
    people.push_back(std::make_tuple("Ben", age, profession));                  

    for (const auto& tmppeople: people) {                                       
        std::cout << "Child[" << std::get<0>(tmppeople) << "] = " << "  age : " 
        << std::get<1>(tmppeople) << "\n    profession : " << std::get<2>(tmppeople) << "\n";
    }  
}

How to call a function from a string stored in a variable?

The easiest way to call a function safely using the name stored in a variable is,

//I want to call method deploy that is stored in functionname 
$functionname = 'deploy';

$retVal = {$functionname}('parameters');

I have used like below to create migration tables in Laravel dynamically,

foreach(App\Test::$columns as $name => $column){
        $table->{$column[0]}($name);
}

Checking whether a String contains a number value in Java

Another possible solution is to use a Scanner object like this:

Scanner scanner = new Scanner(inputString);  
if (scanner.hasNextInt()) {  
  return true;
}
else {
  return false
}

Of course, if you are looking for a double, use hasNextDouble() method (see: Scanner javadoc)

Perl: Use s/ (replace) and return new string

If you have Perl 5.14 or greater, you can use the /r option with the substitution operator to perform non-destructive substitution:

print "bla: ", $myvar =~ s/a/b/r, "\n";

In earlier versions you can achieve the same using a do() block with a temporary lexical variable, e.g.:

print "bla: ", do { (my $tmp = $myvar) =~ s/a/b/; $tmp }, "\n";

What is the difference between g++ and gcc?

For c++ you should use g++.

It's the same compiler (e.g. the GNU compiler collection). GCC or G++ just choose a different front-end with different default options.

In a nutshell: if you use g++ the frontend will tell the linker that you may want to link with the C++ standard libraries. The gcc frontend won't do that (also it could link with them if you pass the right command line options).

Unfamiliar symbol in algorithm: what does ? mean?

Can be read, "For all s such that s does not equal s[start]"

Programmatically navigate to another view controller/scene

If you want to navigate to Controller created Programmatically, then do this:

let newViewController = NewViewController()
self.navigationController?.pushViewController(newViewController, animated: true)

If you want to navigate to Controller on StoryBoard with Identifier "newViewController", then do this:

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
        self.present(newViewController, animated: true, completion: nil)

jQuery: Currency Format Number

Here is the cool regex style for digit grouping:

thenumber.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");

How do I use Comparator to define a custom sort order?

I recommend you create an enum for your car colours instead of using Strings and the natural ordering of the enum will be the order in which you declare the constants.

public enum PaintColors {
    SILVER, BLUE, MAGENTA, RED
}

and

 static class ColorComparator implements Comparator<CarSort>
 {
     public int compare(CarSort c1, CarSort c2)
     {
         return c1.getColor().compareTo(c2.getColor());
     }
 }

You change the String to PaintColor and then in main your car list becomes:

carList.add(new CarSort("Ford Figo",PaintColor.SILVER));

...

Collections.sort(carList, new ColorComparator());

Why is there an unexplainable gap between these inline-block div elements?

Found a solution not involving Flex, because Flex doesn't work in older Browsers. Example:

.container {
    display:block;
    position:relative;
    height:150px;
    width:1024px;
    margin:0 auto;
    padding:0px;
    border:0px;
    background:#ececec;
    margin-bottom:10px;
    text-align:justify;
    box-sizing:border-box;
    white-space:nowrap;
    font-size:0pt;
    letter-spacing:-1em;
}

.cols {
    display:inline-block;
    position:relative;
    width:32%;
    height:100%;
    margin:0 auto;
    margin-right:2%;
    border:0px;
    background:lightgreen;  
    box-sizing:border-box;
    padding:10px;
    font-size:10pt;
    letter-spacing:normal;
}

.cols:last-child {
    margin-right:0;
}

How to get current relative directory of your Makefile?

One line in the Makefile should be enough:

DIR := $(notdir $(CURDIR))

Custom date format with jQuery validation plugin

Is Easy, Example: Valid for HTML5 automatic type="date".

<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/additional-methods.min.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/localization/messages_es.js"></script>

$(function () {

        // Overload method default "date" jquery.validate.min.js
        $.validator.addMethod(
            "date",
            function(value, element) {
                var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/;
                return value.match(dateReg);
            },
            "Invalid date"
        );

     // Form Demo jquery.validate.min.js
     $('#form-datos').validate({
        submitHandler: function(form) {
            form.submit();
        }
    });

});

How to show full column content in a Spark Dataframe?

try this command :

df.show(df.count())

Merge or combine by rownames

you can wrap -Andrie answer into a generic function

mbind<-function(...){
 Reduce( function(x,y){cbind(x,y[match(row.names(x),row.names(y)),])}, list(...) )
}

Here, you can bind multiple frames with rownames as key

Passing a variable from node.js to html

I figured it out I was able to pass a variable like this

<script>var name = "<%= name %>";</script>
console.log(name);

SQL Query for Logins

Select * From Master..SysUsers Where IsSqlUser = 1

Session variables in ASP.NET MVC

The answer here is correct, I however struggled to implement it in an ASP.NET MVC 3 app. I wanted to access a Session object in a controller and couldn't figure out why I kept on getting a "Instance not set to an instance of an Object error". What I noticed is that in a controller when I tried to access the session by doing the following, I kept on getting that error. This is due to the fact that this.HttpContext is part of the Controller object.

this.Session["blah"]
// or
this.HttpContext.Session["blah"]

However, what I wanted was the HttpContext that's part of the System.Web namespace because this is the one the Answer above suggests to use in Global.asax.cs. So I had to explicitly do the following:

System.Web.HttpContext.Current.Session["blah"]

this helped me, not sure if I did anything that isn't M.O. around here, but I hope it helps someone!

super() raises "TypeError: must be type, not classobj" for new-style class

super() can be used only in the new-style classes, which means the root class needs to inherit from the 'object' class.

For example, the top class need to be like this:

class SomeClass(object):
    def __init__(self):
        ....

not

class SomeClass():
    def __init__(self):
        ....

So, the solution is that call the parent's init method directly, like this way:

class TextParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.all_data = []

How to reference a method in javadoc?

The general format, from the @link section of the javadoc documentation, is:

{@link package.class#member label}

Examples

Method in the same class:

/** See also {@link #myMethod(String)}. */
void foo() { ... }

Method in a different class, either in the same package or imported:

/** See also {@link MyOtherClass#myMethod(String)}. */
void foo() { ... }

Method in a different package and not imported:

/** See also {@link com.mypackage.YetAnotherClass#myMethod(String)}. */
void foo() { ... }

Label linked to method, in plain text rather than code font:

/** See also this {@linkplain #myMethod(String) implementation}. */
void foo() { ... }

A chain of method calls, as in your question. We have to specify labels for the links to methods outside this class, or we get getFoo().Foo.getBar().Bar.getBaz(). But these labels can be fragile during refactoring -- see "Labels" below.

/**
 * A convenience method, equivalent to 
 * {@link #getFoo()}.{@link Foo#getBar() getBar()}.{@link Bar#getBaz() getBaz()}.
 * @return baz
 */
public Baz fooBarBaz()

Labels

Automated refactoring may not affect labels. This includes renaming the method, class or package; and changing the method signature.

Therefore, provide a label only if you want different text than the default.

For example, you might link from human language to code:

/** You can also {@linkplain #getFoo() get the current foo}. */
void setFoo( Foo foo ) { ... }

Or you might link from a code sample with text different than the default, as shown above under "A chain of method calls." However, this can be fragile while APIs are evolving.

Type erasure and #member

If the method signature includes parameterized types, use the erasure of those types in the javadoc @link. For example:

int bar( Collection<Integer> receiver ) { ... }

/** See also {@link #bar(Collection)}. */
void foo() { ... }

How to "Open" and "Save" using java

First off, you'll want to go through Oracle's tutorial to learn how to do basic I/O in Java.

After that, you will want to look at the tutorial on how to use a file chooser.

Insert Picture into SQL Server 2005 Image Field using only SQL

CREATE TABLE Employees
(
    Id int,
    Name varchar(50) not null,
    Photo varbinary(max) not null
)


INSERT INTO Employees (Id, Name, Photo) 
SELECT 10, 'John', BulkColumn 
FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture

Standard deviation of a list

The other answers cover how to do std dev in python sufficiently, but no one explains how to do the bizarre traversal you've described.

I'm going to assume A-Z is the entire population. If not see Ome's answer on how to inference from a sample.

So to get the standard deviation/mean of the first digit of every list you would need something like this:

#standard deviation
numpy.std([A_rank[0], B_rank[0], C_rank[0], ..., Z_rank[0]])

#mean
numpy.mean([A_rank[0], B_rank[0], C_rank[0], ..., Z_rank[0]])

To shorten the code and generalize this to any nth digit use the following function I generated for you:

def getAllNthRanks(n):
    return [A_rank[n], B_rank[n], C_rank[n], D_rank[n], E_rank[n], F_rank[n], G_rank[n], H_rank[n], I_rank[n], J_rank[n], K_rank[n], L_rank[n], M_rank[n], N_rank[n], O_rank[n], P_rank[n], Q_rank[n], R_rank[n], S_rank[n], T_rank[n], U_rank[n], V_rank[n], W_rank[n], X_rank[n], Y_rank[n], Z_rank[n]] 

Now you can simply get the stdd and mean of all the nth places from A-Z like this:

#standard deviation
numpy.std(getAllNthRanks(n))

#mean
numpy.mean(getAllNthRanks(n))

How to drop unique in MySQL?

This may help others

alter table fuinfo drop index fuinfo_email_unique

how to parse JSONArray in android

If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?

Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:

List<String> allNames = new ArrayList<String>();

JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
    JSONObject actor = cast.getJSONObject(i);
    String name = actor.getString("name");
    allNames.add(name);
}

(typed straight into the browser, so not tested).

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

From this post:

To get the entire PC CPU and Memory usage:

using System.Diagnostics;

Then declare globally:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Processor", "% Processor Time", "_Total"); 

Then to get the CPU time, simply call the NextValue() method:

this.theCPUCounter.NextValue();

This will get you the CPU usage

As for memory usage, same thing applies I believe:

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Memory", "Available MBytes");

Then to get the memory usage, simply call the NextValue() method:

this.theMemCounter.NextValue();

For a specific process CPU and Memory usage:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Process", "% Processor Time",              
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Process", "Working Set",
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?

To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters

The difference between Processor\% Processor Time and Process\% Processor Time is Processor is from the PC itself and Process is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters

An alternative to using the Performance Counter

Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.

Permission denied (publickey) when SSH Access to Amazon EC2 instance

When you try doing

ssh -i <.pem path> root@ec2-public-dns

You get a message advising you to use the ec2-user.

Please login as the user "ec2-user" rather than the user "root".

So use

ssh -i <.pem path> ec2-user@ec2-public-dns

Circular gradient in android

<!-- Drop Shadow Stack -->
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#00CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#10CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#20CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#30CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <padding
            android:bottom="1dp"
            android:left="1dp"
            android:right="1dp"
            android:top="1dp" />

        <solid android:color="#50CCCCCC" />

        <corners android:radius="3dp" />
    </shape>
</item>

<!-- Background -->
<item>
    <shape android:shape="oval">
        <gradient
            android:startColor="@color/colorAccent_1"
            android:centerColor="@color/colorAccent_2"
            android:endColor="@color/colorAccent_3"
            android:angle="45"
            />
        <corners android:radius="3dp" />
    </shape>
</item>

<color name="colorAccent_1">#6f64d6</color>
<color name="colorAccent_2">#7668F8</color>
<color name="colorAccent_3">#6F63FF</color>

How can I check if a key exists in a dictionary?

Another method is has_key() (if still using Python 2.X):

>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True

Making a Sass mixin with optional arguments

A DRY'r Way of Doing It

And, generally, a neat trick to remove the quotes.

@mixin box-shadow($top, $left, $blur, $color, $inset:"") {
  -webkit-box-shadow: $top $left $blur $color #{$inset};
  -moz-box-shadow:    $top $left $blur $color #{$inset};
  box-shadow:         $top $left $blur $color #{$inset};
}

SASS Version 3+, you can use unquote():

@mixin box-shadow($top, $left, $blur, $color, $inset:"") {
  -webkit-box-shadow: $top $left $blur $color unquote($inset);
  -moz-box-shadow:    $top $left $blur $color unquote($inset);
  box-shadow:         $top $left $blur $color unquote($inset);
} 

Picked this up over here: pass a list to a mixin as a single argument with SASS

LDAP filter for blank (empty) attribute

The schema definition for an attribute determines whether an attribute must have a value. If the manager attribute in the example given is the attribute defined in RFC4524 with OID 0.9.2342.19200300.100.1.10, then that attribute has DN syntax. DN syntax is a sequence of relative distinguished names and must not be empty. The filter given in the example is used to cause the LDAP directory server to return only entries that do not have a manager attribute to the LDAP client in the search result.

Anaconda site-packages

Linux users can find the locations of all the installed packages like this:

pip list | xargs -exec pip show

How to get Toolbar from fragment?

From your Fragment: ( get Toolbar from fragment?)

// get toolbar
((MainAcivity)this.getActivity()).getToolbar();  // getToolbar will be method in Activity that returns Toolbar!!  don't use getSupportActionBar for getting toolbar!!
// get action bar
this.getActivity().getSupportActionBar();

this is very helpful when you are using spinner in Toolbar and call the spinner or custom views in Toolbar from a fragment!

From your Activity:

// get toolbar
this.getToolbar();
// get Action Bar
this.getSupportActionBar();

Add the loading screen in starting of the android application

use ProgressDialog.

ProgressDialog dialog=new ProgressDialog(context);
dialog.setMessage("message");
dialog.setCancelable(false);
dialog.setInverseBackgroundForced(false);
dialog.show();

hide it whenever your UI is ready with data. call :

dialog.hide();

Show special characters in Unix while using 'less' Command

Now, sometimes you already have less open, and you can't use cat on it. For example, you did a | less, and you can't just reopen a file, as that's actually a stream.

If all you need is to identify end of line, one easy way is to search for the last character on the line: /.$. The search will highlight the last character, even if it is a blank, making it easy to identify it.

That will only help with the end of line case. If you need other special characters, you can use the cat -vet solution above with marks and pipe:

  • mark the top of the text you're interested in: ma
  • go to the bottom of the text you're interested in and mark it, as well: mb
  • go back to the mark a: 'a
  • pipe from a to b through cat -vet and view the result in another less command: |bcat -vet | less

This will open another less process, which shows the result of running cat -vet on the text that lies between marks a and b.

If you want the whole thing, instead, do g|$cat -vet | less, to go to the first line and filter all lines through cat.

The advantage of this method over less options is that it does not mess with the output you see on the screen.

One would think that eight years after this question was originally posted, less would have that feature... But I can't even see a feature request for it on https://github.com/gwsw/less/issues

Parse usable Street Address, City, State, Zip from a string

I don't know HOW FEASIBLE this would be, but I haven't seen this mentioned so I thought I would go ahead and suggest this:

If you are strictly in the US... get a huge database of all zip codes, states, cities and streets. Now look for these in your addresses. You can validate what you find by testing if, say, the city you found exists in the state you found, or by checking if the street you found exists in the city you found. If not, chances are John isn't for John's street, but is the name of the addressee... Basically, get the most information you can and check your addresses against it. An extreme example would be to get A LIST OF ALL THE ADDRESSES IN THE US OF A and then find which one has the most relevant match to each of your addresses...

Jenkins: Failed to connect to repository

I had the exact same problem. The way I solved it on Mac is this:

  1. Switch to jenkins user (sudo -iu jenkins)
  2. Run: ssh-keygen (Note - You are creating ssh key pairs for jenkins user now. You should see something like this : Enter file in which to save the key (/Users/Shared/Jenkins/.ssh/id_rsa):
  3. Keep pressing Enter for default value till end
  4. Run the command showing in the Jenkins error message, on your teminal (eg : "git ls-remote -h [email protected]:adolfosrs/jenkins-test.git HEAD")
  5. You will be asked if you want to continue. Say yes
  6. The Github repo will be added to your known_hosts file in : /Users/Shared/Jenkins/.ssh/
  7. Go back to Jenkins portal and try your Github SSH url
  8. It should work. Good Luck

How to format a number 0..9 to display with 2 digits (it's NOT a date)

The String class comes with the format abilities:

System.out.println(String.format("%02d", 5));

for full documentation, here is the doc

How to change sa password in SQL Server 2008 express?

This is what worked for me:

  • Close all Sql Server referencing apps.
  • Open Services in Control Panel.
  • Find the "SQL Server (SQLEXPRESS)" entry and select properties.
  • Stop the service (all Sql Server services).
  • Enter "-m" at the Start parameters" fields.
  • Start the service (click on Start button on General Tab).
  • Open a Command Prompt (right click, Run as administrator if needed).
  • Enter the command:

    osql -S localhost\SQLEXPRESS -E

    (or change localhost to whatever your PC is called).

  • At the prompt type the following commands:

    CREATE LOGIN my_Login_here WITH PASSWORD = 'my_Password_here'

    go

    sp_addsrvrolemember 'my_Login_here', 'sysadmin'

    go

    quit

  • Stop the "SQL Server (SQLEXPRESS)" service.

  • Remove the "-m" from the Start parameters field (if still there).

  • Start the service.

  • In Management Studio, use the login and password you just created. This should give it admin permission.

Why do multiple-table joins produce duplicate rows?

Ok in this example you are getting duplicates because you are joining both D and S onto M. I assume you should be joining D.id onto S.id like below:

SELECT *
FROM M
INNER JOIN S
    on M.Id = S.Id
INNER JOIN D
    ON S.Id = D.Id
INNER JOIN H
    ON D.Id = H.Id

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

Stopping fixed position scrolling at a certain point?

In a project, I actually have some heading fixed to the bottom of the screen on page load (it's a drawing app so the heading is at the bottom to give maximum space to the canvas element on wide viewport).

I needed the heading to become 'absolute' when it reaches the footer on scroll, since I don't want the heading over the footer (heading colour is same as footer background colour).

I took the oldest response on here (edited by Gearge Millo) and that code snippet worked for my use-case. With some playing around I got this working. Now the fixed heading sits beautifully above the footer once it reaches the footer.

Just thought I'd share my use-case and how it worked, and say thank you! The app: http://joefalconer.com/web_projects/drawingapp/index.html

    /* CSS */
    @media screen and (min-width: 1100px) {
        #heading {
            height: 80px;
            width: 100%;
            position: absolute;  /* heading is 'absolute' on page load. DOESN'T WORK if I have this on 'fixed' */
            bottom: 0;
        }
    }

    // jQuery
    // Stop the fixed heading from scrolling over the footer
    $.fn.followTo = function (pos) {
      var $this = this,
      $window = $(window);

      $window.scroll(function (e) {
        if ($window.scrollTop() > pos) {
          $this.css( { position: 'absolute', bottom: '-180px' } );
        } else {
          $this.css( { position: 'fixed', bottom: '0' } );
        }
      });
    };
    // This behaviour is only needed for wide view ports
    if ( $('#heading').css("position") === "absolute" ) {
      $('#heading').followTo(180);
    }

How to load/edit/run/save text files (.py) into an IPython notebook cell?

I have found it satisfactory to use ls and cd within ipython notebook to find the file. Then type cat your_file_name into the cell, and you'll get back the contents of the file, which you can then paste into the cell as code.

Generating a random hex color code with PHP

function random_color(){  
 return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}

How to add the text "ON" and "OFF" to toggle button

Have a look on this example

_x000D_
_x000D_
.switch {
        width: 50px;
        height: 17px;
        position: relative;
        display: inline-block;
    }

        .switch input {
            display: none;
        }

        .switch .slider {
            position: absolute;
            top: 0;
            bottom: 0;
            right: 0;
            left: 0;
            cursor: pointer;
            background-color: #e7ecf1;
            border-radius: 30px !important;
            border: 0;
            padding: 0;
            display: block;
            margin: 12px 10px;
            min-height: 11px;
        }

            .switch .slider:before {
                position: absolute;
                background-color: #aaa;
                height: 15px;
                width: 15px;
                content: "";
                left: 0px;
                bottom: -2px;
                border-radius: 50%;
                transition: ease-in-out .5s;
            }

            .switch .slider:after {
                content: "";
                color: white;
                display: block;
                position: absolute;
                transform: translate(-50%,-50%);
                top: 50%;
                left: 70%;
                transition: all .5s;
                font-size: 10px;
                font-family: Verdana,sans-serif;
            }

        .switch input:checked + .slider:after {
            transition: all .5s;
            left: 30%;
            content: "";
        }

        .switch input:checked + .slider {
            background-color: #d3d6d9;
        }

            .switch input:checked + .slider:before {
                transform: translateX(15px);
                background-color: #26a2ac;
            }
_x000D_
<label class="switch">
                                        <input type="checkbox" />
                                        <div class="slider"></div>
                                    </label>
_x000D_
_x000D_
_x000D_

How to make android listview scrollable?

Practically its not good to do. But if you want to do like this, just make listview's height fixed to wrap_content.

android:layout_height="wrap_content"

how to import csv data into django models

something like this:

f = open('data.txt', 'r')  
for line in f:  
   line =  line.split(';')  
   product = Product()  
   product.name = line[2] + '(' + line[1] + ')'  
   product.description = line[4]  
   product.price = '' #data is missing from file  
   product.save()  

f.close()  

Is there an online application that automatically draws tree structures for phrases/sentences?

There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.

The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.

Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

Multiple select statements in Single query

If you use MyISAM tables, the fastest way is querying directly the stats:

select table_name, table_rows 
     from information_schema.tables 
where 
     table_schema='databasename' and 
     table_name in ('user_table','cat_table','course_table')

If you have InnoDB you have to query with count() as the reported value in information_schema.tables is wrong.

SQL Call Stored Procedure for each Row without using a cursor

If you can turn the stored procedure into a function that returns a table, then you can use cross-apply.

For example, say you have a table of customers, and you want to compute the sum of their orders, you would create a function that took a CustomerID and returned the sum.

And you could do this:

SELECT CustomerID, CustomerSum.Total

FROM Customers
CROSS APPLY ufn_ComputeCustomerTotal(Customers.CustomerID) AS CustomerSum

Where the function would look like:

CREATE FUNCTION ComputeCustomerTotal
(
    @CustomerID INT
)
RETURNS TABLE
AS
RETURN
(
    SELECT SUM(CustomerOrder.Amount) AS Total FROM CustomerOrder WHERE CustomerID = @CustomerID
)

Obviously, the example above could be done without a user defined function in a single query.

The drawback is that functions are very limited - many of the features of a stored procedure are not available in a user-defined function, and converting a stored procedure to a function does not always work.

Using Get-childitem to get a list of files modified in the last 3 days

Very similar to previous responses, but the is from the current directory, looks at any file and only for ones that are 4 days old. This is what I needed for my research and the above answers were all very helpful. Thanks.

Get-ChildItem -Path . -Recurse| ? {$_.LastWriteTime -gt (Get-Date).AddDays(-4)}

How to download a file from a website in C#

Sure, you just use a HttpWebRequest.

Once you have the HttpWebRequest set up, you can save the response stream to a file StreamWriter(Either BinaryWriter, or a TextWriter depending on the mimetype.) and you have a file on your hard drive.

EDIT: Forgot about WebClient. That works good unless as long as you only need to use GET to retrieve your file. If the site requires you to POST information to it, you'll have to use a HttpWebRequest, so I'm leaving my answer up.

Regex: Remove lines containing "help", etc

Easy task with grep:

grep -v help filename

Append > newFileName to redirect output to a new file.


Update

To clarify it, the normal behavior will be printing the lines on screen. To pipe it to a file, the > can be used. Thus, in this command:

grep -v help filename > newFileName
  1. grep calls the grep program, obviously
  2. -v is a flag to inverse the output. By defaulf, grep prints the lines that match the given pattern. With this flag, it will print the lines that don't match the pattern.
  3. help is the pattern to match
  4. filename is the name of the input file
  5. > redirects the output to the following item
  6. newFileName the new file where output will be saved.

As you may noticed, you will not be deleting things in your file. grep will read it and another file will be saved, modified accordingly.

C++ Calling a function from another class

What you should do, is put CallFunction into *.cpp file, where you include B.h.

After edit, files will look like:

B.h:

#pragma once //or other specific to compiler...
using namespace std;

class A 
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
        {
            //stuff done here
        }
};

B.cpp

#include "B.h"
void A::CallFunction(){
//use B object here...
}

Referencing to your explanation, that you have tried to change B b; into pointer- it would be okay, if you wouldn't use it in that same place. You can use pointer of undefined class(but declared), because ALL pointers have fixed byte size(4), so compiler doesn't have problems with that. But it knows nothing about the object they are pointing to(simply: knows the size/boundary, not the content).

So as long as you are using the knowledge, that all pointers are same size, you can use them anywhere. But if you want to use the object, they are pointing to, the class of this object must be already defined and known by compiler.

And last clarification: objects may differ in size, unlike pointers. Pointer is a number/index, which indicates the place in RAM, where something is stored(for example index: 0xf6a7b1).

:after and :before pseudo-element selectors in Sass

Use ampersand to specify the parent selector.

SCSS syntax:

p {
    margin: 2em auto;

    > a {
        color: red;
    }

    &:before {
        content: "";
    }

    &:after {
        content: "* * *";
    }
}

Difference between RUN and CMD in a Dockerfile

The existing answers cover most of what anyone looking at this question would need. So I'll just cover some niche areas for CMD and RUN.

CMD: Duplicates are Allowed but Wasteful

GingerBeer makes an important point: you won't get any errors if you put in more than one CMD - but it's wasteful to do so. I'd like to elaborate with an example:

FROM busybox
CMD echo "Executing CMD"
CMD echo "Executing CMD 2"

If you build this into an image and run a container in this image, then as GingerBeer states, only the last CMD will be heeded. So the output of that container will be:

Executing CMD 2

The way I think of it is that "CMD" is setting a single global variable for the entire image that is being built, so successive "CMD" statements simply overwrite any previous writes to that global variable, and in the final image that's built the last one to write wins. Since a Dockerfile executes in order from top to bottom, we know that the bottom-most CMD is the one gets this final "write" (metaphorically speaking).

RUN: Commands May not Execute if Images are Cached

A subtle point to notice about RUN is that it's treated as a pure function even if there are side-effects, and is thus cached. What this means is that if RUN had some side effects that don't change the resultant image, and that image has already been cached, the RUN won't be executed again and so the side effects won't happen on subsequent builds. For example, take this Dockerfile:

FROM busybox
RUN echo "Just echo while you work"

First time you run it, you'll get output such as this, with different alphanumeric IDs:

docker build -t example/run-echo .
Sending build context to Docker daemon  9.216kB
Step 1/2 : FROM busybox
 ---> be5888e67be6
Step 2/2 : RUN echo "Just echo while you work"
 ---> Running in ed37d558c505
Just echo while you work
Removing intermediate container ed37d558c505
 ---> 6f46f7a393d8
Successfully built 6f46f7a393d8
Successfully tagged example/run-echo:latest

Notice that the echo statement was executed in the above. Second time you run it, it uses the cache, and you won't see any echo in the output of the build:

docker build -t example/run-echo .
Sending build context to Docker daemon  9.216kB
Step 1/2 : FROM busybox
 ---> be5888e67be6
Step 2/2 : RUN echo "Just echo while you work"
 ---> Using cache
 ---> 6f46f7a393d8
Successfully built 6f46f7a393d8
Successfully tagged example/run-echo:latest

What is a regex to match ONLY an empty string?

Wow, ya'll are overthinking it. It's as simple as the following. Besides, many of those answers aren't understood by the RE2 dialect used by C and golang.

^$

Add a new column to existing table in a migration

Although a migration file is best practice as others have mentioned, in a pinch you can also add a column with tinker.

$ php artisan tinker

Here's an example one-liner for the terminal:

Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ $table->integer('paid'); })



(Here it is formatted for readability)

Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ 
    $table->integer('paid'); 
});

jQuery AJAX submit form

This is not the answer to OP's question,
but in case if you can't use static form DOM, you can also try like this.

var $form = $('<form/>').append(
    $('<input/>', {name: 'username'}).val('John Doe'),
    $('<input/>', {name: 'user_id'}).val('john.1234')
);

$.ajax({
    url: 'api/user/search',
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded',
    data: $form.serialize(),
    success: function(data, textStatus, jqXHR) {
        console.info(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        var errorMessage = jqXHR.responseText;
        if (errorMessage.length > 0) {
            alert(errorMessage);
        }
    }
});

How do I break a string in YAML over multiple lines?

You might not believe it, but YAML can do multi-line keys too:

?
 >
 multi
 line
 key
:
  value

Installation of SQL Server Business Intelligence Development Studio

If you have installed SQL 2005 express edition and want to install BIDS (Business Intelligence Development Studio) then go to here Microsoft SQL Server 2005 Express Edition Toolkit

This has an option to install BIDS on my machine, and is the only way l could get hold of BIDS for SQL Server 2005 express edition.

Also this package l think has also allowed me to install both BIDS 2005 & 2008 express edition on the same machine.

Delaying function in swift

 NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHere", userInfo: nil, repeats: false)

This would call the function functionHere() with a 3 seconds delay

Keep a line of text as a single line - wrap the whole line or none at all

You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.

How do I wrap this line of text
-&nbsp;asked&nbsp;by&nbsp;Peter&nbsp;2&nbsp;days&nbsp;ago

How to edit log message already committed in Subversion?

The Subversion FAQ covers this, but uses a bunch of confusing undefined terms like REPOS_PATH without giving any actual examples.

It might take a few tries to get it to work, so save your updated commit message in a file. Unlike with svn-commit.tmp files, Subversion won’t preserve your typing if there’s a problem.

In your working directory, run

svn propedit -r N --revprop svn:log

to edit the commit message. If that works, great! But it probably won’t, because the svn:log revision property is unversioned and Subversion by default will stop you from overwriting it, either with the hook script pre-revprop-change, or an error message that you don’t have such a hook.

To change the hooks, you need access to the filesystem on which the repository is hosted. svn info will tell you the Repository Root. Suppose it’s ~/svnrepo.

  1. cd to ~/svnrepo/hooks
  2. Is there a pre-revprop-change or pre-revprop-change.bat script? If so, temporarily comment out the part of it that aborts if you try to change svn:log.
  3. Otherwise, on Windows, create a blank file called pre-revprop-change.bat. Here’s one way to do that:

    copy con pre-revprop-change.bat
    ^Z
    
  4. Otherwise, on Unix, run

    echo '#!/bin/sh' > pre-revprop-change
    chmod +x pre-revprop-change
    
  5. In the working copy, run svn propedit -r N --revprop svn:log again

  6. Undo your changes to ~/svnrepo/hooks/svn-revprop-change(.bat)

How to map atan2() to degrees 0-360

A formula to have the range of values from 0 to 360 degrees.

f(x,y)=180-90*(1+sign(x))* (1-sign(y^2))-45*(2+sign(x))*sign(y)

     -(180/pi())*sign(x*y)*atan((abs(x)-abs(y))/(abs(x)+abs(y)))

Toggle visibility property of div

To do it with an effect like with $.fadeIn() and $.fadeOut() you can use transitions

.visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 1s linear;
}
.hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 1s, opacity 1s linear;
}

Link to add to Google calendar

Here's an example link you can use to see the format:

https://www.google.com/calendar/render?action=TEMPLATE&text=Your+Event+Name&dates=20140127T224000Z/20140320T221500Z&details=For+details,+link+here:+http://www.example.com&location=Waldorf+Astoria,+301+Park+Ave+,+New+York,+NY+10022&sf=true&output=xml

Note the key query parameters:

text
dates
details
location

Here's another example (taken from http://wordpress.org/support/topic/direct-link-to-add-specific-google-calendar-event):

<a href="http://www.google.com/calendar/render?
action=TEMPLATE
&text=[event-title]
&dates=[start-custom format='Ymd\\THi00\\Z']/[end-custom format='Ymd\\THi00\\Z']
&details=[description]
&location=[location]
&trp=false
&sprop=
&sprop=name:"
target="_blank" rel="nofollow">Add to my calendar</a>

Here's a form which will help you construct such a link if you want (mentioned in earlier answers):

https://support.google.com/calendar/answer/3033039 Edit: This link no longer gives you a form you can use

linq query to return distinct field values from a list of objects

I think this is what your looking for:

    var objs= (from c in List_Objects 
orderby c.TypeID  select c).GroupBy(g=>g.TypeID).Select(x=>x.FirstOrDefault());      

Similar to this Returning a Distinct IQueryable with LINQ?

How to make function decorators and chain them together?

Python decorators add extra functionality to another function

An italics decorator could be like

def makeitalic(fn):
    def newFunc():
        return "<i>" + fn() + "</i>"
    return newFunc

Note that a function is defined inside a function. What it basically does is replace a function with the newly defined one. For example, I have this class

class foo:
    def bar(self):
        print "hi"
    def foobar(self):
        print "hi again"

Now say, I want both functions to print "---" after and before they are done. I could add a print "---" before and after each print statement. But because I don't like repeating myself, I will make a decorator

def addDashes(fn): # notice it takes a function as an argument
    def newFunction(self): # define a new function
        print "---"
        fn(self) # call the original function
        print "---"
    return newFunction
    # Return the newly defined function - it will "replace" the original

So now I can change my class to

class foo:
    @addDashes
    def bar(self):
        print "hi"

    @addDashes
    def foobar(self):
        print "hi again"

For more on decorators, check http://www.ibm.com/developerworks/linux/library/l-cpdecor.html

How do I use JDK 7 on Mac OSX?

This is how I got 1.7 to work with Eclipse. I hope it helps.

  1. I Downloaded the latest OpenJDK 1.7 universal (32/64 bits) JDK from Mac OS/X branch from http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html
  2. copied the jdk to /Library/Java/JavaVirtualMachines/ next to the default 1.6.0 one
  3. In Eclipse > Preferences > Java > Installed JREs you add a new one, of type MacOS X VM, and set the home as /Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home and name Java SE 7 (OpenJDK)
  4. Click Finish
  5. Set the added JRE as default

that should be it :)

Querying Windows Active Directory server using ldapsearch from command line

You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify

One time page refresh after first page load

        var foo = true;
        if (foo){
            window.location.reload(true);
            foo = false;

        }

What does '<?=' mean in PHP?

It's a shortcut for <?php echo $a; ?> if short_open_tags are enabled. Ref: http://php.net/manual/en/ini.core.php

How to convert decimal to hexadecimal in JavaScript

I'm doing conversion to hex string in a pretty large loop, so I tried several techniques in order to find the fastest one. My requirements were to have a fixed-length string as a result, and encode negative values properly (-1 => ff..f).

Simple .toString(16) didn't work for me since I needed negative values to be properly encoded. The following code is the quickest I've tested so far on 1-2 byte values (note that symbols defines the number of output symbols you want to get, that is for 4-byte integer it should be equal to 8):

var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
function getHexRepresentation(num, symbols) {
    var result = '';
    while (symbols--) {
        result = hex[num & 0xF] + result;
        num >>= 4;
    }
    return result;
}

It performs faster than .toString(16) on 1-2 byte numbers and slower on larger numbers (when symbols >= 6), but still should outperform methods that encode negative values properly.

Reading an Excel file in python using pandas

You just need to feed the path to your file to pd.read_excel

import pandas as pd

file_path = "./my_excel.xlsx"
data_frame = pd.read_excel(file_path)

Checkout the documentation to explore parameters like skiprows to ignore rows when loading the excel

Find unique lines

This was the first i tried

skilla:~# uniq -u all.sorted  

76679787
76679787 
76794979
76794979 
76869286
76869286 
......

After doing a cat -e all.sorted

skilla:~# cat -e all.sorted 
$
76679787$
76679787 $
76701427$
76701427$
76794979$
76794979 $
76869286$
76869286 $

Every second line has a trailing space :( After removing all trailing spaces it worked!

thank you

PHP + MySQL transactions examples

When using PDO connection:

$pdo = new PDO('mysql:host=localhost;dbname=mydb;charset=utf8', $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // this is important
]);

I often use the following code for transaction management:

function transaction(Closure $callback)
{
    global $pdo; // let's assume our PDO connection is in a global var

    // start the transaction outside of the try block, because
    // you don't want to rollback a transaction that failed to start
    $pdo->beginTransaction(); 
    try
    {
        $callback();
        $pdo->commit(); 
    }
    catch (Exception $e) // it's better to replace this with Throwable on PHP 7+
    {
        $pdo->rollBack();
        throw $e; // we still have to complain about the exception
    }
}

Usage example:

transaction(function()
{
    global $pdo;

    $pdo->query('first query');
    $pdo->query('second query');
    $pdo->query('third query');
});

This way the transaction-management code is not duplicated across the project. Which is a good thing, because, judging from other PDO-ralated answers in this thread, it's easy to make mistakes in it. The most common ones being forgetting to rethrow the exception and starting the transaction inside the try block.

Change select box option background color

You need to put background-color on the option tag and not the select tag...

select option {
    margin: 40px;
    background: rgba(0, 0, 0, 0.3);
    color: #fff;
    text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);
}

If you want to style each one of the option tags.. use the css attribute selector:

_x000D_
_x000D_
select option {_x000D_
  margin: 40px;_x000D_
  background: rgba(0, 0, 0, 0.3);_x000D_
  color: #fff;_x000D_
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);_x000D_
}_x000D_
_x000D_
select option[value="1"] {_x000D_
  background: rgba(100, 100, 100, 0.3);_x000D_
}_x000D_
_x000D_
select option[value="2"] {_x000D_
  background: rgba(150, 150, 150, 0.3);_x000D_
}_x000D_
_x000D_
select option[value="3"] {_x000D_
  background: rgba(200, 200, 200, 0.3);_x000D_
}_x000D_
_x000D_
select option[value="4"] {_x000D_
  background: rgba(250, 250, 250, 0.3);_x000D_
}
_x000D_
<select>_x000D_
  <option value="">Please choose</option>_x000D_
  <option value="1">Option 1</option>_x000D_
  <option value="2">Option 2</option>_x000D_
  <option value="3">Option 3</option>_x000D_
  <option value="4">Option 4</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Bootstrap modal: close current, open new

None of the answers helped me since I wanted to achieve something which was exactly the same as mentioned in the question.

I have created a jQuery plugin for this purpose.

/*
 * Raj: This file is responsible to display the modals in a stacked fashion. Example:
 * 1. User displays modal A
 * 2. User now wants to display modal B -> This will not work by default if a modal is already displayed
 * 3. User dismisses modal B
 * 4. Modal A should now be displayed automatically -> This does not happen all by itself 
 * 
 * Trying to solve problem for: http://stackoverflow.com/questions/18253972/bootstrap-modal-close-current-open-new
 * 
 */

var StackedModalNamespace = StackedModalNamespace || (function() {
    var _modalObjectsStack = [];
    return {
        modalStack: function() {
            return _modalObjectsStack;
        },
        currentTop: function() {
            var topModal = null;
            if (StackedModalNamespace.modalStack().length) {
                topModal = StackedModalNamespace.modalStack()[StackedModalNamespace.modalStack().length-1];
            }
            return topModal;
        }
    };
}());

// http://stackoverflow.com/a/13992290/260665 difference between $.fn.extend and $.extend
jQuery.fn.extend({
    // https://api.jquery.com/jquery.fn.extend/
    showStackedModal: function() {
        var topModal = StackedModalNamespace.currentTop();
        StackedModalNamespace.modalStack().push(this);
        this.off('hidden.bs.modal').on('hidden.bs.modal', function(){   // Subscription to the hide event
            var currentTop = StackedModalNamespace.currentTop();
            if ($(this).is(currentTop)) {
                // 4. Unwinding - If user has dismissed the top most modal we need to remove it form the stack and display the now new top modal (which happens in point 3 below)
                StackedModalNamespace.modalStack().pop();
            }
            var newTop = StackedModalNamespace.currentTop();
            if (newTop) {
                // 3. Display the new top modal (since the existing modal would have been hidden by point 2 now)
                newTop.modal('show');
            }
        });
        if (topModal) {
            // 2. If some modal is displayed, lets hide it
            topModal.modal('hide');
        } else {
            // 1. If no modal is displayed, just display the modal
            this.modal('show');
        }
    },
});

Working Fiddle for reference, JSFiddle: https://jsfiddle.net/gumdal/67hzgp5c/

You just have to invoke with my new API "showStackedModal()" instead of just "modal('show')". The hide part can still be the same as before and the stacked approach of showing & hiding the modals are automatically taken care.

How to color System.out.println output?

Note

You may not be able to color Window's cmd prompt, but it should work in many unix (or unix-like) terminals.

Also, note that some terminals simply won't support some (if any) ANSI escape sequences and, especially, 24-bit colors.

Usage

Please refer to the section Curses at the bottom for the best solution. For a personal or easy solution (although not as cross-platform solution), refer to the ANSI Escape Sequences section.


TL;DR

  • java: System.out.println((char)27 + "[31m" + "ERROR MESSAGE IN RED");

  • python: print(chr(27) + "[31m" + "ERROR MESSAGE IN RED")

  • bash or zsh: printf '\x1b[31mERROR MESSAGE IN RED'
    • this may also work for Os X: printf '\e[31mERROR MESSAGE IN RED'
  • sh: printf 'CTRL+V,CTRL+[[31mERROR MESSAGE IN RED'
    • ie, press CTRL+V and then CTRL+[ in order to get a "raw" ESC character when escape interpretation is not available
    • If done correctly, you should see a ^[. Although it looks like two characters, it is really just one, the ESC character.
    • You can also press CTRL+V,CTRL+[ in vim in any of the programming or sripting langauges because that uses a literal ESC character
    • Also, you can replace Ctrl+[ with ESC … eg, you can use CTRL+V,ESC, but I find the former easier, since I am already pressing CTRL and since [ is less out of the way.

ANSI Escape Sequences

Background on Escape Sequences

While it is not the best way to do it, the easiest way to do this in a programming or scripting language is to use escape sequences. From that link:

An escape sequence is a series of characters used to change the state of computers and their attached peripheral devices. These are also known as control sequences, reflecting their use in device control.

Backgound on ANSI Escape Sequences

However, it gets even easier than that in video text terminals, as these terminals use ANSI escape sequences. From that link:

ANSI escape sequences are a standard for in-band signaling to control the cursor location, color, and other options on video text terminals. Certain sequences of bytes, most starting with Esc and '[', are embedded into the text, which the terminal looks for and interprets as commands, not as character codes.

How to Use ANSI Escape Sequences

Generally

  • Escape sequences begin with an escape character; for ANSI escape sequences, the sequence always begins with ESC (ASCII: 27 / hex: 0x1B).
  • For a list of what you can do, refer to the ANSI Escape Sequence List on Wikipedia

In Programming Languages

Some programming langauges (like Java) will not interpret \e or \x1b as the ESC character. However, we know that the ASCII character 27 is the ESC character, so we can simply typecast 27 to a char and use that to begin the escape sequence.

Here are some ways to do it in common programming languages:

  • Java

    • System.out.println((char)27 + "[33mYELLOW");
  • Python 3

    • print(chr(27) + "[34mBLUE");
    • print("\x1b[35mMAGENTA");
      • Note that \x1b is interpretted correctly in python
  • Node JS

    • The following will NOT color output in JavaScript in the Web Console
    • console.log(String.fromCharCode(27) + "[36mCYAN");
    • console.log("\x1b[30;47mBLACK_ON_WHITE");
      • Note that \x1b also works in node

In Shell Prompt OR Scripts

If you are working with bash or zsh, it is quite easy to color the output (in most terminals). In Linux, Os X, and in some Window's terminals, you can check to see if your terminal supports color by doing both of the following:

  • printf '\e[31mRED'
  • printf '\x1b[31mRED'

If you see color for both, then that's great! If you see color for only one, then use that sequence. If you do not see color for either of them, then double check to make sure you typed everything correctly and that you are in bash or zsh; if you still do not see any color, then your terminal probably does not support ANSI escape sequences.

If I recall correctly, linux terminals tend to support both \e and \x1b escape sequences, while os x terminals only tend to support \e, but I may be wrong. Nonetheless, if you see something like the following image, then you're all set! (Note that I am using the shell, zsh, and it is coloring my prompt string; also, I am using urxvt as my terminal in linux.)

ANSI Escape Sequences Coloring Text Red

"How does this work?" you might ask. Bascially, printf is interpretting the sequence of characters that follows (everything inside of the single-quotes). When printf encounters \e or \x1b, it will convert these characters to the ESC character (ASCII: 27). That's just what we want. Now, printf sends ESC31m, and since there is an ESC followed by a valid ANSI escape sequence, we should get colored output (so long as it is supported by the terminal).

You can also use echo -e '\e[32mGREEN' (for example), to color output. Note that the -e flag for echo "[enables] interpretation of backslash escapes" and must be used if you want echo to appropriately interpret the escape sequence.


More on ANSI Escape Sequences

ANSI escape sequences can do more than just color output, but let's start with that, and see exactly how color works; then, we will see how to manipulate the cursor; finally, we'll take a look and see how to use 8-bit color and also 24-bit color (although it only has tenuous support).

On Wikipedia, they refer to ESC[ as CSI, so I will do the same.

Color

To color output using ANSI escapes, use the following:

  • CSI n m
    • CSI: escape character—^[[ or ESC[
    • n: a number—one of the following:
      • 30-37, 39: foreground
      • 40-47, 49: background
    • m: a literal ASCII m—terminates the escape sequence

I will use bash or zsh to demonstrate all of the possible color combinations. Plop the following in bash or zsh to see for yourself (You may need to replace \e with \x1b):

  • for fg in {30..37} 39; do for bg in {40..47} 49; do printf "\e[${fg};${bg}m~TEST~"; done; printf "\n"; done;

Result:

various foreground/background colors using ANSI escapes

Quick Reference (Color)

+~~~~~~+~~~~~~+~~~~~~~~~~~+
|  fg  |  bg  |  color    |
+~~~~~~+~~~~~~+~~~~~~~~~~~+
|  30  |  40  |  black    |
|  31  |  41  |  red      |
|  32  |  42  |  green    |
|  33  |  43  |  yellow   |
|  34  |  44  |  blue     |
|  35  |  45  |  magenta  |
|  36  |  46  |  cyan     |
|  37  |  47  |  white    |
|  39  |  49  |  default  |
+~~~~~~+~~~~~~+~~~~~~~~~~~+

Select Graphic Rendition (SGR)

SGR just allows you to change the text. Many of these do not work in certain terminals, so use these sparingly in production-level projects. However, they can be useful for making program output more readable or helping you distinguish between different types of output.

Color actually falls under SGR, so the syntax is the same:

  • CSI n m
    • CSI: escape character—^[[ or ESC[
    • n: a number—one of the following:
      • 0: reset
      • 1-9: turns on various text effects
      • 21-29: turns off various text effects (less supported than 1-9)
      • 30-37, 39: foreground color
      • 40-47, 49: background color
      • 38: 8- or 24-bit foreground color (see 8/24-bit Color below)
      • 48: 8- or 24-bit background color (see 8/24-bit Color below)
    • m: a literal ASCII m—terminates the escape sequence

Although there is only tenuous support for faint (2), italic (3), underline (4), blinking (5,6), reverse video (7), conceal (8), and crossed out (9), some (but rarely all) tend to work on linux and os x terminals.

It's also worthwhile to note that you can separate any of the above attributes with a semi-colon. For example printf '\e[34;47;1;3mCRAZY TEXT\n' will show CRAZY TEXT with a blue foreground on a white background, and it will be bold and italic.

Eg:

string attributes together example screenshot

Plop the following in your bash or zsh shell to see all of the text effects you can do. (You may need to replace \e with \x1b.)

  • for i in {1..9}; do printf "\e[${i}m~TEST~\e[0m "; done

Result:

SGR state 1 SGR state 2

You can see that my terminal supports all of the text effects except for faint (2), conceal (8) and cross out (9).

Quick Reference (SGR Attributes 0-9)

+~~~~~+~~~~~~~~~~~~~~~~~~+
|  n  |  effect          |
+~~~~~+~~~~~~~~~~~~~~~~~~+
|  0  |  reset           |
|  1  |  bold            |
|  2  |  faint*          |
|  3  |  italic**        |
|  4  |  underline       |
|  5  |  slow blink      |
|  6  |  rapid blink*    |
|  7  |  inverse         |
|  8  |  conceal*        |
|  9  |  strikethrough*  |
+~~~~~+~~~~~~~~~~~~~~~~~~+

* not widely supported
** not widely supported and sometimes treated as inverse

8-bit Color

While most terminals support this, it is less supported than 0-7,9 colors.

Syntax:

  • CSI 38;5; n m
    • CSI: escape character—^[[ or ESC[
    • 38;5;: literal string that denotes use of 8-bit colors for foreground
    • n: a number—one of the following:
      • 0-255

If you want to preview all of the colors in your terminal in a nice way, I have a nice script on gist.github.com.

It looks like this:

8-bit color example screenshot

If you want to change the background using 8-bit colors, just replace the 38 with a 48:

  • CSI 48;5; n m
    • CSI: escape character—^[[ or ESC[
    • 48;5;: literal string that denotes use of 8-bit colors for background
    • n: a number—one of the following:
      • 0-255

24-bit Color

Also known as true color, 24-bit color provides some really cool functionality. Support for this is definitely growing (as far as I know it works in most modern terminals except urxvt, my terminal [insert angry emoji]).

24-bit color is actually supported in vim (see the vim wiki to see how to enable 24-bit colors). It's really neat because it pulls from the colorscheme defined for gvim; eg, it uses the fg/bg from highlight guibg=#______ guifg=#______ for the 24-bit colors! Neato, huh?

Here is how 24-bit color works:

  • CSI 38;2; r ; g ; b m
    • CSI: escape character—^[[ or ESC[
    • 38;2;: literal string that denotes use of 24-bit colors for foreground
    • r,g,b: numbers—each should be 0-255

To test just a few of the many colors you can have ((2^8)^3 or 2^24 or 16777216 possibilites, I think), you can use this in bash or zsh:

  • for r in 0 127 255; do for g in 0 127 255; do for b in 0 127 255; do printf "\e[38;2;${r};${g};${b}m($r,$g,$b)\e[0m "; done; printf "\n"; done; done;

Result (this is in gnome-terminal since urxvt DOES NOT SUPPORT 24-bit color ... get it together, urxvt maintainer ... for real):

24-bit color example screenshot

If you want 24-bit colors for the background ... you guessed it! You just replace 38 with 48:

  • CSI 48;2; r ; g ; b m
    • CSI: escape character—^[[ or ESC[
    • 48;2;: literal string that denotes use of 24-bit colors for background
    • r,g,b: numbers—each should be 0-255

Inserting Raw Escape Sequences

Sometimes \e and \x1b will not work. For example, in the sh shell, sometimes neither works (although it does on my system now, I don't think it used to).

To circumvent this, you can use CTRL+V,CTRL+[ or CTRLV,ESC

This will insert a "raw" ESC character (ASCII: 27). It will look like this ^[, but do not fret; it is only one character—not two.

Eg:

sh raw escape char example screenshot


Curses

Refer to the Curses (Programming Library) page for a full reference on curses. It should be noted that curses only works on unix and unix-like operating systems.

Up and Running with Curses

I won't go into too much detail, for search engines can reveal links to websites that can explain this much better than I can, but I'll discuss it briefly here and give an example.

Why Use Curses Over ANSI Escapes?

If you read the above text, you might recall that \e or \x1b will sometimes work with printf. Well, sometimes \e and \x1b will not work at all (this is not standard and I have never worked with a terminal like this, but it is possible). More importantly, more complex escape sequences (think Home and other multi-character keys) are difficult to support for every terminal (unless you are willing to spend a lot of time and effort parsing terminfo and termcap and and figuring out how to handle every terminal).

Curses solves this problem. Basically, it is able to understand what capabilities a terminal has, using these methods (as described by the wikipedia article linked above):

Most implementations of curses use a database that can describe the capabilities of thousands of different terminals. There are a few implementations, such as PDCurses, which use specialized device drivers rather than a terminal database. Most implementations use terminfo; some use termcap. Curses has the advantage of back-portability to character-cell terminals and simplicity. For an application that does not require bit-mapped graphics or multiple fonts, an interface implementation using curses will usually be much simpler and faster than one using an X toolkit.

Most of the time, curses will poll terminfo and will then be able to understand how to manipulate the cursor and text attributes. Then, you, the programmer, use the API provided by curses to manipulate the cursor or change the text color or other attributes if the functionality you seek is desired.

Example with Python

I find python is really easy to use, but if you want to use curses in a different programming language, then simply search it on duckduckgo or any other search engine. :) Here is a quick example in python 3:

import curses

def main(stdscr):
    # allow curses to use default foreground/background (39/49)
    curses.use_default_colors()

    # Clear screen
    stdscr.clear()

    curses.init_pair(1, curses.COLOR_RED, -1)
    curses.init_pair(2, curses.COLOR_GREEN, -1)
    stdscr.addstr("ERROR: I like tacos, but I don't have any.\n", curses.color_pair(1))
    stdscr.addstr("SUCCESS: I found some tacos.\n", curses.color_pair(2))

    stdscr.refresh() # make sure screen is refreshed
    stdscr.getkey()  # wait for user to press key

if __name__ == '__main__':
    curses.wrapper(main)

result:

enter image description here

You might think to yourself that this is a much more round-about way of doing things, but it really is much more cross-platform (really cross-terminal … at least in the unix- and unix-like-platform world). For colors, it is not quite as important, but when it comes to supporting other multi-sequence escape sequences (such as Home, End, Page Up, Page Down, etc), then curses becomes all the more important.

Example with Tput

  • tput is a command line utility for manipulating cursor and text
  • tput comes with the curses package. If you want to use cross-terminal (ish) applications in the terminal, you should use tput, as it parses terminfo or whatever it needs to and uses a set of standardized commands (like curses) and returns the correct escape sequence.
  • example:
echo "$(tput setaf 1)$(tput bold)ERROR:$(tput sgr0)$(tput setaf 1) My tacos have gone missing"
echo "$(tput setaf 2)$(tput bold)SUCCESS:$(tput sgr0)$(tput setaf 2) Oh good\! I found my tacos\!"

Result:

example with tput

More Info on Tput

How can I install packages using pip according to the requirements.txt file from a local directory?

Short answer

pip install -r /path/to/requirements.txt

or in another form:

python -m pip install -r /path/to/requirements.txt

Explanation

Here, -r is short form of --requirement and it asks the pip to install from the given requirements file.

pip will start installation only after checking the availability of all listed items in the requirements file and it won't start installation even if one requirement is unavailable.

One workaround to install the available packages is installing listed packages one by one. Use the following command for that. A red color warning will be shown to notify you about the unavailable packages.

cat requirements.txt | xargs -n 1 pip install

To ignore comments (lines starting with a #) and blank lines, use:

cat requirements.txt | cut -f1 -d"#" | sed '/^\s*$/d' | xargs -n 1 pip install

Controlling Spacing Between Table Cells

table.test td {
    background-color: lime;
    padding: 12px;
    border:2px solid #fff;border-collapse:separate;
}

How do I use reflection to call a generic method?

Nobody provided the "classic Reflection" solution, so here is a complete code example:

using System;
using System.Collections;
using System.Collections.Generic;

namespace DictionaryRuntime
{
    public class DynamicDictionaryFactory
    {
        /// <summary>
        /// Factory to create dynamically a generic Dictionary.
        /// </summary>
        public IDictionary CreateDynamicGenericInstance(Type keyType, Type valueType)
        {
            //Creating the Dictionary.
            Type typeDict = typeof(Dictionary<,>);

            //Creating KeyValue Type for Dictionary.
            Type[] typeArgs = { keyType, valueType };

            //Passing the Type and create Dictionary Type.
            Type genericType = typeDict.MakeGenericType(typeArgs);

            //Creating Instance for Dictionary<K,T>.
            IDictionary d = Activator.CreateInstance(genericType) as IDictionary;

            return d;

        }
    }
}

The above DynamicDictionaryFactory class has a method

CreateDynamicGenericInstance(Type keyType, Type valueType)

and it creates and returns an IDictionary instance, the types of whose keys and values are exactly the specified on the call keyType and valueType.

Here is a complete example how to call this method to instantiate and use a Dictionary<String, int> :

using System;
using System.Collections.Generic;

namespace DynamicDictionary
{
    class Test
    {
        static void Main(string[] args)
        {
            var factory = new DictionaryRuntime.DynamicDictionaryFactory();
            var dict = factory.CreateDynamicGenericInstance(typeof(String), typeof(int));

            var typedDict = dict as Dictionary<String, int>;

            if (typedDict != null)
            {
                Console.WriteLine("Dictionary<String, int>");

                typedDict.Add("One", 1);
                typedDict.Add("Two", 2);
                typedDict.Add("Three", 3);

                foreach(var kvp in typedDict)
                {
                    Console.WriteLine("\"" + kvp.Key + "\": " + kvp.Value);
                }
            }
            else
                Console.WriteLine("null");
        }
    }
}

When the above console application is executed, we get the correct, expected result:

Dictionary<String, int>
"One": 1
"Two": 2
"Three": 3

How to replace multiple substrings of a string?

Here my $0.02. It is based on Andrew Clark's answer, just a little bit clearer, and it also covers the case when a string to replace is a substring of another string to replace (longer string wins)

def multireplace(string, replacements):
    """
    Given a string and a replacement map, it returns the replaced string.

    :param str string: string to execute replacements on
    :param dict replacements: replacement dictionary {value to find: value to replace}
    :rtype: str

    """
    # Place longer ones first to keep shorter substrings from matching
    # where the longer ones should take place
    # For instance given the replacements {'ab': 'AB', 'abc': 'ABC'} against 
    # the string 'hey abc', it should produce 'hey ABC' and not 'hey ABc'
    substrs = sorted(replacements, key=len, reverse=True)

    # Create a big OR regex that matches any of the substrings to replace
    regexp = re.compile('|'.join(map(re.escape, substrs)))

    # For each match, look up the new string in the replacements
    return regexp.sub(lambda match: replacements[match.group(0)], string)

It is in this this gist, feel free to modify it if you have any proposal.

How to define multiple CSS attributes in jQuery?

$('#message').css({ width: 550, height: 300, 'font-size': '8pt' });

For homebrew mysql installs, where's my.cnf?

Server version: 8.0.19 Homebrew. macOS Catalina 10.15.5 and installed MySQL via Homebrew. Found this file here:

/usr/local/etc/my.cnf

This solution helped :)

How do I return multiple values from a function in C?

Use pointers as your function parameters. Then use them to return multiple value.

CS0234: Mvc does not exist in the System.Web namespace

This problem can happen when you deploy your web application to a server, so you must check if you already installed MVC3.

Check if the folder C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 3 exists.

If it doesn't exist, you need to install it from http://www.microsoft.com/en-us/download/details.aspx?id=1491


If you wont to install you can add all DLLs locally in bin folder and add references to them this work fine if you host on server don't deploy ASP.NET Web Pages or MVC3.

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

Linux command to list all available commands and aliases

compgen -c > list.txt && wc list.txt

How to dismiss keyboard for UITextView with return key?

You can also hide keyboard when touch in view screen:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
     UITouch * touch = [touches anyObject];
     if(touch.phase == UITouchPhaseBegan) {
        [txtDetail resignFirstResponder];
      }
 }

Find size of an array in Perl

First, the second is not equivalent to the other two. $#array returns the last index of the array, which is one less than the size of the array.

The other two are virtually the same. You are simply using two different means to create scalar context. It comes down to a question of readability.

I personally prefer the following:

say 0+@array;          # Represent @array as a number

I find it clearer than

say scalar(@array);    # Represent @array as a scalar

and

my $size = @array;
say $size;

The latter looks quite clear alone like this, but I find that the extra line takes away from clarity when part of other code. It's useful for teaching what @array does in scalar context, and maybe if you want to use $size more than once.

Set environment variables from file of key/value pairs

If env supports the -S option one may use newlines or escape characters like \n or \t (see env):

env -S "$(cat .env)" command

.env file example:

KEY="value with space\nnewline\ttab\tand
multiple
lines"

Test:

env -S "$(cat .env)" sh -c 'echo "$KEY"'

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

Backout restores or undoes our changes. The way it does this is that, P4 undoes the changes in a changelist (default or new) on our local workspace. We then have to submit/commit this backedout changelist as we do other changeslists. The second part is important here, as it doesn't automatically backout the changelist on the server, we have to submit the backedout changelist (which makes sense after you do it, but i was initially assuming it does that automatically).

As pointed by others, Rollback has greater powers - It can restore changes to a specific date, changelist or a revision#

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

Just pressing F5 is not always working.

why?

Because your ISP is also caching web data for you.

Solution: Force Refresh.

Force refresh your browser by pressing CTRL + F5 in Firefox or Chrome to clear ISP cache too, instead of just pressing F5

You then can see 200 response instead of 304 in the browser F12 developer tools network tab.

Another trick is to add question mark ? at the end of the URL string of the requested page:

http://localhost:52199/Customers/Create?

The question mark will ensure that the browser refresh the request without caching any previous requests.

Additionally in Visual Studio you can set the default browser to Chrome in Incognito mode to avoid cache issues while developing, by adding Chrome in Incognito mode as default browser, see the steps (self illustrated):

Go to browsers list Select browse with... Click Add... Point to the chrome.exe on your platform, add argument "Incognito" Choose the browser you just added and set as default, then click browse

TypeError: $ is not a function WordPress

Function errors are a common thing in almost all content management systems and there is a few ways you can approach this.

  1. Wrap your code using:

    <script> 
    jQuery(function($) {
    
    YOUR CODE GOES HERE
    
    });
    </script>
    
  2. You can also use jQuery's API using noConflict();

    <script>
    $.noConflict();
    jQuery( document ).ready(function( $ ) {
    // Code that uses jQuery's $ can follow here.
    });
    // Code that uses other library's $ can follow here.
    </script>
    
  3. Another example of using noConflict without using document ready:

    <script>
    jQuery.noConflict();
        (function( $ ) {
            $(function() { 
                // YOUR CODE HERE
            });
         });
    </script>
    
  4. You could even choose to create your very alias to avoid conflicts like so:

    var jExample = jQuery.noConflict();
    // Do something with jQuery
    jExample( "div p" ).hide();
    
  5. Yet another longer solution is to rename all referances of $ to jQuery:

    $( "div p" ).hide(); to jQuery( "div p" ).hide();

Comparing Dates in Oracle SQL

You can use trunc and to_date as follows:

select TO_CHAR (g.FECHA, 'DD-MM-YYYY HH24:MI:SS') fecha_salida, g.NUMERO_GUIA, g.BOD_ORIGEN, g.TIPO_GUIA, dg.DOC_NUMERO, dg.* 
from ils_det_guia dg, ils_guia g
where dg.NUMERO_GUIA = g.NUMERO_GUIA and dg.TIPO_GUIA = g.TIPO_GUIA and dg.BOD_ORIGEN = g.BOD_ORIGEN
and dg.LAB_CODIGO = 56 
and trunc(g.FECHA) > to_date('01/02/15','DD/MM/YY')
order by g.FECHA;

Cannot load properties file from resources directory

If the file is placed under target/classes after compiling, then it is already in a directory that is part of the build path. The directory src/main/resources is the Maven default directory for such resources, and it is automatically placed to the build path by the Eclipse Maven plugin (M2E). So, there is no need to move your properties file.

The other topic is, how to retrieve such resources. Resources in the build path are automatically in the class path of the running Java program. Considering this, you should always load such resources with a class loader. Example code:

String resourceName = "myconf.properties"; // could also be a constant
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
try(InputStream resourceStream = loader.getResourceAsStream(resourceName)) {
    props.load(resourceStream);
}
// use props here ...

How to round up a number in Javascript?

/**
 * @param num The number to round
 * @param precision The number of decimal places to preserve
 */
function roundUp(num, precision) {
  precision = Math.pow(10, precision)
  return Math.ceil(num * precision) / precision
}

roundUp(192.168, 1) //=> 192.2

Android emulator: How to monitor network traffic?

Yes, wireshark will work.

I don't think there is any easy way to filter out solely emulator traffic, since it is coming from the same src IP.

Perhaps the best way would be to set up a very bare VMware environment and only run the emulator in there, at least that way there wouldn't be too much background traffic.

Subprocess check_output returned non-zero exit status 1

The command yum that you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yum command to fix that.

Your code could show this error this way:

import subprocess
try:
    subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

Insert default value when parameter is null

The pattern I generally use is to create the row without the columns that have default constraints, then update the columns to replace the default values with supplied values (if not null).

Assuming col1 is the primary key and col4 and col5 have a default contraint

-- create initial row with default values
insert table1 (col1, col2, col3)
    values (@col1, @col2, @col3)

-- update default values, if supplied
update table1
    set col4 = isnull(@col4, col4),
        col5 = isnull(@col5, col5)
    where col1 = @col1

If you want the actual values defaulted into the table ...

-- create initial row with default values
insert table1 (col1, col2, col3)
    values (@col1, @col2, @col3)

-- create a container to hold the values actually inserted into the table
declare @inserted table (col4 datetime, col5 varchar(50))

-- update default values, if supplied
update table1
    set col4 = isnull(@col4, col4),
        col5 = isnull(@col5, col5)
    output inserted.col4, inserted.col5 into @inserted (col4, col5)
    where col1 = @col1

-- get the values defaulted into the table (optional)
select @col4 = col4, @col5 = col5 from @inserted

Cheers...

Specifing width of a flexbox flex item: width or basis?

The bottom statement is equivalent to:

.half {
   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: 50%;
}

Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.

Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.

I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)

How can change width of dropdown list?

This:

<select style="width: XXXpx;">

XXX = Any Number

Works great in Google Chrome v70.0.3538.110

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • Cause of No suitable driver found for

    I had the same problem with spring, commons-dbcp and oracle 10g. Using this URL I got the 'no suitable driver' error: jdbc:oracle:[email protected]:1521:kinangop

    The above URL is missing a full colon just before the @. After correcting that, the error disappeared.

    String.Format like functionality in T-SQL?

    take a look at xp_sprintf. example below.

    DECLARE @ret_string varchar (255)
    EXEC xp_sprintf @ret_string OUTPUT, 
        'INSERT INTO %s VALUES (%s, %s)', 'table1', '1', '2'
    PRINT @ret_string
    

    Result looks like this:

    INSERT INTO table1 VALUES (1, 2)
    

    Just found an issue with the max size (255 char limit) of the string with this so there is an alternative function you can use:

    create function dbo.fnSprintf (@s varchar(MAX), 
                    @params varchar(MAX), @separator char(1) = ',')
    returns varchar(MAX)
    as
    begin
    declare @p varchar(MAX)
    declare @paramlen int
    
    set @params = @params + @separator
    set @paramlen = len(@params)
    while not @params = ''
    begin
        set @p = left(@params+@separator, charindex(@separator, @params)-1)
        set @s = STUFF(@s, charindex('%s', @s), 2, @p)
        set @params = substring(@params, len(@p)+2, @paramlen)
    end
    return @s
    end
    

    To get the same result as above you call the function as follows:

    print dbo.fnSprintf('INSERT INTO %s VALUES (%s, %s)', 'table1,1,2', default)
    

    Backporting Python 3 open(encoding="utf-8") to Python 2

    Not a general answer, but may be useful for the specific case where you are happy with the default python 2 encoding, but want to specify utf-8 for python 3:

    if sys.version_info.major > 2:
        do_open = lambda filename: open(filename, encoding='utf-8')
    else:
        do_open = lambda filename: open(filename)
    
    with do_open(filename) as file:
        pass
    

    Using colors with printf

    #include <stdio.h>
    
    //fonts color
    #define FBLACK      "\033[30;"
    #define FRED        "\033[31;"
    #define FGREEN      "\033[32;"
    #define FYELLOW     "\033[33;"
    #define FBLUE       "\033[34;"
    #define FPURPLE     "\033[35;"
    #define D_FGREEN    "\033[6;"
    #define FWHITE      "\033[7;"
    #define FCYAN       "\x1b[36m"
    
    //background color
    #define BBLACK      "40m"
    #define BRED        "41m"
    #define BGREEN      "42m"
    #define BYELLOW     "43m"
    #define BBLUE       "44m"
    #define BPURPLE     "45m"
    #define D_BGREEN    "46m"
    #define BWHITE      "47m"
    
    //end color
    #define NONE        "\033[0m"
    
    int main(int argc, char *argv[])
    {
        printf(D_FGREEN BBLUE"Change color!\n"NONE);
    
        return 0;
    }
    

    Handling very large numbers in Python

    python supports arbitrarily large integers naturally:

    example:

    >>> 10**1000
    10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    

    You could even get, for example of a huge integer value, fib(4000000).

    But still it does not (for now) supports an arbitrarily large float !!

    If you need one big, large, float then check up on the decimal Module. There are examples of use on these foruns: OverflowError: (34, 'Result too large')

    Another reference: http://docs.python.org/2/library/decimal.html

    You can even using the gmpy module if you need a speed-up (which is likely to be of your interest): Handling big numbers in code

    Another reference: https://code.google.com/p/gmpy/

    Split string with delimiters in C

    Below is my strtok() implementation from zString library. zstring_strtok() differs from standard library's strtok() in the way it treats consecutive delimiters.

    Just have a look at the code below,sure that you will get an idea about how it works (I tried to use as many comments as I could)

    char *zstring_strtok(char *str, const char *delim) {
        static char *static_str=0;      /* var to store last address */
        int index=0, strlength=0;       /* integers for indexes */
        int found = 0;                  /* check if delim is found */
    
        /* delimiter cannot be NULL
        * if no more char left, return NULL as well
        */
        if (delim==0 || (str == 0 && static_str == 0))
            return 0;
    
        if (str == 0)
            str = static_str;
    
        /* get length of string */
        while(str[strlength])
            strlength++;
    
        /* find the first occurance of delim */
        for (index=0;index<strlength;index++)
            if (str[index]==delim[0]) {
                found=1;
                break;
            }
    
        /* if delim is not contained in str, return str */
        if (!found) {
            static_str = 0;
            return str;
        }
    
        /* check for consecutive delimiters
        *if first char is delim, return delim
        */
        if (str[0]==delim[0]) {
            static_str = (str + 1);
            return (char *)delim;
        }
    
        /* terminate the string
        * this assignmetn requires char[], so str has to
        * be char[] rather than *char
        */
        str[index] = '\0';
    
        /* save the rest of the string */
        if ((str + index + 1)!=0)
            static_str = (str + index + 1);
        else
            static_str = 0;
    
            return str;
    }
    

    Below is an example usage...

      Example Usage
          char str[] = "A,B,,,C";
          printf("1 %s\n",zstring_strtok(s,","));
          printf("2 %s\n",zstring_strtok(NULL,","));
          printf("3 %s\n",zstring_strtok(NULL,","));
          printf("4 %s\n",zstring_strtok(NULL,","));
          printf("5 %s\n",zstring_strtok(NULL,","));
          printf("6 %s\n",zstring_strtok(NULL,","));
    
      Example Output
          1 A
          2 B
          3 ,
          4 ,
          5 C
          6 (null)
    

    The library can be downloaded from Github https://github.com/fnoyanisi/zString

    Php, wait 5 seconds before executing an action

    before starting your actions, use

     sleep(5);
    

    ThreadStart with parameters

    As has already been mention in various answers here, the Thread class currently (4.7.2) provides several constructors and a Start method with overloads.

    These relevant constructors for this question are:

    public Thread(ThreadStart start);
    

    and

    public Thread(ParameterizedThreadStart start);
    

    which either take a ThreadStart delegate or a ParameterizedThreadStart delegate.

    The corresponding delegates look like this:

    public delegate void ThreadStart();
    public delegate void ParameterizedThreadStart(object obj);
    

    So as can be seen, the correct constructor to use seems to be the one taking a ParameterizedThreadStart delegate so that some method conform to the specified signature of the delegate can be started by the thread.

    A simple example for instanciating the Thread class would be

    Thread thread = new Thread(new ParameterizedThreadStart(Work));
    

    or just

    Thread thread = new Thread(Work);
    

    The signature of the corresponding method (called Work in this example) looks like this:

    private void Work(object data)
    {
       ...
    }
    

    What is left is to start the thread. This is done by using either

    public void Start();
    

    or

    public void Start(object parameter);
    

    While Start() would start the thread and pass null as data to the method, Start(...) can be used to pass anything into the Work method of the thread.

    There is however one big problem with this approach: Everything passed into the Work method is cast into an object. That means within the Work method it has to be cast to the original type again like in the following example:

    public static void Main(string[] args)
    {
        Thread thread = new Thread(Work);
    
        thread.Start("I've got some text");
        Console.ReadLine();
    }
    
    private static void Work(object data)
    {
        string message = (string)data; // Wow, this is ugly
    
        Console.WriteLine($"I, the thread write: {message}");
    }
    



    Casting is something you typically do not want to do.

    What if someone passes something else which is not a string? As this seems not possible at first (because It is my method, I know what I do or The method is private, how should someone ever be able to pass anything to it?) you may possibly end up with exactly that case for various reasons. As some cases may not be a problem, others are. In such cases you will probably end up with an InvalidCastException which you probably will not notice because it simply terminates the thread.

    As a solution you would expect to get a generic ParameterizedThreadStart delegate like ParameterizedThreadStart<T> where T would be the type of data you want to pass into the Work method. Unfortunately something like this does not exist (yet?).

    There is however a suggested solution to this issue. It involves creating a class which contains both, the data to be passed to the thread as well as the method that represents the worker method like this:

    public class ThreadWithState
    {
        private string message;
    
        public ThreadWithState(string message)
        {
            this.message = message;
        }
    
        public void Work()
        {
            Console.WriteLine($"I, the thread write: {this.message}");
        }
    }
    

    With this approach you would start the thread like this:

    ThreadWithState tws = new ThreadWithState("I've got some text");
    Thread thread = new Thread(tws.Work);
    
    thread.Start();
    

    So in this way you simply avoid casting around and have a typesafe way of providing data to a thread ;-)

    The performance impact of using instanceof in Java

    instanceof is probably going to be more costly than a simple equals in most real world implementations (that is, the ones where instanceof is really needed, and you can't just solve it by overriding a common method, like every beginner textbook as well as Demian above suggest).

    Why is that? Because what is probably going to happen is that you have several interfaces, that provide some functionality (let's say, interfaces x, y and z), and some objects to manipulate that may (or not) implement one of those interfaces... but not directly. Say, for instance, I have:

    w extends x

    A implements w

    B extends A

    C extends B, implements y

    D extends C, implements z

    Suppose I am processing an instance of D, the object d. Computing (d instanceof x) requires to take d.getClass(), loop through the interfaces it implements to know whether one is == to x, and if not do so again recursively for all of their ancestors... In our case, if you do a breadth first exploration of that tree, yields at least 8 comparisons, supposing y and z don't extend anything...

    The complexity of a real-world derivation tree is likely to be higher. In some cases, the JIT can optimize most of it away, if it is able to resolve in advance d as being, in all possible cases, an instance of something that extends x. Realistically, however, you are going to go through that tree traversal most of the time.

    If that becomes an issue, I would suggest using a handler map instead, linking the concrete class of the object to a closure that does the handling. It removes the tree traversal phase in favor of a direct mapping. However, beware that if you have set a handler for C.class, my object d above will not be recognized.

    here are my 2 cents, I hope they help...

    sqlite copy data from one table to another

    I've been wrestling with this, and I know there are other options, but I've come to the conclusion the safest pattern is:

    create table destination_old as select * from destination;
    
    drop table destination;
    
    create table destination as select
    d.*, s.country
    from destination_old d left join source s
    on d.id=s.id;
    

    It's safe because you have a copy of destination before you altered it. I suspect that update statements with joins weren't included in SQLite because they're powerful but a bit risky.

    Using the pattern above you end up with two country fields. You can avoid that by explicitly stating all of the columns you want to retrieve from destination_old and perhaps using coalesce to retrieve the values from destination_old if the country field in source is null. So for example:

    create table destination as select
    d.field1, d.field2,...,coalesce(s.country,d.country) country
    from destination_old d left join source s
    on d.id=s.id;
    

    How can I parse a YAML file from a Linux shell script?

    Whenever you need a solution for "How to work with YAML/JSON/compatible data from a shell script" which works on just about every OS with Python (*nix, OSX, Windows), consider yamlpath, which provides several command-line tools for reading, writing, searching, and merging YAML, EYAML, JSON, and compatible files. Since just about every OS either comes with Python pre-installed or it is trivial to install, this makes yamlpath highly portable. Even more interesting: this project defines an intuitive path language with very powerful, command-line-friendly syntax that enables accessing one or more nodes.

    To your specific question and after installing yamlpath using Python's native package manager or your OS's package manager (yamlpath is available via RPM to some OSes):

    #!/bin/bash
    # Read values directly from YAML (or EYAML, JSON, etc) for use in this shell script:
    myShellVar=$(yaml-get --query=any.path.no[matter%how].complex source-file.yaml)
    
    # Use the value any way you need:
    echo "Retrieved ${myShellVar}"
    
    # Perhaps change the value and write it back:
    myShellVar="New Value"
    yaml-set --change=/any/path/no[matter%how]/complex --value="$myShellVar" source-file.yaml
    

    You didn't specify that the data was a simple Scalar value though, so let's up the ante. What if the result you want is an Array? Even more challenging, what if it's an Array-of-Hashes and you only want one property of each result? Suppose further that your data is actually spread out across multiple YAML files and you need all the results in a single query. That's a much more interesting question to demonstrate with. So, suppose you have these two YAML files:

    File: data1.yaml

    ---
    baubles:
      - name: Doohickey
        sku: 0-000-1
        price: 4.75
        weight: 2.7g
      - name: Doodad
        sku: 0-000-2
        price: 10.5
        weight: 5g
      - name: Oddball
        sku: 0-000-3
        price: 25.99
        weight: 25kg
    

    File: data2.yaml

    ---
    baubles:
      - name: Fob
        sku: 0-000-4
        price: 0.99
        weight: 18mg
      - name: Doohickey
        price: 10.5
      - name: Oddball
        sku: 0-000-3
        description: This ball is odd
    

    How would you report only the sku of every item in inventory after applying the changes from data2.yaml to data1.yaml, all from a shell script? Try this:

    #!/bin/bash
    baubleSKUs=($(yaml-merge --aoh=deep data1.yaml data2.yaml | yaml-get --query=/baubles/sku -))
    
    for sku in "${baubleSKUs[@]}"; do
        echo "Found bauble SKU:  ${sku}"
    done
    

    You get exactly what you need from only a few lines of code:

    Found bauble SKU:  0-000-1
    Found bauble SKU:  0-000-2
    Found bauble SKU:  0-000-3
    Found bauble SKU:  0-000-4
    

    As you can see, yamlpath turns very complex problems into trivial solutions. Note that the entire query was handled as a stream; no YAML files were changed by the query and there were no temp files.

    I realize this is "yet another tool to solve the same question" but after reading the other answers here, yamlpath appears more portable and robust than most alternatives. It also fully understands YAML/JSON/compatible files and it does not need to convert YAML to JSON to perform requested operations. As such, comments within the original YAML file are preserved whenever you need to change data in the source YAML file. Like some alternatives, yamlpath is also portable across OSes. More importantly, yamlpath defines a query language that is extremely powerful, enabling very specialized/filtered data queries. It can even operate against results from disparate parts of the file in a single query.

    If you want to get or set many values in the data at once -- including complex data like hashes/arrays/maps/lists -- yamlpath can do that. Want a value but don't know precisely where it is in the document? yamlpath can find it and give you the exact path(s). Need to merge multiple data file together, including from STDIN? yamlpath does that, too. Further, yamlpath fully comprehends YAML anchors and their aliases, always giving or changing exactly the data you expect whether it is a concrete or referenced value.

    Disclaimer: I wrote and maintain yamlpath, which is based on ruamel.yaml, which is in turn based on PyYAML. As such, yamlpath is fully standards-compliant.

    How to import existing Git repository into another?

    If you want to retain the exact commit history of the second repository and therefore also retain the ability to easily merge upstream changes in the future then here is the method you want. It results in unmodified history of the subtree being imported into your repo plus one merge commit to move the merged repository to the subdirectory.

    git remote add XXX_remote <path-or-url-to-XXX-repo>
    git fetch XXX_remote
    git merge -s ours --no-commit --allow-unrelated-histories XXX_remote/master
    git read-tree --prefix=ZZZ/ -u XXX_remote/master
    git commit -m "Imported XXX as a subtree."
    

    You can track upstream changes like so:

    git pull -s subtree XXX_remote master
    

    Git figures out on its own where the roots are before doing the merge, so you don't need to specify the prefix on subsequent merges.

    The downside is that in the merged history the files are unprefixed (not in a subdirectory). As a result git log ZZZ/a will show you all the changes (if any) except those in the merged history. You can do:

    git log --follow -- a
    

    but that won't show the changes other then in the merged history.

    In other words, if you don't change ZZZ's files in repository XXX, then you need to specify --follow and an unprefixed path. If you change them in both repositories, then you have 2 commands, none of which shows all the changes.

    Git versions before 2.9: You don’t need to pass the --allow-unrelated-histories option to git merge.

    The method in the other answer that uses read-tree and skips the merge -s ours step is effectively no different than copying the files with cp and committing the result.

    Original source was from github's "Subtree Merge" help article. And another useful link.

    Android: View.setID(int id) programmatically - how to avoid ID conflicts?

    From API level 17 and above, you can call: View.generateViewId()

    Then use View.setId(int).

    If your app is targeted lower than API level 17, use ViewCompat.generateViewId()