Programs & Examples On #Info hash

foreach for JSON array , syntax

Try this:

$.each(result,function(index, value){
    console.log('My array has at position ' + index + ', this value: ' + value);
});

Java Synchronized list

That should be fine as long as you don't require the "remove" method to be atomic.

In other words, if the "do something" checks that the item appears more than once in the list for example, it is possible that the result of that check will be wrong by the time you reach the next line.

Also, make sure you synchronize on the list when iterating:

synchronized(list) {
    for (Object o : list) {}
}

As mentioned by Peter Lawrey, CopyOnWriteArrayList can make your life easier and can provide better performance in a highly concurrent environment.

Set adb vendor keys

look at this url Android adb devices unauthorized else briefly do the following:

  1. look for adbkey with not extension in the platform-tools/.android and delete this file
  2. look at C:\Users\*username*\.android) and delete adbkey
  3. C:\Windows\System32\config\systemprofile\.android and delete adbkey

You may find it in one of the directories above. Or just search adbkey in the Parent folders above then locate and delete.

How can I create an array/list of dictionaries in python?

This is how I did it and it works:

dictlist = [dict() for x in range(n)]

It gives you a list of n empty dictionaries.

Method to get all files within folder and subfolders that will return a list

Simply use this:

public static List<String> GetAllFiles(String directory)
{
    return Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).ToList();
}

And if you want every file, even extensionless ones:

public static List<String> GetAllFiles(String directory)
{
    return Directory.GetFiles(directory, "*", SearchOption.AllDirectories).ToList();
}

How can I change the default Mysql connection timeout when connecting through python?

MAX_EXECUTION_TIME is also an important parameter for long running queries.Will work for MySQL 5.7 or later.

Check the current value

SELECT @@GLOBAL.MAX_EXECUTION_TIME, @@SESSION.MAX_EXECUTION_TIME;

Then set it according to your needs.

SET SESSION MAX_EXECUTION_TIME=2000;
SET GLOBAL MAX_EXECUTION_TIME=2000;

jQuery remove selected option from this

This should do the trick:

$('#some_select_box').click(function() {
  $('option:selected', this ).remove();
});

Skip the headers when editing a csv file using Python

Your reader variable is an iterable, by looping over it you retrieve the rows.

To make it skip one item before your loop, simply call next(reader, None) and ignore the return value.

You can also simplify your code a little; use the opened files as context managers to have them closed automatically:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   reader = csv.reader(infile)
   next(reader, None)  # skip the headers
   writer = csv.writer(outfile)
   for row in reader:
       # process each row
       writer.writerow(row)

# no need to close, the files are closed automatically when you get to this point.

If you wanted to write the header to the output file unprocessed, that's easy too, pass the output of next() to writer.writerow():

headers = next(reader, None)  # returns the headers or `None` if the input is empty
if headers:
    writer.writerow(headers)

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]

A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.

From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.

Remove all special characters, punctuation and spaces from string

After seeing this, I was interested in expanding on the provided answers by finding out which executes in the least amount of time, so I went through and checked some of the proposed answers with timeit against two of the example strings:

  • string1 = 'Special $#! characters spaces 888323'
  • string2 = 'how much for the maple syrup? $20.99? That s ricidulous!!!'

Example 1

'.join(e for e in string if e.isalnum())

  • string1 - Result: 10.7061979771
  • string2 - Result: 7.78372597694

Example 2

import re re.sub('[^A-Za-z0-9]+', '', string)

  • string1 - Result: 7.10785102844
  • string2 - Result: 4.12814903259

Example 3

import re re.sub('\W+','', string)

  • string1 - Result: 3.11899876595
  • string2 - Result: 2.78014397621

The above results are a product of the lowest returned result from an average of: repeat(3, 2000000)

Example 3 can be 3x faster than Example 1.

How to convert String into Hashmap in java

This is one solution. If you want to make it more generic, you can use the StringUtils library.

String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1);           //remove curly brackets
String[] keyValuePairs = value.split(",");              //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();               

for(String pair : keyValuePairs)                        //iterate over the pairs
{
    String[] entry = pair.split("=");                   //split the pairs to get key and value 
    map.put(entry[0].trim(), entry[1].trim());          //add them to the hashmap and trim whitespaces
}

For example you can switch

 value = value.substring(1, value.length()-1);

to

 value = StringUtils.substringBetween(value, "{", "}");

if you are using StringUtils which is contained in apache.commons.lang package.

Lists: Count vs Count()

Always prefer Count and Length properties on a type over the extension method Count(). The former is an O(1) for every type which contains them. The Count() extension method has some type check optimizations that can cause it to run also in O(1) time but will degrade to O(N) if the underlying collection is not one of the few types it knows about.

VBA paste range

This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:

'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Sub CopyLayout(TargetRange As Range, typee As Integer)
    Application.ScreenUpdating = False
        Dim ncolumn As Integer
        Dim nrow As Integer

        SheetLayout.Activate
    If (typee = 1) Then 'is installation
        Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    ElseIf (typee = 2) Then 'is package
        Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    End If

    Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@

    If typee = 1 Then
       nrow = SheetLayout.Range("installationlayout").Rows.Count
       ncolumn = SheetLayout.Range("installationlayout").Columns.Count

       Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    ElseIf typee = 2 Then
       nrow = SheetLayout.Range("PackageLayout").Rows.Count
       ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
       Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    End If
    Range("A1").Select 'Deselect the created table

    Application.CutCopyMode = False
    Application.ScreenUpdating = True
End Sub

'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
    Dim R As Long, C As Long

    For R = 1 To RowCount
        PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
        If R >= 2 And R < RowCount Then
            PastedTable.Rows(R).Group 'Main group of the table
        End If
        If R = 2 Then
            PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
        ElseIf (R = 4 And typee = 1) Then
            PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
        End If
    Next R

    For C = 1 To ColumnCount
        PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
    Next C
End Function



Sub test ()
    Call CopyLayout(Sheet2.Range("A18"), 2)
end sub

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

I had the same problem as above and Eclipse suggested installing:

Hint: On 64-bit systems, make sure the 32-bit libraries are installed:   
   "sudo apt-get install ia32-libs"    
or on some systems,  
   "sudo apt-get install lib32z1"   

When I tried to install ia32-libs, Ubuntu prompted to install three other packages:

$ sudo apt-get install ia32-libs  
Reading package lists... Done  
Building dependency tree         
Reading state information... Done  
Package ia32-libs is not available, but is referred to by another package.  
This may mean that the package is missing, has been obsoleted, or  
is only available from another source  
However the following packages replace it:  
  lib32z1 lib32ncurses5 lib32bz2-1.0  

E: Package 'ia32-libs' has no installation candidate  
$   
$ sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0    

With Android Studio and intellij, I also had to install the 32bit version of libstdc++6:

sudo apt-get install lib32stdc++6

Difference between | and || or & and && for comparison

The & and | are usually bitwise operations.

Where as && and || are usually logical operations.

For comparison purposes, it's perfectly fine provided that everything returns either a 1 or a 0. Otherwise, it can return false positives. You should avoid this though to prevent hard to read bugs.

How can I scale an image in a CSS sprite

This seems to work for me.

If the sprites are in grid, set the background-size to 100% number of sprites across and 100% number of sprites down. Then use background-position -<x*100>% -<y*100>% where x and y are the zero based sprite

In other words if you want the 3rd sprite from the left and 2nd row that's 2 over and 1 down so

background-position: -200% -100%;

For example here's a sprite sheet 4x2 sprites

enter image description here

And here's an example

_x000D_
_x000D_
div {_x000D_
  margin: 3px;_x000D_
  display: inline-block;_x000D_
}_x000D_
.sprite {_x000D_
  background-image: url('https://i.stack.imgur.com/AEYNC.png');_x000D_
  background-size: 400% 200%;  /* 4x2 sprites so 400% 200% */_x000D_
}_x000D_
.s0x0 { background-position:    -0%   -0%; }_x000D_
.s1x0 { background-position:  -100%   -0%; }_x000D_
.s2x0 { background-position:  -200%   -0%; }_x000D_
.s3x0 { background-position:  -300%   -0%; }_x000D_
.s0x1 { background-position:    -0%  -100%; }_x000D_
.s1x1 { background-position:  -100%  -100%; }_x000D_
.s2x1 { background-position:  -200%  -100%; }_x000D_
.s3x1 { background-position:  -300%  -100%; }
_x000D_
<div class="sprite s3x1" style="width: 45px; height:20px"></div>_x000D_
<div class="sprite s3x1" style="width: 128px; height:30px"></div>_x000D_
<div class="sprite s3x1" style="width: 64px; height:56px"></div>_x000D_
<div class="sprite s2x1" style="width: 57px; height:60px"></div>_x000D_
<div class="sprite s3x0" style="width: 45px; height:45px"></div>_x000D_
<div class="sprite s0x1" style="width: 12px; height:100px"></div>_x000D_
_x000D_
<br/>_x000D_
<div class="sprite s0x0" style="width: 45px; height:20px"></div>_x000D_
<div class="sprite s1x0" style="width: 128px; height:45px"></div>_x000D_
<div class="sprite s2x0" style="width: 64px; height:56px"></div>_x000D_
<div class="sprite s3x0" style="width: 57px; height:60px"></div>_x000D_
<br/>_x000D_
<div class="sprite s0x1" style="width: 45px; height:45px"></div>_x000D_
<div class="sprite s1x1" style="width: 12px; height:50px"></div>_x000D_
<div class="sprite s2x1" style="width: 12px; height:50px"></div>_x000D_
<div class="sprite s3x1" style="width: 12px; height:50px"></div>
_x000D_
_x000D_
_x000D_

If the sprites are different sizes you'd need to set the background-size for each sprite to the a percent such that that sprite's width becomes 100%

In other words if image is 640px wide and the sprite inside that image is 45px wide then to get that 45px to be 640px

xScale = imageWidth / spriteWidth
xScale = 640 / 45
xScale = 14.2222222222
xPercent = xScale * 100
xPercent = 1422.22222222%

Then you need to set the offset. The complication of the offset is that 0% is aligned left and 100% is aligned right.

enter image description here

As a graphics programmer, I'd expect an offset of 100% to move the background 100% across the element, in other words entirely off the right side but that's not what 100% means when used with backgrouhnd-position. background-position: 100%; means right aligned. So, the forumla for taking that into account after scaling is

xOffsetScale = 1 + 1 / (xScale - 1)              
xOffset = offsetX * offsetScale / imageWidth

Assume the offset is 31px

xOffsetScale = 1 + 1 / (14.222222222 - 1)
xOffsetScale = 1.0756302521021115
xOffset = offsetX * xOffsetScale / imageWidth
xOffset = 31 * 1.0756302521021115 / 640
xOffset = 0.05210084033619603
xOffsetPercent = 5.210084033619603

Here's a 640x480 image with 2 sprites.

  1. at 31x 27y size 45w 32h
  2. at 500x 370y size 105w 65h

enter image description here

Following the math above for sprite 1

xScale = imageWidth / spriteWidth
xScale = 640 / 45
xScale = 14.2222222222
xPercent = xScale * 100
xPercent = 1422.22222222%

xOffsetScale = 1 + 1 / (14.222222222 - 1)
xOffsetScale = 1.0756302521021115
xOffset = offsetX * xOffsetScale / imageWidth
xOffset = 31 * 1.0756302521021115 / 640
xOffset = 0.05210084033619603
xOffsetPercent = 5.210084033619603

yScale = imageHeight / spriteHEight
yScale = 480 / 32
yScale = 15
yPercent = yScale * 100
yPercent = 1500%

yOffsetScale = 1 + 1 / (15 - 1)
yOffsetScale = 1.0714285714285714
yOffset = offsetY * yOffsetScale / imageHeight
yOffset = 27 * 1.0714285714285714 / 480
yOffset = 0.06026785714285714
yOffsetPercent = 6.026785714285714

_x000D_
_x000D_
div {_x000D_
  margin: 3px;_x000D_
  display: inline-block;_x000D_
}_x000D_
.sprite {_x000D_
  background-image: url('https://i.stack.imgur.com/mv9lJ.png');_x000D_
}_x000D_
.s1 {_x000D_
  background-size:      1422.2222% 1500%;_x000D_
  background-position:  5.210084033619603% 6.026785714285714%;_x000D_
}_x000D_
.s2 {_x000D_
  background-size:      609.5238095238095% 738.4615384615385%;_x000D_
  background-position:  93.45794392523367% 89.1566265060241%;_x000D_
}
_x000D_
<div class="sprite s1" style="width: 45px; height:20px"></div>_x000D_
<div class="sprite s1" style="width: 128px; height:30px"></div>_x000D_
<div class="sprite s1" style="width: 64px; height:56px"></div>_x000D_
<div class="sprite s1" style="width: 57px; height:60px"></div>_x000D_
<div class="sprite s1" style="width: 45px; height:45px"></div>_x000D_
<div class="sprite s1" style="width: 12px; height:50px"></div>_x000D_
<div class="sprite s1" style="width: 50px; height:40px"></div>_x000D_
<hr/>_x000D_
<div class="sprite s2" style="width: 45px; height:20px"></div>_x000D_
<div class="sprite s2" style="width: 128px; height:30px"></div>_x000D_
<div class="sprite s2" style="width: 64px; height:56px"></div>_x000D_
<div class="sprite s2" style="width: 57px; height:60px"></div>_x000D_
<div class="sprite s2" style="width: 45px; height:45px"></div>_x000D_
<div class="sprite s2" style="width: 12px; height:50px"></div>_x000D_
<div class="sprite s2" style="width: 50px; height:40px"></div>
_x000D_
_x000D_
_x000D_

Python TypeError: not enough arguments for format string

Note that the % syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:

instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)

This also fixes the error that you happened to have.

Animate scroll to ID on page load

try with following code. make elements with class name page-scroll and keep id name to href of corresponding links

$('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: ($($anchor.attr('href')).offset().top - 50)
        }, 1250, 'easeInOutExpo');
        event.preventDefault();
    });

Return rows in random order

Here's an example (source):

SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);

Python Prime number checker

def is_prime(n):
    return all(n%j for j in xrange(2, int(n**0.5)+1)) and n>1

Regular Expression Validation For Indian Phone Number and Mobile number

You can use regular expression like this.

/^[(]+\ ++\d{2}[)]+[^0]+\d{9}/

Is there a way to remove the separator line from a UITableView?

In interface Builder set table view separator "None"

enter image description here and those separator lines which are shown after the last cell can be remove by following approach. Best approach is to assign Empty View to tableView FooterView in viewDidLoad

self.tableView.tableFooterView = UIView()

How to add browse file button to Windows Form using C#

var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    string fileToOpen = FD.FileName;

    System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);

    //OR

    System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
    //etc
}

How can I group by date time column without taking time into consideration

I believe you need to group by , in that day of the month of the year . so why not using TRUNK_DATE functions . The way it works is described below :

Group By DATE_TRUNC('day' , 'occurred_at_time')

Insert new item in array on any position in PHP

Try this one:

$colors = array('red', 'blue', 'yellow');

$colors = insertElementToArray($colors, 'green', 2);


function insertElementToArray($arr = array(), $element = null, $index = 0)
{
    if ($element == null) {
        return $arr;
    }

    $arrLength = count($arr);
    $j = $arrLength - 1;

    while ($j >= $index) {
        $arr[$j+1] = $arr[$j];
        $j--;
    }

    $arr[$index] = $element;

    return $arr;
}

Sending Windows key using SendKeys

download InputSimulator from nuget package.

then write this:

        var simu = new InputSimulator();
        simu.Keyboard.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.VK_E);

in my case to create new vertial desktop, 3 keys needed and code like this(windows key + ctrl + D):

        simu.Keyboard.ModifiedKeyStroke(new[] { VirtualKeyCode.LWIN, VirtualKeyCode.CONTROL }, VirtualKeyCode.VK_D);

Display all dataframe columns in a Jupyter Python Notebook

I know this question is a little old but the following worked for me in a Jupyter Notebook running pandas 0.22.0 and Python 3:

import pandas as pd
pd.set_option('display.max_columns', <number of columns>)

You can do the same for the rows too:

pd.set_option('display.max_rows', <number of rows>)

This saves importing IPython, and there are more options in the pandas.set_option documentation: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.set_option.html

Git blame -- prior commits?

Building on the previous answer, this bash one-liner should give you what you're looking for. It displays the git blame history for a particular line of a particular file, through the last 5 revisions:

LINE=10 FILE=src/options.cpp REVS=5; for commit in $(git rev-list -n $REVS HEAD $FILE); do git blame -n -L$LINE,+1 $commit -- $FILE; done

In the output of this command, you might see the content of the line change, or the line number displayed might even change, for a particular commit.

This often indicates that the line was added for the first time, after that particular commit. It could also indicate the line was moved from another part of the file.

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

The CLASS_H is an include guard; it's used to avoid the same header file being included multiple times (via different routes) within the same CPP file (or, more accurately, the same translation unit), which would lead to multiple-definition errors.

Include guards aren't needed on CPP files because, by definition, the contents of the CPP file are only read once.

You seem to have interpreted the include guards as having the same function as import statements in other languages (such as Java); that's not the case, however. The #include itself is roughly equivalent to the import in other languages.

access key and value of object using *ngFor

You could create a custom pipe to return the list of key for each element. Something like that:

import { PipeTransform, Pipe } from '@angular/core';

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push(key);
    }
    return keys;
  }
}

and use it like that:

<tr *ngFor="let c of content">           
  <td *ngFor="let key of c | keys">{{key}}: {{c[key]}}</td>
</tr>

Edit

You could also return an entry containing both key and value:

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}

and use it like that:

<span *ngFor="let entry of content | keys">           
  Key: {{entry.key}}, value: {{entry.value}}
</span>

how to implement Interfaces in C++?

Interface are nothing but a pure abstract class in C++. Ideally this interface class should contain only pure virtual public methods and static const data. For example:

class InterfaceA
{
public:
  static const int X = 10;

  virtual void Foo() = 0;
  virtual int Get() const = 0;
  virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}

Making a Simple Ajax call to controller in asp.net mvc

Add "JsonValueProviderFactory" in global.asax :

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}

Get height of div with no height set in css

jQuery .height will return you the height of the element. It doesn't need CSS definition as it determines the computed height.

DEMO

You can use .height(), .innerHeight() or outerHeight() based on what you need.

enter image description here

.height() - returns the height of element excludes padding, border and margin.

.innerHeight() - returns the height of element includes padding but excludes border and margin.

.outerHeight() - returns the height of the div including border but excludes margin.

.outerHeight(true) - returns the height of the div including margin.

Check below code snippet for live demo. :)

_x000D_
_x000D_
$(function() {_x000D_
  var $heightTest = $('#heightTest');_x000D_
  $heightTest.html('Div style set as "height: 180px; padding: 10px; margin: 10px; border: 2px solid blue;"')_x000D_
    .append('<p>Height (.height() returns) : ' + $heightTest.height() + ' [Just Height]</p>')_x000D_
    .append('<p>Inner Height (.innerHeight() returns): ' + $heightTest.innerHeight() + ' [Height + Padding (without border)]</p>')_x000D_
    .append('<p>Outer Height (.outerHeight() returns): ' + $heightTest.outerHeight() + ' [Height + Padding + Border]</p>')_x000D_
    .append('<p>Outer Height (.outerHeight(true) returns): ' + $heightTest.outerHeight(true) + ' [Height + Padding + Border + Margin]</p>')_x000D_
});
_x000D_
div { font-size: 0.9em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="heightTest" style="height: 150px; padding: 10px; margin: 10px; border: 2px solid blue; overflow: hidden; ">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Twitter bootstrap hide element on small devices

On small device : 4 columns x 3 (= 12) ==> col-sm-3

On extra small : 3 columns x 4 (= 12) ==> col-xs-4

 <footer class="row">
        <nav class="col-xs-4 col-sm-3">
            <ul class="list-unstyled">
            <li>Text 1</li>
            <li>Text 2</li>
            <li>Text 3</li>
            </ul>
        </nav>
        <nav class="col-xs-4 col-sm-3">
            <ul class="list-unstyled">
            <li>Text 4</li>
            <li>Text 5</li>
            <li>Text 6</li>
            </ul>
        </nav>
        <nav class="col-xs-4 col-sm-3">
            <ul class="list-unstyled">
            <li>Text 7</li>
            <li>Text 8</li>
            <li>Text 9</li>
            </ul>
        </nav>
        <nav class="hidden-xs col-sm-3">
            <ul class="list-unstyled">
            <li>Text 10</li>
            <li>Text 11</li>
            <li>Text 12</li>
            </ul>
        </nav>
    </footer>

As you say, hidden-xs is not enough, you have to combine xs and sm class.


Here is links to the official doc about available responsive classes and about the grid system.

Have in head :

  • 1 row = 12 cols
  • For XtraSmall device : col-xs-__
  • For SMall device : col-sm-__
  • For MeDium Device: col-md-__
  • For LarGe Device : col-lg-__
  • Make visible only (hidden on other) : visible-md (just visible in medium [not in lg xs or sm])
  • Make hidden only (visible on other) : hidden-xs (just hidden in XtraSmall)

How to get index of object by its property in JavaScript?

Only way known for me is to looping through all array:

var index=-1;
for(var i=0;i<Data.length;i++)
  if(Data[i].name==="John"){index=i;break;}

or case insensitive:

var index=-1;
for(var i=0;i<Data.length;i++)
  if(Data[i].name.toLowerCase()==="john"){index=i;break;}

On result variable index contain index of object or -1 if not found.

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

Ok, I figured it out. The issue was that I didn't have the correct permissions set for myrepo.git and the parent directory git.

As root I logged into the server and used:

$ chown username /home/username/git

This then returns drwxrwxr-x 4 username root 4096 2012-10-30 15:51 /home/username/git with the following:

$ ls -ld /home/username/git

I then make a new directory for myrepo.git inside git:

$ mkdir myrepo.git
$ ls -ld myrepo.git/
drwxr-xr-x 2 root root 4096 2012-10-30 18:41 myrepo.git/

but it has the user set to root, so I change it to username the same way as before.

$ chown username myrepo.git/
$ ls -ld myrepo.git/
drwxr-xr-x 2 username root 4096 2012-10-30 18:41 myrepo.git/

I then sign out of root and sign into server as username:

Inside git directory:

$ cd myrepo.git/
$ git --bare init
Initialized empty Git repository in /home/username/git/myrepo.git/

On local machine:

$ git remote add origin      
ssh://[email protected]/home/username/git/myrepo.git
$ git push origin master

SUCCESS!

Hopefully this comes in handy for anyone else that runs into the same issue in the future!

Resources

Do Git tags only apply to the current branch?

If you create a tag by e.g.

git tag v1.0

the tag will refer to the most recent commit of the branch you are currently on. You can change branch and create a tag there.

You can also just refer to the other branch while tagging,

git tag v1.0 name_of_other_branch

which will create the tag to the most recent commit of the other branch.

Or you can just put the tag anywhere, no matter which branch, by directly referencing to the SHA1 of some commit

git tag v1.0 <sha1>

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

writing a batch file that opens a chrome URL

start "Chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 2"

start "webpage name" "http://someurl.com/"

start "Chrome" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 3"

start "webpage name" "http://someurl.com/"

TypeError: a bytes-like object is required, not 'str'

Simply replace message parameter passed in clientSocket.sendto(message,(serverName, serverPort)) to clientSocket.sendto(message.encode(),(serverName, serverPort)). Then you would successfully run in in python3

Show popup after page load

When the DOM is finished loading you can add your code in the $(document).ready() function.

Remove the onclick from here:

<input type="submit" name="submit" value="Submit" onClick="PopUp()" />

Try this:

$(document).ready(function(){
   setTimeout(function(){
      PopUp();
   },5000); // 5000 to load it after 5 seconds from page load
});

How to use z-index in svg elements?

Move to front by transform:TranslateZ

Warning: Only works in FireFox

_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 160 160" style="width:160px; height:160px;">
    <g style="transform-style: preserve-3d;">
        <g id="one" style="transform-style: preserve-3d;">
            <circle fill="green" cx="100" cy="105" r="20" style="transform:TranslateZ(1px);"></circle>
        </g>
        <g id="two" style="transform-style: preserve-3d;">
            <circle fill="orange" cx="100" cy="95" r="20"></circle>
        </g>
    </g>
</svg>
_x000D_
_x000D_
_x000D_

Change font-weight of FontAwesome icons?

Webkit browsers support the ability to add "stroke" to fonts. This bit of style makes fonts look thinner (assuming a white background):

-webkit-text-stroke: 2px white;

Example on codepen here: http://codepen.io/mackdoyle/pen/yrgEH Some people are using SVG for a cross-platform "stroke" solution: http://codepen.io/CrocoDillon/pen/dGIsK

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.

After importing PDFKit, you should initialize a PDFView with a local or a remote URL and display it in your view.

if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
    let pdfView = PDFView(frame: view.frame)
    pdfView.document = PDFDocument(url: url)
    view.addSubview(pdfView)
}

Read more about PDFKit in the Apple Developer documentation.

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

You have to disable the sandbox for Groovy in your job configuration.

Currently this is not possible for multibranch projects where the groovy script comes from the scm. For more information see https://issues.jenkins-ci.org/browse/JENKINS-28178

Angular 5 Service to read local .json file

Let’s create a JSON file, we name it navbar.json you can name it whatever you want!

navbar.json

[
  {
    "href": "#",
    "text": "Home",
    "icon": ""
  },
  {
    "href": "#",
    "text": "Bundles",
    "icon": "",
    "children": [
      {
        "href": "#national",
        "text": "National",
        "icon": "assets/images/national.svg"
      }
    ]
  }
]

Now we’ve created a JSON file with some menu data. We’ll go to app component file and paste the below code.

app.component.ts

import { Component } from '@angular/core';
import menudata from './navbar.json';

@Component({
  selector: 'lm-navbar',
  templateUrl: './navbar.component.html'
})
export class NavbarComponent {
    mainmenu:any = menudata;

}

Now your Angular 7 app is ready to serve the data from the local JSON file.

Go to app.component.html and paste the following code in it.

app.component.html

<ul class="navbar-nav ml-auto">
                  <li class="nav-item" *ngFor="let menu of mainmenu">
                  <a class="nav-link" href="{{menu.href}}">{{menu.icon}} {{menu.text}}</a>
                  <ul class="sub_menu" *ngIf="menu.children && menu.children.length > 0"> 
                            <li *ngFor="let sub_menu of menu.children"><a class="nav-link" href="{{sub_menu.href}}"><img src="{{sub_menu.icon}}" class="nav-img" /> {{sub_menu.text}}</a></li> 
                        </ul>
                  </li>
                  </ul>

How to display raw html code in PRE or something like it but without escaping it

You can use the xmp element, see What was the <XMP> tag used for?. It has been in HTML since the beginning and is supported by all browsers. Specifications frown upon it, but HTML5 CR still describes it and requires browsers to support it (though it also tells authors not to use it, but it cannot really prevent you).

Everything inside xmp is taken as such, no markup (tags or character references) is recognized there, except, for apparent reason, the end tag of the element itself, </xmp>.

Otherwise xmp is rendered like pre.

When using “real XHTML”, i.e. XHTML served with an XML media type (which is rare), the special parsing rules do not apply, so xmp is treated like pre. But in “real XHTML”, you can use a CDATA section, which implies similar parsing rules. It has no special formatting, so you would probably want to wrap it inside a pre element:

<pre><![CDATA[
This is a demo, tags like <p> will
appear literally.
]]></pre>

I don’t see how you could combine xmp and CDATA section to achieve so-called polyglot markup

How to pass text in a textbox to JavaScript function?

This is what I have done. (Adapt from all of your answers)

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

It works. Thanks to all of you. :)

how to show only even or odd rows in sql server 2008?

SELECT *
  FROM   
  ( 
     SELECT rownum rn, empno, ename
     FROM emp
  ) temp
  WHERE  MOD(temp.rn,2) = 1

Typescript sleep

You have to wait for TypeScript 2.0 with async/await for ES5 support as it now supported only for TS to ES6 compilation.

You would be able to create delay function with async:

function delay(ms: number) {
    return new Promise( resolve => setTimeout(resolve, ms) );
}

And call it

await delay(300);

Please note, that you can use await only inside async function.

If you can't (let's say you are building nodejs application), just place your code in the anonymous async function. Here is an example:

    (async () => { 
        // Do something before delay
        console.log('before delay')

        await delay(1000);

        // Do something after
        console.log('after delay')
    })();

Example TS Application: https://github.com/v-andrew/ts-template

In OLD JS you have to use

setTimeout(YourFunctionName, Milliseconds);

or

setTimeout( () => { /*Your Code*/ }, Milliseconds );

However with every major browser supporting async/await it less useful.

Update: TypeScript 2.1 is here with async/await.

Just do not forget that you need Promise implementation when you compile to ES5, where Promise is not natively available.

PS

You have to export the function if you want to use it outside of the original file.

List<Object> and List<?>

List<Object> object = new List<Object>();

You cannot do this because List is an interface and you cannot create object of any interface or in other word you cannot instantiate any interface. Moreover, you can assign any object of class which implements List to its reference variable. For example you can do this:

list<Object> object = new ArrayList<Object>();

Here ArrayList is a class which implements List, you can use any class which implements List.

How to write new line character to a file in Java

Split the string in to string array and write using above method (I assume your text contains \n to get new line)

String[] test = test.split("\n");

and the inside a loop

bufferedWriter.write(test[i]);
bufferedWriter.newline();

Jmeter - Run .jmx file through command line and get the summary report in a excel

To get the results in excel like file, you have one option to get it done with csv file. Use below commands with provided options.

jmeter -n -t /path-to-jmeter-test/file.jmx -l TestResults.csv
-n states Non GUI mode
-t states Test JMX File
-l state Log the results in provided file

Also you can pass any results related parameters dynamically in command line arguments using -Jprop.name=value which are already defined in jmeter.properties in bin folder.

How to silence output in a Bash script?

Redirect stderr to stdout

This will redirect the stderr (which is descriptor 2) to the file descriptor 1 which is the the stdout.

2>&1

Redirect stdout to File

Now when perform this you are redirecting the stdout to the file sample.s

myprogram > sample.s

Redirect stderr and stdout to File

Combining the two commands will result in redirecting both stderr and stdout to sample.s

myprogram > sample.s 2>&1

Redirect stderr and stdout to /dev/null

Redirect to /dev/null if you want to completely silent your application.

myprogram >/dev/null 2>&1

Why is &#65279; appearing in my HTML?

The character in question &#65279 is the Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF). It may be that you copied it into your code via a copy/paste without realizing it. The fact that it's not visible makes it hard to tell if you're using an editor that displays actual unicode characters.

One option is to open the file in a very basic text editor that doesn't understand unicode, or one that understands it but has the ability to display any non-ascii characters using their actual codes.

Once you locate it, you can delete the small block of text around it and retype that text manually.

How to use multiprocessing queue in Python?

Here's a dead simple usage of multiprocessing.Queue and multiprocessing.Process that allows callers to send an "event" plus arguments to a separate process that dispatches the event to a "do_" method on the process. (Python 3.4+)

import multiprocessing as mp
import collections

Msg = collections.namedtuple('Msg', ['event', 'args'])

class BaseProcess(mp.Process):
    """A process backed by an internal queue for simple one-way message passing.
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.queue = mp.Queue()

    def send(self, event, *args):
        """Puts the event and args as a `Msg` on the queue
        """
       msg = Msg(event, args)
       self.queue.put(msg)

    def dispatch(self, msg):
        event, args = msg

        handler = getattr(self, "do_%s" % event, None)
        if not handler:
            raise NotImplementedError("Process has no handler for [%s]" % event)

        handler(*args)

    def run(self):
        while True:
            msg = self.queue.get()
            self.dispatch(msg)

Usage:

class MyProcess(BaseProcess):
    def do_helloworld(self, arg1, arg2):
        print(arg1, arg2)

if __name__ == "__main__":
    process = MyProcess()
    process.start()
    process.send('helloworld', 'hello', 'world')

The send happens in the parent process, the do_* happens in the child process.

I left out any exception handling that would obviously interrupt the run loop and exit the child process. You can also customize it by overriding run to control blocking or whatever else.

This is really only useful in situations where you have a single worker process, but I think it's a relevant answer to this question to demonstrate a common scenario with a little more object-orientation.

How to execute a function when page has fully loaded?

For completeness sake, you might also want to bind it to DOMContentLoaded, which is now widely supported

document.addEventListener("DOMContentLoaded", function(event){
  // your code here
});

More info: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

Force IE10 to run in IE10 Compatibility View?

You should try the IE 5 quirks compatibility mod (is the default IE10 compatibility view)

<meta http-equiv="X-UA-Compatible" content="IE=5">

important: set in the top of your iframe structure (if you use iframe structure)

more info 1, 2

How can I simulate mobile devices and debug in Firefox Browser?

You could use the Firefox add-on User Agent Overrider. With this add-on you can use whatever user agent you want, for examlpe:

Firefox 28/Android: Mozilla/5.0 (Android; Mobile; rv:28.0) Gecko/24.0 Firefox/28.0

If your website detects mobile devices through the user agent then you can test your layout this way.


Update Nov '17:

Due to the release of Firefox 57 and the introduction of web extension this add-on sadly is no longer available. Alternatively you can edit the Firefox preference general.useragent.override in your configuration:

  1. In the address bar type about:config
  2. Search for general.useragent.override
  3. If the preference doesn't exist, right-click on the about:config page, click New, then select String
  4. Name the new preference general.useragent.override
  5. Set the value to the user agent you want

How can I use JavaScript in Java?

You can use ScriptEngine, example:


public class Main {
    public static void main(String[] args) {
        StringBuffer javascript = null;
        ScriptEngine runtime = null;

        try {
            runtime = new ScriptEngineManager().getEngineByName("javascript");
            javascript = new StringBuffer();

            javascript.append("1 + 1");

            double result = (Double) runtime.eval(javascript.toString());

            System.out.println("Result: " + result);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

"Comparison method violates its general contract!"

The violation of the contract often means that the comparator is not providing the correct or consistent value when comparing objects. For example, you might want to perform a string compare and force empty strings to sort to the end with:

if ( one.length() == 0 ) {
    return 1;                   // empty string sorts last
}
if ( two.length() == 0 ) {
    return -1;                  // empty string sorts last                  
}
return one.compareToIgnoreCase( two );

But this overlooks the case where BOTH one and two are empty - and in that case, the wrong value is returned (1 instead of 0 to show a match), and the comparator reports that as a violation. It should have been written as:

if ( one.length() == 0 ) {
    if ( two.length() == 0 ) {
        return 0;               // BOth empty - so indicate
    }
    return 1;                   // empty string sorts last
}
if ( two.length() == 0 ) {
    return -1;                  // empty string sorts last                  
}
return one.compareToIgnoreCase( two );

adding to window.onload event?

You can use attachEvent(ie8) and addEventListener instead

addEvent(window, 'load', function(){ some_methods_1() });
addEvent(window, 'load', function(){ some_methods_2() });

function addEvent(element, eventName, fn) {
    if (element.addEventListener)
        element.addEventListener(eventName, fn, false);
    else if (element.attachEvent)
        element.attachEvent('on' + eventName, fn);
}

adb shell su works but adb root does not

You need to replace the adbd binary in the boot.img/sbin/ folder to one that is su capable. You will also have to make some default.prop edits too.

Samsung seems to make this more difficult than other vendors. I have some adbd binaries you can try but it will require the knowledge of de-compiling and re-compiling the boot.img with the new binary. Also, if you have a locked bootloader... this is not gonna happen.

Also Chainfire has an app that will grant adbd root permission in the play store: https://play.google.com/store/apps/details?id=eu.chainfire.adbd&hl=en

Lastly, if you are trying to write a windows script with SU permissions you can do this buy using the following command style... However, you will at least need to grant (on the phone) SU permissions the frist time its ran...

adb shell "su -c ls" <-list working directory with su rights. adb shell "su -c echo anytext > /data/test.file"

These are just some examples. If you state specifically what you are trying to accomplish I may be able to give more specific advice

-scosler

How to preserve insertion order in HashMap?

HashMap is unordered per the second line of the documentation:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Perhaps you can do as aix suggests and use a LinkedHashMap, or another ordered collection. This link can help you find the most appropriate collection to use.

Implement an input with a mask

I wrote a similar solution some time ago.
Of course it's just a PoC and can be improved further.

This solution covers the following features:

  • Seamless character input
  • Pattern customization
  • Live validation while you typing
  • Full date validation (including correct days in each month and a leap year consideration)
  • Descriptive errors, so the user will understand what is going on while he is unable to type a character
  • Fix cursor position and prevent selections
  • Show placeholder if the value is empty

_x000D_
_x000D_
const pattern = "__/__/____";_x000D_
const patternFreeChar = "_";_x000D_
const validDate = [_x000D_
  /^[0-3]$/,_x000D_
  /^(0[1-9]|[12]\d|3[01])$/,_x000D_
  /^(0[1-9]|[12]\d|3[01])[01]$/,_x000D_
  /^((0[1-9]|[12]\d|3[01])(0[13578]|1[02])|(0[1-9]|[12]\d|30)(0[469]|11)|(0[1-9]|[12]\d)02)$/,_x000D_
  /^((0[1-9]|[12]\d|3[01])(0[13578]|1[02])|(0[1-9]|[12]\d|30)(0[469]|11)|(0[1-9]|[12]\d)02)[12]$/,_x000D_
  /^((0[1-9]|[12]\d|3[01])(0[13578]|1[02])|(0[1-9]|[12]\d|30)(0[469]|11)|(0[1-9]|[12]\d)02)(19|20)/_x000D_
]_x000D_
_x000D_
/**_x000D_
 * Validate a date as your type._x000D_
 * @param {string} date The date in format DDMMYYYY as a string representation._x000D_
 * @throws {Error} When the date is invalid._x000D_
 */_x000D_
function validateStartTypingDate(date) {_x000D_
  if ( !date ) return "";_x000D_
  _x000D_
  date = date.substr(0, 8);_x000D_
  _x000D_
  if ( !/^\d+$/.test(date) )_x000D_
   throw new Error("Please type numbers only");_x000D_
  _x000D_
 if ( !validDate[Math.min(date.length-1,validDate.length-1)].test(date) ) {_x000D_
    let errMsg = "";_x000D_
    switch ( date.length ) {_x000D_
     case 1:_x000D_
       throw new Error("Day in month can start only with 0, 1, 2 or 3");_x000D_
        _x000D_
     case 2:_x000D_
       throw new Error("Day in month must be in a range between 01 and 31");_x000D_
        _x000D_
     case 3:_x000D_
       throw new Error("Month can start only with 0 or 1");_x000D_
        _x000D_
     case 4: {_x000D_
       const day = parseInt(date.substr(0,2));_x000D_
       const month = parseInt(date.substr(2,2));_x000D_
        const monthName = new Date(0,month-1).toLocaleString('en-us',{month:'long'});_x000D_
        _x000D_
        if ( month < 1 || month > 12 )_x000D_
         throw new Error("Month number must be in a range between 01 and 12");_x000D_
          _x000D_
        if ( day > 30 && [4,6,9,11].includes(month) )_x000D_
         throw new Error(`${monthName} have maximum 30 days`);_x000D_
          _x000D_
        if ( day > 29 && month === 2 )_x000D_
         throw new Error(`${monthName} have maximum 29 days`);_x000D_
        break; _x000D_
      }_x000D_
         _x000D_
      case 5:_x000D_
      case 6:_x000D_
       throw new Error("We support only years between 1900 and 2099, so the full year can start only with 19 or 20");_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  if ( date.length === 8 ) {_x000D_
   const day = parseInt(date.substr(0,2));_x000D_
    const month = parseInt(date.substr(2,2));_x000D_
    const year = parseInt(date.substr(4,4));_x000D_
    const monthName = new Date(0,month-1).toLocaleString('en-us',{month:'long'});_x000D_
    if ( !isLeap(year) && month === 2 && day === 29 )_x000D_
      throw new Error(`The year you are trying to enter (${year}) is not a leap year. Thus, in this year, ${monthName} can have maximum 28 days`);_x000D_
  }_x000D_
  _x000D_
  return date;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Check whether the given year is a leap year._x000D_
 */_x000D_
function isLeap(year) {_x000D_
  return new Date(year, 1, 29).getDate() === 29;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Move cursor to the end of the provided input element._x000D_
 */_x000D_
function moveCursorToEnd(el) {_x000D_
 if (typeof el.selectionStart == "number") {_x000D_
  el.selectionStart = el.selectionEnd = el.value.length;_x000D_
 } else if (typeof el.createTextRange != "undefined") {_x000D_
  el.focus();_x000D_
  var range = el.createTextRange();_x000D_
  range.collapse(false);_x000D_
  range.select();_x000D_
 }_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Move cursor to the end of the self input element._x000D_
 */_x000D_
function selfMoveCursorToEnd() {_x000D_
 return moveCursorToEnd(this);_x000D_
}_x000D_
_x000D_
const input = document.querySelector("input")_x000D_
_x000D_
input.addEventListener("keydown", function(event){_x000D_
 event.preventDefault();_x000D_
  document.getElementById("date-error-msg").innerText = "";_x000D_
  _x000D_
  // On digit pressed_x000D_
  let inputMemory = this.dataset.inputMemory || "";_x000D_
  _x000D_
  if ( event.key.length === 1 ) {_x000D_
    try {_x000D_
      inputMemory = validateStartTypingDate(inputMemory + event.key);_x000D_
    } catch (err) {_x000D_
      document.getElementById("date-error-msg").innerText = err.message;_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  // On backspace pressed_x000D_
  if ( event.code === "Backspace" ) {_x000D_
   inputMemory = inputMemory.slice(0, -1);_x000D_
  }_x000D_
  _x000D_
  // Build an output using a pattern_x000D_
  if ( this.dataset.inputMemory !== inputMemory ) {_x000D_
   let output = pattern;_x000D_
   for ( let i=0, digit; i<inputMemory.length, digit=inputMemory[i]; i++ ) {_x000D_
     output = output.replace(patternFreeChar, digit);_x000D_
    }_x000D_
    this.dataset.inputMemory = inputMemory;_x000D_
    this.value = output;_x000D_
  }_x000D_
  _x000D_
  // Clean the value if the memory is empty_x000D_
  if ( inputMemory === "" ) {_x000D_
   this.value = "";_x000D_
  }_x000D_
}, false);_x000D_
_x000D_
input.addEventListener('select', selfMoveCursorToEnd, false);_x000D_
input.addEventListener('mousedown', selfMoveCursorToEnd, false);_x000D_
input.addEventListener('mouseup', selfMoveCursorToEnd, false);_x000D_
input.addEventListener('click', selfMoveCursorToEnd, false);
_x000D_
<input type="text" placeholder="DD/MM/YYYY" />_x000D_
<div id="date-error-msg"></div>
_x000D_
_x000D_
_x000D_

A link to jsfiddle: https://jsfiddle.net/d1xbpw8f/56/

Good luck!

How do I mount a remote Linux folder in Windows through SSH?

Take a look at CIFS (http://www.samba.org/cifs/). It is a virtual file system you can run on your linux machine that will allow you to mount folders on your linux machine in windows using SMB.

CIFS on linux information can be found here: http://linux-cifs.samba.org/

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

I worked on Access Denied for User 'root'@'localhost' (using password: YES) for several hours, I have found following solution,

The answer to this problem was that in the my.cnf located within
/etc/mysql/my.cnf

the line was either 
bind-address = 127.0.0.1 
            (or)
bind-address = localhost
            (or)
bind-address = 0.0.0.0

I should prefer that 127.0.0.1

I should also prefer 0.0.0.0, it is more flexible 
because which will allow all connections

C# ASP.NET Send Email via TLS

I was almost using the same technology as you did, however I was using my app to connect an Exchange Server via Office 365 platform on WinForms. I too had the same issue as you did, but was able to accomplish by using code which has slight modification of what others have given above.

SmtpClient client = new SmtpClient(exchangeServer, 587);
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send(msg);

I had to use the Port 587, which is of course the default port over TSL and the did the authentication.

Relay access denied on sending mail, Other domain outside of network

I'm using THUNDERBIRD as MUA and I have same issues. I solved adding the IP address of my home PC on mynetworks parameter on main.cf

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 MyIpAddress

P.S. I don't have a static ip for my home PC so when my ISP change it I ave to adjust every time.

SQLAlchemy create_all() does not create tables

You should put your model class before create_all() call, like this:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

If your models are declared in a separate module, import them before calling create_all().

Say, the User model is in a file called models.py,

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)

# See important note below
from models import User

db.create_all()
db.session.commit()

admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users

Important note: It is important that you import your models after initializing the db object since, in your models.py _you also need to import the db object from this module.

How to get the index of an element in an IEnumerable?

I would implement it like this:

public static class EnumerableExtensions
{
    public static int IndexOf<T>(this IEnumerable<T> obj, T value)
    {
        return obj.IndexOf(value, null);
    }

    public static int IndexOf<T>(this IEnumerable<T> obj, T value, IEqualityComparer<T> comparer)
    {
        comparer = comparer ?? EqualityComparer<T>.Default;
        var found = obj
            .Select((a, i) => new { a, i })
            .FirstOrDefault(x => comparer.Equals(x.a, value));
        return found == null ? -1 : found.i;
    }
}

AngularJS toggle class using ng-class

How to use conditional in ng-class:

Solution 1:

<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>

Solution 2:

<i ng-class="{true: 'icon-autoscroll', false: 'icon-autoscroll-disabled'}[autoScroll]"></i>

Solution 3 (angular v.1.1.4+ introduced support for ternary operator):

<i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>

Plunker

What difference is there between WebClient and HTTPWebRequest classes in .NET?

I know its too longtime to reply but just as an information purpose for future readers:

WebRequest

System.Object
    System.MarshalByRefObject
        System.Net.WebRequest

The WebRequest is an abstract base class. So you actually don't use it directly. You use it through it derived classes - HttpWebRequest and FileWebRequest.

You use Create method of WebRequest to create an instance of WebRequest. GetResponseStream returns data stream.

There are also FileWebRequest and FtpWebRequest classes that inherit from WebRequest. Normally, you would use WebRequest to, well, make a request and convert the return to either HttpWebRequest, FileWebRequest or FtpWebRequest, depend on your request. Below is an example:

Example:

var _request = (HttpWebRequest)WebRequest.Create("http://stackverflow.com");
var _response = (HttpWebResponse)_request.GetResponse();

WebClient

System.Object
        System.MarshalByRefObject
            System.ComponentModel.Component
                System.Net.WebClient

WebClient provides common operations to sending and receiving data from a resource identified by a URI. Simply, it’s a higher-level abstraction of HttpWebRequest. This ‘common operations’ is what differentiate WebClient from HttpWebRequest, as also shown in the sample below:

Example:

var _client = new WebClient();
var _stackContent = _client.DownloadString("http://stackverflow.com");

There are also DownloadData and DownloadFile operations under WebClient instance. These common operations also simplify code of what we would normally do with HttpWebRequest. Using HttpWebRequest, we have to get the response of our request, instantiate StreamReader to read the response and finally, convert the result to whatever type we expect. With WebClient, we just simply call DownloadData, DownloadFile or DownloadString.

However, keep in mind that WebClient.DownloadString doesn’t consider the encoding of the resource you requesting. So, you would probably end up receiving weird characters if you don’t specify and encoding.

NOTE: Basically "WebClient takes few lines of code as compared to Webrequest"

Using textures in THREE.js

Without Error Handeling

//Load background texture
 new THREE.TextureLoader();
loader.load('https://images.pexels.com/photos/1205301/pexels-photo-1205301.jpeg' , function(texture)
            {
             scene.background = texture;  
            });

With Error Handling

// Function called when download progresses
var onProgress = function (xhr) {
  console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};

// Function called when download errors
var onError = function (error) {
  console.log('An error happened'+error);
};

//Function  called when load completes.
var onLoad = function (texture) {
  var objGeometry = new THREE.BoxGeometry(30, 30, 30);
  var objMaterial = new THREE.MeshPhongMaterial({
    map: texture,
    shading: THREE.FlatShading
  });

  var boxMesh = new THREE.Mesh(objGeometry, objMaterial);
  scene.add(boxMesh);

  var render = function () {
    requestAnimationFrame(render);
    boxMesh.rotation.x += 0.010;
    boxMesh.rotation.y += 0.010;
      sphereMesh.rotation.y += 0.1;
    renderer.render(scene, camera);
  };

  render();
}


//LOAD TEXTURE and on completion apply it on box
var loader = new THREE.TextureLoader();
    loader.load('https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/The_Earth_seen_from_Apollo_17.jpg/1920px-The_Earth_seen_from_Apollo_17.jpg', 
                onLoad, 
                onProgress, 
                onError);

Result:

enter image description here

https://codepen.io/hiteshsahu/pen/jpGLpq/

How to center form in bootstrap 3

Many people advise using col- and col-offset- classes, but it doesn't work right for me, it centers the form only for a certain screen size, but if you change it, the markup slides out.

I found two ways to align form:

Use a custom CSS:

<div class=".center">
  <form>

  </form>
</div>

.center {
  margin: 0 auto;
  width: 100%;
}
form {
  margin: 0 auto;
  width: 500px; /*find your value*/
  text-align: center;
}

Original code

OR just copy a CSS class "justify-content-center" from bootstrap 4, it's very short:

.justify-content-center {
    -ms-flex-pack: center !important;
    justify-content: center !important;
}

And then use it:

<div class="container">
    <div class="row">
        <div class="form-inline justify-content-center">
        </div>
    </div>
</div>

Replace a string in a file with nodejs

<p>Please click in the following {{link}} to verify the account</p>


function renderHTML(templatePath: string, object) {
    const template = fileSystem.readFileSync(path.join(Application.staticDirectory, templatePath + '.html'), 'utf8');
    return template.match(/\{{(.*?)\}}/ig).reduce((acc, binding) => {
        const property = binding.substring(2, binding.length - 2);
        return `${acc}${template.replace(/\{{(.*?)\}}/, object[property])}`;
    }, '');
}
renderHTML(templateName, { link: 'SomeLink' })

for sure you can improve the reading template function to read as stream and compose the bytes by line to make it more efficient

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

No code change required:

While you are in debug mode within the catch {...} block open up the "QuickWatch" window (Ctrl+Alt+Q) and paste in there:

((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors

or:

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

If you are not in a try/catch or don't have access to the exception object.

This will allow you to drill down into the ValidationErrors tree. It's the easiest way I've found to get instant insight into these errors.

Is it valid to define functions in JSON results?

Nope, definitely not.

If you use a decent JSON serializer, it won't let you serialize a function like that. It's a valid OBJECT, but not valid JSON. Whatever that website's intent, it's not sending valid JSON.

How can I get the current stack trace in Java?

Thread.currentThread().getStackTrace();

is fine if you don't care what the first element of the stack is.

new Throwable().getStackTrace();

will have a defined position for your current method, if that matters.

Bootstrap 3 modal responsive

Old post. I ended up setting media queries and using max-width: YYpx; and width:auto; for each breakpoint. This will scale w/ images as well (per say you have an image that's 740px width on the md screen), the modal will scale down to 740px (excluding padding for the .modal-body, if applied)

<div class="modal fade" id="bs-button-info-modal" tabindex="-1" role="dialog" aria-labelledby="Button Information Modal">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <div class="modal-body"></div>
        </div>
    </div>
</div>

Note that I'm using SCSS, bootstrap 3.3.7, and did not make any additional edits to the _modals.scss file that _bootstrap.scss imports. The CSS below is added to an additional SCSS file and imported AFTER _bootstrap.scss.

It is also important to note that the original bootstrap styles for .modal-dialog is not set for the default 992px breakpoint, only as high as the 768px breakpoint (which has a hard set width applied width: 600px;, hence why I overrode it w/ width: auto;.

@media (min-width: $screen-sm-min) { // this is the 768px breakpoint
    .modal-dialog {
        max-width: 600px;
        width: auto;
    }
}

@media (min-width: $screen-md-min) { // this is the 992px breakpoint
    .modal-dialog { 
        max-width: 800px;
    }
}

Example below of modal being responsive with an image.

enter image description here

C# Copy a file to another location with a different name

One method is:

File.Copy(oldFilePathWithFileName, newFilePathWithFileName);

Or you can use the FileInfo.CopyTo() method too something like this:

FileInfo file = new FileInfo(oldFilePathWithFileName);
file.CopyTo(newFilePathWithFileName);

Example:

File.Copy(@"c:\a.txt", @"c:\b.txt");

or

FileInfo file = new FileInfo(@"c:\a.txt");
file.CopyTo(@"c:\b.txt");

How to set label size in Bootstrap

In Bootstrap 3 they do not have separate classes for different styles of labels.

http://getbootstrap.com/components/

However, you can customize bootstrap classes that way. In your css file

.lb-sm {
  font-size: 12px;
}

.lb-md {
  font-size: 16px;
}

.lb-lg {
  font-size: 20px;
}

Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label

_x000D_
_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
_x000D_
_x000D_

They might add size classes for labels in future Bootstrap versions.

Git copy changes from one branch to another

If you are using tortoise git.

please follow the below steps.

  1. Checkout BranchB
  2. Open project folder, go to TortoiseGit --> Pull
  3. In pull screen, Change the remote branch "BranchA" and click ok.
  4. Then right click again, go to TortoiseGit --> Push.

Now your changes moved from BranchA to BranchB

Python conversion from binary string to hexadecimal

For whatever reason I have had issues with some of these answers, I've went and written a couple helper functions for myself, so if you have problems like I did, give these a try.

def bin_string_to_bin_value(input):
   highest_order = len(input) - 1
   result = 0
   for bit in input:
      result = result + int(bit) * pow(2,highest_order)
      highest_order = highest_order - 1
   return bin(result)

def hex_string_to_bin_string(input):
   lookup = {"0" : "0000", "1" : "0001", "2" : "0010", "3" : "0011", "4" : "0100", "5" : "0101", "6" : "0110", "7" : "0111", "8" : "1000", "9" : "1001", "A" : "1010", "B" : "1011", "C" : "1100", "D" : "1101", "E" : "1110", "F" : "1111"}
   result = ""
   for byte in input:
      result =  result + lookup[byte]
   return result
def hex_string_to_hex_value(input):
   bin_string = hex_string_to_bin_string(input)
   bin_value = bin_string_to_bin_value(bin_string)
   return hex(int(bin_value, 2))

They seem to work well.

print hex_string_to_hex_value("FF")
print hex_string_to_hex_value("01234567")
print bin_string_to_bin_value("11010001101011")

results in:

0xff
0x1234567
0b11010001101011

Allow anything through CORS Policy

Just encountered with this issue in my rails application in production. A lot of answers here gave me hints and helped me to finally come to an answer that worked fine for me.

I am running Nginx and it was simple enough to just modify the my_app.conf file (where my_app is your app name). You can find this file in /etc/nginx/conf.d

If you do not have location / {} already you can just add it under server {}, then add add_header 'Access-Control-Allow-Origin' '*'; under location / {}.

The final format should look something like this:

server {
    server_name ...;
    listen ...;
    root ...;

    location / {
        add_header 'Access-Control-Allow-Origin' '*';
    }
}

git diff between two different files

I believe using --no-index is what you're looking for:

git diff [<options>] --no-index [--] <path> <path>

as mentioned in the git manual:

This form is to compare the given two paths on the filesystem. You can omit the --no-index option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.

How to set tbody height with overflow scroll

If you want tbody to show a scrollbar, set its display: block;.

Set display: table; for the tr so that it keeps the behavior of a table.

To evenly spread the cells, use table-layout: fixed;.

DEMO tbody scroll


CSS:

table, tr td {
    border: 1px solid red
}
tbody {
    display: block;
    height: 50px;
    overflow: auto;
}
thead, tbody tr {
    display: table;
    width: 100%;
    table-layout: fixed;/* even columns width , fix width of table too*/
}
thead {
    width: calc( 100% - 1em )/* scrollbar is average 1em/16px width, remove it from thead width */
}
table {
    width: 400px;
}

If tbody doesn't show a scroll, because content is less than height or max-height, set the scroll any time with: overflow-y: scroll;. DEMO 2

Important note: this approach to making a table scrollable has drawbacks in some cases. (See comments below.)

How to convert data.frame column from Factor to numeric

breast$class <- as.numeric(as.character(breast$class))

If you have many columns to convert to numeric

indx <- sapply(breast, is.factor)
breast[indx] <- lapply(breast[indx], function(x) as.numeric(as.character(x)))

Another option is to use stringsAsFactors=FALSE while reading the file using read.table or read.csv

Just in case, other options to create/change columns

 breast[,'class'] <- as.numeric(as.character(breast[,'class']))

or

 breast <- transform(breast, class=as.numeric(as.character(breast)))

Read data from SqlDataReader

You have to read database columnhere. You could have a look on following code snippet

                string connectionString = ConfigurationManager.ConnectionStrings["NameOfYourSqlConnectionString"].ConnectionString;
                using (var _connection = new SqlConnection(connectionString))
                {
                    _connection.Open();

                    using (SqlCommand command = new SqlCommand("SELECT SomeColumnName FROM TableName", _connection))
                    {

                        SqlDataReader sqlDataReader = command.ExecuteReader();
                        if (sqlDataReader.HasRows)
                        {
                            while (sqlDataReader.Read())
                            {
                                string YourFirstDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString(); // Remember Type Casting is required here it has to be according to database column data type
                                string YourSecondDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();
                                string YourThridDataBaseTableColumn = sqlDataReader["SomeColumn"].ToString();

                            }
                        }
                        sqlDataReader.Close();
                    }
                    _connection.Close();

uncaught syntaxerror unexpected token U JSON

This is not a difficult task. That problem also occur at my site you should have to shift your js files top ordered. Because at the place where you are using JSON Parsing, this time your JS files are not loaded. EXAMPLE #

<script type="text/javaScript">
...........SOME CODE.............
</script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>

change to

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script type="text/javaScript">
...........SOME CODE.............
</script>

Multithreading in Bash

Bash job control involves multiple processes, not multiple threads.

You can execute a command in background with the & suffix.

You can wait for completion of a background command with the wait command.

You can execute multiple commands in parallel by separating them with |. This provides also a synchronization mechanism, since stdout of a command at left of | is connected to stdin of command at right.

How do I draw a shadow under a UIView?

To those who failed in getting this to work (As myself!) after trying all the answers here, just make sure Clip Subviews is not enabled at the Attributes inspector...

how to take user input in Array using java?

You can do the following:

    import java.util.Scanner;

    public class Test {

            public static void main(String[] args) {

            int arr[];
            Scanner scan = new Scanner(System.in);
            // If you want to take 5 numbers for user and store it in an int array
            for(int i=0; i<5; i++) {
                System.out.print("Enter number " + (i+1) + ": ");
                arr[i] = scan.nextInt();    // Taking user input
            }

            // For printing those numbers
            for(int i=0; i<5; i++) 
                System.out.println("Number " + (i+1) + ": " + arr[i]);
        }
    }

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

The first: Please make sure your port '12345' is opening and then when you using a different network. You have to use the IP address in LAN. Don't use the 'localhost' or '127.0.0.1'. The solution here is: In server

host = '192.168.1.12' #Ip address in LAN network

In client

host = '27.32.123.32' # external IP Address

Hope it works for you

What is 'Currying'?

As all other answers currying helps to create partially applied functions. Javascript does not provide native support for automatic currying. So the examples provided above may not help in practical coding. There is some excellent example in livescript (Which essentially compiles to js) http://livescript.net/

times = (x, y) --> x * y
times 2, 3       #=> 6 (normal use works as expected)
double = times 2
double 5         #=> 10

In above example when you have given less no of arguments livescript generates new curried function for you (double)

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

Single-threaded apartment - cannot instantiate ActiveX control

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)

example:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WebBrowser());
    }
}

Oracle 'Partition By' and 'Row_Number' keyword

I often use row_number() as a quick way to discard duplicate records from my select statements. Just add a where clause. Something like...

select a,b,rn 
  from (select a, b, row_number() over (partition by a,b order by a,b) as rn           
          from table) 
 where rn=1;

How to copy java.util.list Collection

You may create a new list with an input of a previous list like so:

List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);

This will allow you to modify the order or what elemtents are contained independent of the first list.

Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

example:

MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"

Edit

To avoid this you need a deep copy of each element in the list like so:

List<Torero> one = new ArrayList<Torero>();
//add elements

List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
    Torero copy = deepCopy(t);
    two.add(copy);
}

with copy like the following:

public Torero deepCopy(Torero input){
    Torero copy = new Torero();
    copy.setValue(input.getValue());//.. copy primitives, deep copy objects again

    return copy;
}

Visual Studio Community 2015 expiration date

I also get same issue after I repair vs2015, even I click check license online, still fail. Correct action is: 1. Sign out 2. Check License Status, then it will pop-up login window, after login then it able to successfully get the license info.

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties: ro.product.name, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Here is a sample for ISO-8859-9;

protected void btnKaydet_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.ContentType = "application/vnd.openxmlformatsofficedocument.wordprocessingml.documet";
    Response.AddHeader("Content-Disposition", "attachment; filename=XXXX.doc");
    Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-9");
    Response.Charset = "ISO-8859-9";
    EnableViewState = false;


    StringWriter writer = new StringWriter();
    HtmlTextWriter html = new HtmlTextWriter(writer);
    form1.RenderControl(html);


    byte[] bytesInStream = Encoding.GetEncoding("iso-8859-9").GetBytes(writer.ToString());
    MemoryStream memoryStream = new MemoryStream(bytesInStream);


    string msgBody = "";
    string Email = "[email protected]";
    SmtpClient client = new SmtpClient("mail.xxxxx.org");
    MailMessage message = new MailMessage(Email, "[email protected]", "ONLINE APP FORM WITH WORD DOC", msgBody);
    Attachment att = new Attachment(memoryStream, "XXXX.doc", "application/vnd.openxmlformatsofficedocument.wordprocessingml.documet");
    message.Attachments.Add(att);
    message.BodyEncoding = System.Text.Encoding.UTF8;
    message.IsBodyHtml = true;
    client.Send(message);}

How to change the ROOT application?

Not a very good solution but one way is to redirect from the ROOT app to YourWebApp. For this you need to modify the ROOT index.html.

<html>
    <head>
        <title>Redirecting to /YourWebApp</title>
    </head>
    <body onLoad="javascript:window.location='YourWebApp';">
    </body>
</html>

OR

<html>
    <head>
        <title>Redirecting to /YourWebApp</title>
        <meta http-equiv="refresh" content="0;url=YourWebApp" />
    </head>
    <body>
    </body>
</html>

Reference : http://staraphd.blogspot.com/2009/10/change-default-root-folder-in-tomcat.html

python: urllib2 how to send cookie with urlopen request

Maybe using cookielib.CookieJar can help you. For instance when posting to a page containing a form:

import urllib2
import urllib
from cookielib import CookieJar

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# input-type values from the html form
formdata = { "username" : username, "password": password, "form-id" : "1234" }
data_encoded = urllib.urlencode(formdata)
response = opener.open("https://page.com/login.php", data_encoded)
content = response.read()

EDIT:

After Piotr's comment I'll elaborate a bit. From the docs:

The CookieJar class stores HTTP cookies. It extracts cookies from HTTP requests, and returns them in HTTP responses. CookieJar instances automatically expire contained cookies when necessary. Subclasses are also responsible for storing and retrieving cookies from a file or database.

So whatever requests you make with your CookieJar instance, all cookies will be handled automagically. Kinda like your browser does :)

I can only speak from my own experience and my 99% use-case for cookies is to receive a cookie and then need to send it with all subsequent requests in that session. The code above handles just that, and it does so transparently.

How to terminate a process in vbscript

Dim shll : Set shll = CreateObject("WScript.Shell")
Set Rt = shll.Exec("Notepad") : wscript.sleep 4000 : Rt.Terminate

Run the process with .Exec.

Then wait for 4 seconds.

After that kill this process.

Why is "using namespace std;" considered bad practice?

I agree with others – it is asking for name clashes, ambiguities and then the fact is it is less explicit. While I can see the use of using, my personal preference is to limit it. I would also strongly consider what some others pointed out:

If you want to find a function name that might be a fairly common name, but you only want to find it in the std namespace (or the reverse – you want to change all calls that are not in namespace std, namespace X, ...), then how do you propose to do this?

You could write a program to do it, but wouldn't it be better to spend time working on your project itself rather than writing a program to maintain your project?

Personally, I actually don't mind the std:: prefix. I like the look more than not having it. I don't know if that is because it is explicit and says to me "this isn't my code... I am using the standard library" or if it is something else, but I think it looks nicer. This might be odd given that I only recently got into C++ (used and still do C and other languages for much longer and C is my favourite language of all time, right above assembly).

There is one other thing although it is somewhat related to the above and what others point out. While this might be bad practise, I sometimes reserve std::name for the standard library version and name for program-specific implementation. Yes, indeed this could bite you and bite you hard, but it all comes down to that I started this project from scratch, and I'm the only programmer for it. Example: I overload std::string and call it string. I have helpful additions. I did it in part because of my C and Unix (+ Linux) tendency towards lower-case names.

Besides that, you can have namespace aliases. Here is an example of where it is useful that might not have been referred to. I use the C++11 standard and specifically with libstdc++. Well, it doesn't have complete std::regex support. Sure, it compiles, but it throws an exception along the lines of it being an error on the programmer's end. But it is lack of implementation.

So here's how I solved it. Install Boost's regex, and link it in. Then, I do the following so that when libstdc++ has it implemented entirely, I need only remove this block and the code remains the same:

namespace std
{
    using boost::regex;
    using boost::regex_error;
    using boost::regex_replace;
    using boost::regex_search;
    using boost::regex_match;
    using boost::smatch;
    namespace regex_constants = boost::regex_constants;
}

I won't argue on whether that is a bad idea or not. I will however argue that it keeps it clean for my project and at the same time makes it specific: True, I have to use Boost, but I'm using it like the libstdc++ will eventually have it. Yes, starting your own project and starting with a standard (...) at the very beginning goes a very long way with helping maintenance, development and everything involved with the project!

Just to clarify something: I don't actually think it is a good idea to use a name of a class/whatever in the STL deliberately and more specifically in place of. The string is the exception (ignore the first, above, or second here, pun if you must) for me as I didn't like the idea of 'String'.

As it is, I am still very biased towards C and biased against C++. Sparing details, much of what I work on fits C more (but it was a good exercise and a good way to make myself a. learn another language and b. try not be less biased against object/classes/etc which is maybe better stated as less closed-minded, less arrogant, and more accepting.). But what is useful is what some already suggested: I do indeed use list (it is fairly generic, is it not ?), and sort (same thing) to name two that would cause a name clash if I were to do using namespace std;, and so to that end I prefer being specific, in control and knowing that if I intend it to be the standard use then I will have to specify it. Put simply: no assuming allowed.

And as for making Boost's regex part of std. I do that for future integration and – again, I admit fully this is bias - I don't think it is as ugly as boost::regex:: .... Indeed, that is another thing for me. There are many things in C++ that I still have yet to come to fully accept in looks and methods (another example: variadic templates versus var arguments [though I admit variadic templates are very very useful!]). Even those that I do accept it was difficult, and I still have issues with them.

Parsing arguments to a Java command line program

You could use the refcodes-console artifact at refcodes-console on REFCODES.ORG:

Option<String> r     = new StringOptionImpl( "-r", null, "opt1", "..." );
Option<String> s     = new StringOptionImpl( "-S", null, "opt2", "..." );
Operand<String> arg1 = new StringOperandImpl( "arg1", "..." );
Operand<String> arg2 = new StringOperandImpl( "arg2", "..." );
Operand<String> arg3 = new StringOperandImpl( "arg3", "..." );
Operand<String> arg4 = new StringOperandImpl( "arg4", "..." );
Switch test          = new SwitchImpl( null, "--test", "..." );
Option<String> a     = new StringOptionImpl( "-A", null, "opt3", "..." );
Condition theRoot    = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4,
    test );

Create your arguments parser ArgsParserImpl with your root condition:

ArgsParser theArgsParser = new ArgsParserImpl( theRoot );
theArgsParser.setName( "MyProgramm" );
theArgsParser.setSyntaxNotation( SyntaxNotation.GNU_POSIX );

Above you define your syntax, below you invoke the parser:

theArgsParser.printUsage();
theArgsParser.printSeparatorLn();
theArgsParser.printOptions();
theArgsParser.evalArgs( new String[] {
    "-r", "RRRRR", "-S", "SSSSS", "11111", "22222", "33333", "44444", 
    "--test", "-A", "AAAAA"
} );

In case you provided some good descriptions, theArgsParser.printUsage() will even show you the pretty printed usage:

Usage: MyProgramm -r <opt1> -S <opt2> -A <opt3> arg1 arg2 arg3 arg4 --test

In the above example all defined arguments must be passed by the user, else the parser will detect a wrong usage. In case the --test switch is to be optional (or any other argument), assign theRoot as follows:

theRoot = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4, new OptionalImpl( test ) );

Then your syntax looks as follows:

Usage: MyProgramm -r <opt1> -S <opt2> -A <opt3> arg1 arg2 arg3 arg4 [--test]

The full example for your case you find in the StackOverFlowExamle. You can use AND, OR, XOR conditions and any kind of nesting ... hope this helps.

Evaluate the parsed arguments as follows: r.getValue() ); or if (test.getValue() == true) ...:

LOGGER.info( "r    :=" + r.getValue() );
LOGGER.info( "S    :=" + s.getValue() );
LOGGER.info( "arg1 :=" + arg1.getValue() );
LOGGER.info( "arg2 :=" + arg2.getValue() );
LOGGER.info( "arg3 :=" + arg3.getValue() );
LOGGER.info( "arg4 :=" + arg4.getValue() );
LOGGER.info( "test :=" + test.getValue() + "" );
LOGGER.info( "A    :=" + a.getValue() );

JAVA_HOME and PATH are set but java -version still shows the old one

When it searches for java it looks from left to right in path entries which are separated by : so you need to add the path of latest jdk/bin directory before /usr/bin, so when it searches it'll find the latest one and stop searching further.

i.e. PATH=/usr/java/jdk_1.8/bin:/usr/bin:..... and so on.

then initialize user profile using command: source ~/.bash_profile

and check with: [which java]

you'll get the right one.

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

Check the Node version you're using, might be a mismatch between what it is expected.

What is the basic difference between the Factory and Abstract Factory Design Patterns?

Abstract factory is an interface for creating related objects but factory method is a method. Abstract factory is implemented by factory method.

enter image description here

Java : Convert formatted xml file to one line string

FileUtils.readFileToString(fileName);

link

What's the simplest way of detecting keyboard input in a script from the terminal?

Edit:

I've thought about this problem a lot, and there are a few different behaviors one could want. I've been implementing most of them for Unix and Windows, and will post them here once they are done.

Synchronous/Blocking key capture:

  1. A simple input or raw_input, a blocking function which returns text typed by a user once they press a newline.
  2. A simple blocking function that waits for the user to press a single key, then returns that key

Asynchronous key capture:

  1. A callback that is called with the pressed key whenever the user types a key into the command prompt, even when typing things into an interpreter (a keylogger)
  2. A callback that is called with the typed text after the user presses enter (a less realtime keylogger)
  3. A callback that is called with the keys pressed when a program is running (say, in a for loop or while loop)

Polling:

  1. The user simply wants to be able to do something when a key is pressed, without having to wait for that key (so this should be non-blocking). Thus they call a poll() function and that either returns a key, or returns None. This can either be lossy (if they take too long to between poll they can miss a key) or non-lossy (the poller will store the history of all keys pressed, so when the poll() function requests them they will always be returned in the order pressed).

  2. The same as 1, except that poll only returns something once the user presses a newline.

Robots:

These are something that can be called to programmatically fire keyboard events. This can be used alongside key captures to echo them back out to the user

Implementations

Synchronous/Blocking key capture:

A simple input or raw_input, a blocking function which returns text typed by a user once they press a newline.

typedString = raw_input()

A simple blocking function that waits for the user to press a single key, then returns that key

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen. From http://code.activestate.com/recipes/134892/"""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            try:
                self.impl = _GetchMacCarbon()
            except(AttributeError, ImportError):
                self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

class _GetchMacCarbon:
    """
    A function which returns the current ASCII key that is down;
    if no ASCII key is down, the null string is returned.  The
    page http://www.mactech.com/macintosh-c/chap02-1.html was
    very helpful in figuring out how to do this.
    """
    def __init__(self):
        import Carbon
        Carbon.Evt #see if it has this (in Unix, it doesn't)

    def __call__(self):
        import Carbon
        if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
            return ''
        else:
            #
            # The event contains the following info:
            # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
            #
            # The message (msg) contains the ASCII char which is
            # extracted with the 0x000000FF charCodeMask; this
            # number is converted to an ASCII character with chr() and
            # returned
            #
            (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
            return chr(msg & 0x000000FF)


def getKey():
    inkey = _Getch()
    import sys
    for i in xrange(sys.maxint):
        k=inkey()
        if k<>'':break

    return k

Asynchronous key capture:

A callback that is called with the pressed key whenever the user types a key into the command prompt, even when typing things into an interpreter (a keylogger)

A callback that is called with the typed text after the user presses enter (a less realtime keylogger)

Windows:

This uses the windows Robot given below, naming the script keyPress.py

# Some if this is from http://nullege.com/codes/show/src@e@i@einstein-HEAD@Python25Einstein@[email protected]/380/win32api.GetStdHandle
# and
# http://nullege.com/codes/show/src@v@i@VistA-HEAD@Python@[email protected]/901/win32console.GetStdHandle.PeekConsoleInput

from ctypes import *
import time
import threading

from win32api import STD_INPUT_HANDLE, STD_OUTPUT_HANDLE

from win32console import GetStdHandle, KEY_EVENT, ENABLE_WINDOW_INPUT, ENABLE_MOUSE_INPUT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT

import keyPress


class CaptureLines():
    def __init__(self):
        self.stopLock = threading.Lock()

        self.isCapturingInputLines = False

        self.inputLinesHookCallback = CFUNCTYPE(c_int)(self.inputLinesHook)
        self.pyosInputHookPointer = c_void_p.in_dll(pythonapi, "PyOS_InputHook")
        self.originalPyOsInputHookPointerValue = self.pyosInputHookPointer.value

        self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)

    def inputLinesHook(self):

        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)
        inputChars = self.readHandle.ReadConsole(10000000)
        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_PROCESSED_INPUT)

        if inputChars == "\r\n":
            keyPress.KeyPress("\n")
            return 0

        inputChars = inputChars[:-2]

        inputChars += "\n"

        for c in inputChars:
            keyPress.KeyPress(c)

        self.inputCallback(inputChars)

        return 0


    def startCapture(self, inputCallback):
        self.stopLock.acquire()

        try:
            if self.isCapturingInputLines:
                raise Exception("Already capturing keystrokes")

            self.isCapturingInputLines = True
            self.inputCallback = inputCallback

            self.pyosInputHookPointer.value = cast(self.inputLinesHookCallback, c_void_p).value
        except Exception as e:
            self.stopLock.release()
            raise

        self.stopLock.release()

    def stopCapture(self):
        self.stopLock.acquire()

        try:
            if not self.isCapturingInputLines:
                raise Exception("Keystrokes already aren't being captured")

            self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)

            self.isCapturingInputLines = False
            self.pyosInputHookPointer.value = self.originalPyOsInputHookPointerValue

        except Exception as e:
            self.stopLock.release()
            raise

        self.stopLock.release()

A callback that is called with the keys pressed when a program is running (say, in a for loop or while loop)

Windows:

import threading
from win32api import STD_INPUT_HANDLE
from win32console import GetStdHandle, KEY_EVENT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT


class KeyAsyncReader():
    def __init__(self):
        self.stopLock = threading.Lock()
        self.stopped = True
        self.capturedChars = ""

        self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
        self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)



    def startReading(self, readCallback):
        self.stopLock.acquire()

        try:
            if not self.stopped:
                raise Exception("Capture is already going")

            self.stopped = False
            self.readCallback = readCallback

            backgroundCaptureThread = threading.Thread(target=self.backgroundThreadReading)
            backgroundCaptureThread.daemon = True
            backgroundCaptureThread.start()
        except:
            self.stopLock.release()
            raise

        self.stopLock.release()


    def backgroundThreadReading(self):
        curEventLength = 0
        curKeysLength = 0
        while True:
            eventsPeek = self.readHandle.PeekConsoleInput(10000)

            self.stopLock.acquire()
            if self.stopped:
                self.stopLock.release()
                return
            self.stopLock.release()


            if len(eventsPeek) == 0:
                continue

            if not len(eventsPeek) == curEventLength:
                if self.getCharsFromEvents(eventsPeek[curEventLength:]):
                    self.stopLock.acquire()
                    self.stopped = True
                    self.stopLock.release()
                    break

                curEventLength = len(eventsPeek)



    def getCharsFromEvents(self, eventsPeek):
        callbackReturnedTrue = False
        for curEvent in eventsPeek:
            if curEvent.EventType == KEY_EVENT:
                    if ord(curEvent.Char) == 0 or not curEvent.KeyDown:
                        pass
                    else:
                        curChar = str(curEvent.Char)
                        if self.readCallback(curChar) == True:
                            callbackReturnedTrue = True


        return callbackReturnedTrue

    def stopReading(self):
        self.stopLock.acquire()
        self.stopped = True
        self.stopLock.release()

Polling:

The user simply wants to be able to do something when a key is pressed, without having to wait for that key (so this should be non-blocking). Thus they call a poll() function and that either returns a key, or returns None. This can either be lossy (if they take too long to between poll they can miss a key) or non-lossy (the poller will store the history of all keys pressed, so when the poll() function requests them they will always be returned in the order pressed).

Windows and OS X (and maybe Linux):

global isWindows

isWindows = False
try:
    from win32api import STD_INPUT_HANDLE
    from win32console import GetStdHandle, KEY_EVENT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT
    isWindows = True
except ImportError as e:
    import sys
    import select
    import termios


class KeyPoller():
    def __enter__(self):
        global isWindows
        if isWindows:
            self.readHandle = GetStdHandle(STD_INPUT_HANDLE)
            self.readHandle.SetConsoleMode(ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_INPUT)

            self.curEventLength = 0
            self.curKeysLength = 0

            self.capturedChars = []
        else:
            # Save the terminal settings
            self.fd = sys.stdin.fileno()
            self.new_term = termios.tcgetattr(self.fd)
            self.old_term = termios.tcgetattr(self.fd)

            # New terminal setting unbuffered
            self.new_term[3] = (self.new_term[3] & ~termios.ICANON & ~termios.ECHO)
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.new_term)

        return self

    def __exit__(self, type, value, traceback):
        if isWindows:
            pass
        else:
            termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)

    def poll(self):
        if isWindows:
            if not len(self.capturedChars) == 0:
                return self.capturedChars.pop(0)

            eventsPeek = self.readHandle.PeekConsoleInput(10000)

            if len(eventsPeek) == 0:
                return None

            if not len(eventsPeek) == self.curEventLength:
                for curEvent in eventsPeek[self.curEventLength:]:
                    if curEvent.EventType == KEY_EVENT:
                        if ord(curEvent.Char) == 0 or not curEvent.KeyDown:
                            pass
                        else:
                            curChar = str(curEvent.Char)
                            self.capturedChars.append(curChar)
                self.curEventLength = len(eventsPeek)

            if not len(self.capturedChars) == 0:
                return self.capturedChars.pop(0)
            else:
                return None
        else:
            dr,dw,de = select.select([sys.stdin], [], [], 0)
            if not dr == []:
                return sys.stdin.read(1)
            return None

Simple use case:

with KeyPoller() as keyPoller:
    while True:
        c = keyPoller.poll()
        if not c is None:
            if c == "c":
                break
            print c

The same as above, except that poll only returns something once the user presses a newline.

Robots:

These are something that can be called to programmatically fire keyboard events. This can be used alongside key captures to echo them back out to the user

Windows:

# Modified from http://stackoverflow.com/a/13615802/2924421

import ctypes
from ctypes import wintypes
import time

user32 = ctypes.WinDLL('user32', use_last_error=True)

INPUT_MOUSE    = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP       = 0x0002
KEYEVENTF_UNICODE     = 0x0004
KEYEVENTF_SCANCODE    = 0x0008

MAPVK_VK_TO_VSC = 0

# C struct definitions
wintypes.ULONG_PTR = wintypes.WPARAM

SendInput = ctypes.windll.user32.SendInput

PUL = ctypes.POINTER(ctypes.c_ulong)

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class MOUSEINPUT(ctypes.Structure):
    _fields_ = (("dx",          wintypes.LONG),
                ("dy",          wintypes.LONG),
                ("mouseData",   wintypes.DWORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = (("uMsg",    wintypes.DWORD),
                ("wParamL", wintypes.WORD),
                ("wParamH", wintypes.WORD))

class INPUT(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = (("ki", KEYBDINPUT),
                    ("mi", MOUSEINPUT),
                    ("hi", HARDWAREINPUT))
    _anonymous_ = ("_input",)
    _fields_ = (("type",   wintypes.DWORD),
                ("_input", _INPUT))

LPINPUT = ctypes.POINTER(INPUT)

def _check_count(result, func, args):
    if result == 0:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
                             LPINPUT,       # pInputs
                             ctypes.c_int)  # cbSize

def KeyDown(unicodeKey):
    key, unikey, uniflag = GetKeyCode(unicodeKey)
    x = INPUT( type=INPUT_KEYBOARD, ki= KEYBDINPUT( key, unikey, uniflag, 0))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def KeyUp(unicodeKey):
    key, unikey, uniflag = GetKeyCode(unicodeKey)
    extra = ctypes.c_ulong(0)
    x = INPUT( type=INPUT_KEYBOARD, ki= KEYBDINPUT( key, unikey, uniflag | KEYEVENTF_KEYUP, 0))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def KeyPress(unicodeKey):
    time.sleep(0.0001)
    KeyDown(unicodeKey)
    time.sleep(0.0001)
    KeyUp(unicodeKey)
    time.sleep(0.0001)


def GetKeyCode(unicodeKey):
    k = unicodeKey
    curKeyCode = 0
    if k == "up": curKeyCode = 0x26
    elif k == "down": curKeyCode = 0x28
    elif k == "left": curKeyCode = 0x25
    elif k == "right": curKeyCode = 0x27
    elif k == "home": curKeyCode = 0x24
    elif k == "end": curKeyCode = 0x23
    elif k == "insert": curKeyCode = 0x2D
    elif k == "pgup": curKeyCode = 0x21
    elif k == "pgdn": curKeyCode = 0x22
    elif k == "delete": curKeyCode = 0x2E
    elif k == "\n": curKeyCode = 0x0D

    if curKeyCode == 0:
        return 0, int(unicodeKey.encode("hex"), 16), KEYEVENTF_UNICODE
    else:
        return curKeyCode, 0, 0

OS X:

#!/usr/bin/env python

import time
from Quartz.CoreGraphics import CGEventCreateKeyboardEvent
from Quartz.CoreGraphics import CGEventPost

# Python releases things automatically, using CFRelease will result in a scary error
#from Quartz.CoreGraphics import CFRelease

from Quartz.CoreGraphics import kCGHIDEventTap

# From http://stackoverflow.com/questions/281133/controlling-the-mouse-from-python-in-os-x
# and from https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/index.html#//apple_ref/c/func/CGEventCreateKeyboardEvent


def KeyDown(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)

def KeyUp(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

def KeyPress(k):
    keyCode, shiftKey = toKeyCode(k)

    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, True))
        time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, True))
    time.sleep(0.0001)

    CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, keyCode, False))
    time.sleep(0.0001)

    if shiftKey:
        CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(None, 0x38, False))
        time.sleep(0.0001)



# From http://stackoverflow.com/questions/3202629/where-can-i-find-a-list-of-mac-virtual-key-codes

def toKeyCode(c):
    shiftKey = False
    # Letter
    if c.isalpha():
        if not c.islower():
            shiftKey = True
            c = c.lower()

    if c in shiftChars:
        shiftKey = True
        c = shiftChars[c]
    if c in keyCodeMap:
        keyCode = keyCodeMap[c]
    else:
        keyCode = ord(c)
    return keyCode, shiftKey

shiftChars = {
    '~': '`',
    '!': '1',
    '@': '2',
    '#': '3',
    '$': '4',
    '%': '5',
    '^': '6',
    '&': '7',
    '*': '8',
    '(': '9',
    ')': '0',
    '_': '-',
    '+': '=',
    '{': '[',
    '}': ']',
    '|': '\\',
    ':': ';',
    '"': '\'',
    '<': ',',
    '>': '.',
    '?': '/'
}


keyCodeMap = {
    'a'                 : 0x00,
    's'                 : 0x01,
    'd'                 : 0x02,
    'f'                 : 0x03,
    'h'                 : 0x04,
    'g'                 : 0x05,
    'z'                 : 0x06,
    'x'                 : 0x07,
    'c'                 : 0x08,
    'v'                 : 0x09,
    'b'                 : 0x0B,
    'q'                 : 0x0C,
    'w'                 : 0x0D,
    'e'                 : 0x0E,
    'r'                 : 0x0F,
    'y'                 : 0x10,
    't'                 : 0x11,
    '1'                 : 0x12,
    '2'                 : 0x13,
    '3'                 : 0x14,
    '4'                 : 0x15,
    '6'                 : 0x16,
    '5'                 : 0x17,
    '='                 : 0x18,
    '9'                 : 0x19,
    '7'                 : 0x1A,
    '-'                 : 0x1B,
    '8'                 : 0x1C,
    '0'                 : 0x1D,
    ']'                 : 0x1E,
    'o'                 : 0x1F,
    'u'                 : 0x20,
    '['                 : 0x21,
    'i'                 : 0x22,
    'p'                 : 0x23,
    'l'                 : 0x25,
    'j'                 : 0x26,
    '\''                : 0x27,
    'k'                 : 0x28,
    ';'                 : 0x29,
    '\\'                : 0x2A,
    ','                 : 0x2B,
    '/'                 : 0x2C,
    'n'                 : 0x2D,
    'm'                 : 0x2E,
    '.'                 : 0x2F,
    '`'                 : 0x32,
    'k.'                : 0x41,
    'k*'                : 0x43,
    'k+'                : 0x45,
    'kclear'            : 0x47,
    'k/'                : 0x4B,
    'k\n'               : 0x4C,
    'k-'                : 0x4E,
    'k='                : 0x51,
    'k0'                : 0x52,
    'k1'                : 0x53,
    'k2'                : 0x54,
    'k3'                : 0x55,
    'k4'                : 0x56,
    'k5'                : 0x57,
    'k6'                : 0x58,
    'k7'                : 0x59,
    'k8'                : 0x5B,
    'k9'                : 0x5C,

    # keycodes for keys that are independent of keyboard layout
    '\n'                : 0x24,
    '\t'                : 0x30,
    ' '                 : 0x31,
    'del'               : 0x33,
    'delete'            : 0x33,
    'esc'               : 0x35,
    'escape'            : 0x35,
    'cmd'               : 0x37,
    'command'           : 0x37,
    'shift'             : 0x38,
    'caps lock'         : 0x39,
    'option'            : 0x3A,
    'ctrl'              : 0x3B,
    'control'           : 0x3B,
    'right shift'       : 0x3C,
    'rshift'            : 0x3C,
    'right option'      : 0x3D,
    'roption'           : 0x3D,
    'right control'     : 0x3E,
    'rcontrol'          : 0x3E,
    'fun'               : 0x3F,
    'function'          : 0x3F,
    'f17'               : 0x40,
    'volume up'         : 0x48,
    'volume down'       : 0x49,
    'mute'              : 0x4A,
    'f18'               : 0x4F,
    'f19'               : 0x50,
    'f20'               : 0x5A,
    'f5'                : 0x60,
    'f6'                : 0x61,
    'f7'                : 0x62,
    'f3'                : 0x63,
    'f8'                : 0x64,
    'f9'                : 0x65,
    'f11'               : 0x67,
    'f13'               : 0x69,
    'f16'               : 0x6A,
    'f14'               : 0x6B,
    'f10'               : 0x6D,
    'f12'               : 0x6F,
    'f15'               : 0x71,
    'help'              : 0x72,
    'home'              : 0x73,
    'pgup'              : 0x74,
    'page up'           : 0x74,
    'forward delete'    : 0x75,
    'f4'                : 0x76,
    'end'               : 0x77,
    'f2'                : 0x78,
    'page down'         : 0x79,
    'pgdn'              : 0x79,
    'f1'                : 0x7A,
    'left'              : 0x7B,
    'right'             : 0x7C,
    'down'              : 0x7D,
    'up'                : 0x7E
}

How to initialise memory with new operator in C++?

you can always use memset:

int myArray[10];
memset( myArray, 0, 10 * sizeof( int ));

How to log a method's execution time exactly in milliseconds?

Here is another way, in Swift, to do that using the defer keyword

func methodName() {
  let methodStart = Date()
  defer {
    let executionTime = Date().timeIntervalSince(methodStart)
    print("Execution time: \(executionTime)")
  }
  // do your stuff here
}

From Apple's docs: A defer statement is used for executing code just before transferring program control outside of the scope that the defer statement appears in.

This is similar to a try/finally block with the advantage of having the related code grouped.

Why is it not advisable to have the database and web server on the same machine?

Wow, No one brings up the fact that if you actually buy SQL server at 5k bucks, you might want to use it for more than your web application. If your using express, maybe you don't care. I see SQL servers run Databases for 20 to 30 applicaitions, so putting it on the webserver would not be smart.

Secondly, depends on whom the server is for. I do work for financial companies and the govt. So we use a crazy pain in the arse approach of using only sprocs and limiting ports from webserver to SQL. So if the web app gets hacked. The only thing the hacker can do is call sprocs as the user account on the webserver is locked down to only see/call sprocs on the DB. So now the hacker has to figure out how to get into the DB. If its on the web server well its kind of easy to get to.

Using momentjs to convert date to epoch then back to date

There are a few things wrong here:

  • First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".

  • .unix() returns Unix Time in whole seconds, but the default moment constructor accepts a timestamp in milliseconds. You should instead use .valueOf() to return milliseconds. Note that calling .unix()*1000 would also work, but it would result in a loss of precision.

  • You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:

    moment("10/15/2014 9:00", "M/D/YYYY H:mm")
    
  • .calendar() has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format() function instead. Again, you may want to pass a format specifier.

  • To answer your questions in comments, No - you don't need to call .local() or .utc().

Putting it all together:

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);

On my machine, in the US Pacific time zone, it results in:

Values are: ts = 1413388800000, s = 10/15/2014 9:00

Since the input value is interpreted in terms of local time, you will get a different value for ts if you are in a different time zone.

Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix() to return the timestamp in whole seconds, and moment.unix(ts) to parse it back to a moment.

var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);

Handling the window closing event with WPF / MVVM Light Toolkit

We use AttachedCommandBehavior for this. You can attach any event to a command on your view model avoiding any code behind.

We use it throughout our solution and have almost zero code behind

http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/

Is it ok to use `any?` to check if an array is not empty?

The difference between an array evaluating its values to true or if its empty.

The method empty? comes from the Array class
http://ruby-doc.org/core-2.0.0/Array.html#method-i-empty-3F

It's used to check if the array contains something or not. This includes things that evaluate to false, such as nil and false.

>> a = []
=> []
>> a.empty?
=> true
>> a = [nil, false]
=> [nil, false]
>> a.empty?
=> false
>> a = [nil]
=> [nil]
>> a.empty?
=> false

The method any? comes from the Enumerable module.
http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-any-3F

It's used to evaluate if "any" value in the array evaluates to true. Similar methods to this are none?, all? and one?, where they all just check to see how many times true could be evaluated. which has nothing to do with the count of values found in a array.

case 1

>> a = []
=> []
>> a.any?
=> false
>> a.one?
=> false
>> a.all?
=> true
>> a.none?
=> true

case 2

>> a = [nil, true]
=> [nil, true]
>> a.any?
=> true
>> a.one?
=> true
>> a.all?
=> false
>> a.none?
=> false

case 3

>> a = [true, true]
=> [true, true]
>> a.any?
=> true
>> a.one?
=> false
>> a.all?
=> true
>> a.none?
=> false

Does HTTP use UDP?

Maybe some change on this topic with QUIC

QUIC (Quick UDP Internet Connections, pronounced quick) is an experimental transport layer network protocol developed by Google and implemented in 2013. QUIC supports a set of multiplexed connections between two endpoints over User Datagram Protocol (UDP), and was designed to provide security protection equivalent to TLS/SSL, along with reduced connection and transport latency, and bandwidth estimation in each direction to avoid congestion. QUIC's main goal is to optimize connection-oriented web applications currently using TCP.

Link to a section of a webpage

The fragment identifier (also known as: Fragment IDs, Anchor Identifiers, Named Anchors) introduced by a hash mark # is the optional last part of a URL for a document. It is typically used to identify a portion of that document.

<a href="http://www.someuri.com/page#fragment">Link to fragment identifier</a>

Syntax for URIs also allows an optional query part introduced by a question mark ?. In URIs with a query and a fragment the fragment follows the query.

<a href="http://www.someuri.com/page?query=1#fragment">Link to fragment with a query</a>

When a Web browser requests a resource from a Web server, the agent sends the URI to the server, but does not send the fragment. Instead, the agent waits for the server to send the resource, and then the agent (Web browser) processes the resource according to the document type and fragment value.

Named Anchors <a name="fragment"> are deprecated in XHTML 1.0, the ID attribute is the suggested replacement. <div id="fragment"></div>

3-dimensional array in numpy

Read this article for better insight. Note: Numpy reports the shape of 3D arrays in the order layers, rows, columns.

https://opensourceoptions.com/blog/numpy-array-shapes-and-reshaping-arrays/#:~:text=3D%20arrays,order%20layers%2C%20rows%2C%20columns.

Iterating through list of list in Python

if you don't want recursion you could try:

x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]
layer1=x
layer2=[]
while True:
    for i in layer1:
        if isinstance(i,list):
            for j in i:
                layer2.append(j)
        else:
            print i
    layer1[:]=layer2
    layer2=[]
    if len(layer1)==0:
        break

which gives:

sam
Test
Test2
(u'file.txt', ['id', 1, 0])
(u'file2.txt', ['id', 1, 2])
one

(note that it didn't look into the tuples for lists because the tuples aren't lists. You can add tuple to the "isinstance" method if you want to fix this)

Which tool to build a simple web front-end to my database

I think PHP is a good solution. It's simple to set up, free and there is plenty of documentation on how to create a database management app. Ruby on Rails is faster to code but a bit more difficult to set up.

Disabling swap files creation in vim

To disable swap files from within vim, type

:set noswapfile

To disable swap files permanently, add the below to your ~/.vimrc file

set noswapfile

For more details see the Vim docs on swapfile

How to force reloading php.ini file?

You also can use graceful restart the apache server with service apache2 reload or apachectl -k graceful. As the apache doc says:

The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.

Deploying just HTML, CSS webpage to Tomcat

There is no real need to create a war to run it from Tomcat. You can follow these steps

  1. Create a folder in webapps folder e.g. MyApp

  2. Put your html and css in that folder and name the html file, which you want to be the starting page for your application, index.html

  3. Start tomcat and point your browser to url "http://localhost:8080/MyApp". Your index.html page will pop up in the browser

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
            Else
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
        MsgBox ("Bingo not found")
End If

Update

In my

With Sheet1
    .....
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

DataTable: How to get item value with row name and column name? (VB)

Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
     searchedValue = rows(0).Item("ColumnName2") 
End If

With FirstOrDefault:

Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
     searchedValue = row.Item("ColumnName2") 
End If

In C#:

var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
     searchedValue = row["ColumnName2"];

Multiline strings in VB.NET

VB.Net has no such feature and it will not be coming in Visual Studio 2010. The feature that jirwin is refering is called implicit line continuation. It has to do with removing the _ from a multi-line statement or expression. This does remove the need to terminate a multiline string with _ but there is still no mult-line string literal in VB.

Example for multiline string

Visual Studio 2008

Dim x = "line1" & vbCrlf & _
        "line2"

Visual Studio 2010

Dim x = "line1" & vbCrlf & 
        "line2"

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

The difference between sys.stdout.write and print?

Are there situations in which sys.stdout.write() is preferable to print?

I have found that stdout works better than print in a multithreading situation. I use a queue (FIFO) to store the lines to print and I hold all threads before the print line until my print queue is empty. Even so, using print I sometimes lose the final \n on the debug I/O (using the Wing Pro IDE).

When I use std.out with \n in the string, the debug I/O formats correctly and the \n's are accurately displayed.

MINGW64 "make build" error: "bash: make: command not found"

  • Go to ezwinports, https://sourceforge.net/projects/ezwinports/files/

  • Download make-4.2.1-without-guile-w32-bin.zip (get the version without guile)

  • Extract zip
  • Copy the contents to C:\ProgramFiles\Git\mingw64\ merging the folders, but do NOT overwrite/replace any exisiting files.

Install Qt on Ubuntu

Also take a look at awesome project aqtinstall https://github.com/miurahr/aqtinstall/ (it can install any Qt version on Linux, Mac and Windows machines without any interaction!) and GitHub Action that uses this tool: https://github.com/jurplel/install-qt-action

How to make jQuery UI nav menu horizontal?

I'm new to stackoverflow, so please be nice :) however turning to the problem of horizontal jQuery ui menu, the only way I could manage to resolve the problem (refering to this) was to set:

#nav li {width: auto; clear: none; float: left}
#nav ul li {width: auto; clear: none; float:none}

CSS - Syntax to select a class within an id

This will also work and you don't need the extra class:

#navigation li li {}

If you have a third level of LI's you may have to reset/override some of the styles they will inherit from the above selector. You can target the third level like so:

#navigation li li li {}

Getting "conflicting types for function" in C, why?

A C Function-Declaration Backgrounder

In C, function declarations don't work like they do in other languages: The C compiler itself doesn't search backward and forward in the file to find the function's declaration from the place you call it, and it doesn't scan the file multiple times to figure out the relationships either: The compiler only scans forward in the file exactly once, from top to bottom. Connecting function calls to function declarations is part of the linker's job, and is only done after the file is compiled down to raw assembly instructions.

This means that as the compiler scans forward through the file, the very first time the compiler encounters the name of a function, one of two things have to be the case: It either is seeing the function declaration itself, in which case the compiler knows exactly what the function is and what types it takes as arguments and what types it returns — or it's a call to the function, and the compiler has to guess how the function will eventually be declared.

(There's a third option, where the name is used in a function prototype, but we'll ignore that for now, since if you're seeing this problem in the first place, you're probably not using prototypes.)

History Lesson

In the earliest days of C, the fact that the compiler had to guess types wasn't really an issue: All of the types were more-or-less the same — pretty much everything was either an int or a pointer, and they were the same size. (In fact, in B, the language that preceded C, there were no types at all; everything was just an int or pointer and its type was determined solely by how you used it!) So the compiler could safely guess the behavior of any function just based on the number of parameters that were passed: If you passed two parameters, the compiler would push two things onto the call stack, and presumably the callee would have two arguments declared, and that would all line up. If you passed only one parameter but the function expected two, it would still sort-of work, and the second argument would just be ignored/garbage. If you passed three parameters and the function expected two, it would also still sort-of work, and the third parameter would be ignored and stomped on by the function's local variables. (Some old C code still expects these mismatched-argument rules will work, too.)

But having the compiler let you pass anything to anything isn't really a good way to design a programming language. It worked well in the early days because the early C programmers were mostly wizards, and they knew not to pass the wrong type to functions, and even if they did get the types wrong, there were always tools like lint that could do deeper double-checking of your C code and warn you about such things.

Fast-forward to today, and we're not quite in the same boat. C has grown up, and a lot of people are programming in it who aren't wizards, and to accommodate them (and to accommodate everyone else who regularly used lint anyway), the compilers have taken on many of the abilities that were previously part of lint — especially the part where they check your code to ensure it's type-safe. Early C compilers would let you write int foo = "hello"; and it would just blithely assign the pointer to the integer, and it was up to you to make sure you weren't doing anything stupid. Modern C compilers complain loudly when you get your types wrong, and that's a good thing.

Type Conflicts

So what's all this got to do with the mysterious conflicting-type error on the line of the function declaration? As I said above, C compilers still have to either know or guess what a name means the first time they see that name as they scan forward through the file: They can know what it means it if it's an actual function declaration itself (or a function "prototype," more on that shortly), but if it's just a call to the function, they have to guess. And, sadly, the guess is often wrong.

When the compiler saw your call to do_something(), it looked at how it was invoked, and it concluded that do_something() would eventually be declared like this:

int do_something(char arg1[], char arg2[])
{
    ...
}

Why did it conclude that? Because that's how you called it! (Some C compilers may conclude that it was int do_something(int arg1, int arg2), or simply int do_something(...), both of which are even farther from what you want, but the important point is that regardless of how the compiler guesses the types, it guesses them differently from what your actual function uses.)

Later on, as the compiler scans forward in the file, it sees your actual declaration of char *do_something(char *, char *). That function declaration isn't even close to the declaration that the compiler guessed, which means that the line where the compiler compiled the call was compiled wrong, and the program is just not going to work. So it rightly prints an error telling you that your code isn't going to work as written.

You might be wondering, "Why does it assume I'm returning an int?" Well, it assumes that type because there's no information to the contrary: printf() can take in any type in its variable arguments, so without a better answer, int is as good a guess as any. (Many early C compilers always assumed int for every unspecified type, and assumed you meant ... for the arguments for every function declared f() — not void — which is why many modern code standards recommend always putting void in for the arguments if there really aren't supposed to be any.)

The Fix

There are two common fixes for the function-declaration error.

The first solution, which is recommended by many other answers here, is to put a prototype in the source code above the place where the function is first called. A prototype looks just like the function's declaration, but it has a semicolon where the body should be:

char *do_something(char *dest, const char *src);

By putting the prototype first, the compiler then knows what the function will eventually look like, so it doesn't have to guess. By convention, programmers often put prototypes at the top of the file, just under the #include statements, to ensure that they'll always be defined before any potential usages of them.

The other solution, which also shows up in some real-world code, is to simply reorder your functions so that the function declarations are always before anything that calls them! You could move the entire char *do_something(char *dest, const char *src) { ... } function above the first call to it, and the compiler then would know exactly what the function looks like and wouldn't have to guess.

In practice, most people use function prototypes, because you can also take function prototypes and move them into header (.h) files so that code in other .c files can call those functions. But either solution works, and many codebases use both.

C99 and C11

It is useful to note that the rules are slightly different in the newer versions of the C standard. In the earlier versions (C89 and K&R), the compiler really would guess the types at function-call time (and K&R-era compilers often wouldn't even warn you if they were wrong). C99 and C11 both require that the function declaration/prototype must precede the first call, and it's an error if it doesn't. But many modern C compilers — mainly for backward compatibility with earlier code — will only warn about a missing prototype and not consider it an error.

Setting the Vim background colors

Try adding

set background=dark

to your .gvimrc too. This work well for me.

Generate a sequence of numbers in Python

This works by exploiting the % properties of the list rather than the increments.

for num in range(1,100):
    if num % 4 == 1 or num % 4 ==2:
        n.append(num)
        continue
    pass

ImportError: No module named apiclient.discovery

apiclient was the original name of the library.
At some point, it was switched over to be googleapiclient.

If your code is running on Google App Engine, both should work.

If you are running the application yourself, with the google-api-python-client installed, both should work as well.

Although, if we take a look at the source code of the apiclient package's __init__.py module, we can see that the apiclient module was simply kept around for backwards-compatibility.

Retain apiclient as an alias for googleapiclient.

So, you really should be using googleapiclient in your code, since the apiclient alias was just maintained as to not break legacy code.

# bad
from apiclient.discovery import build

# good
from googleapiclient.discovery import build

Open a local HTML file using window.open in Chrome

This worked for me fine:

File 1:

    <html>
    <head></head>
    <body>
        <a href="#" onclick="window.open('file:///D:/Examples/file2.html'); return false">CLICK ME</a>
    </body>
    <footer></footer>
    </html>

File 2:

    <html>
        ...
    </html>

This method works regardless of whether or not the 2 files are in the same directory, BUT both files must be local.

For obvious security reasons, if File 1 is located on a remote server you absolutely cannot open a file on some client's host computer and trying to do so will open a blank target.

UICollectionView current visible cell index

Swift 3 & Swift 4:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
   var visibleRect = CGRect()

   visibleRect.origin = collectionView.contentOffset
   visibleRect.size = collectionView.bounds.size

   let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)

   guard let indexPath = collectionView.indexPathForItem(at: visiblePoint) else { return } 

   print(indexPath[1])
}

If you want to show actual number than you can add +1

Android check null or empty string in Android

All you can do is to call equals() method on empty String literal and pass the object you are testing as shown below :

 String nullString = null;
 String empty = new String();
 boolean test = "".equals(empty); // true 
 System.out.println(test); 
 boolean check = "".equals(nullString); // false 
 System.out.println(check);

What is the Difference Between Mercurial and Git?

Sometime last year I evaluated both git and hg for my own use, and decided to go with hg. I felt it looked like a cleaner solution, and worked better on more platforms at the time. It was mostly a toss-up, though.

More recently, I started using git because of git-svn and the ability to act as a Subversion client. This won me over and I've now switched completely to git. I think it's got a slightly higher learning curve (especially if you need to poke around the insides), but it really is a great system. I'm going to go read those two comparison articles that John posted now.

How to debug Lock wait timeout exceeded on MySQL?

Due to the popularity of MySQL, there's no wonder Lock wait timeout exceeded; try restarting transaction exception gets so much attention on SO.

The more contention you have, the greater the chance of deadlocks, which a DB engine will resolve by time-outing one of the deadlocked transactions.

Also, long-running transactions that have modified (e.g. UPDATE or DELETE) a large number of entries are more likely to generate conflicts with other transactions.

Although InnoDB MVCC, you can still request explicit locks using the FOR UPDATE clause. However, unlike other popular DBs (Oracle, MSSQL, PostgreSQL, DB2), MySQL uses REPEATABLE_READ as the default isolation level.

Now, the locks that you acquired (either by modifying rows or using explicit locking), are held for the duration of the currently running transaction. If you want a good explanation of the difference between REPEATABLE_READ and READ COMMITTED in regards to locking, please read this Percona article.

In REPEATABLE READ every lock acquired during a transaction is held for the duration of the transaction.

In READ COMMITTED the locks that did not match the scan are released after the STATEMENT completes.

...

This means that in READ COMMITTED other transactions are free to update rows that they would not have been able to update (in REPEATABLE READ) once the UPDATE statement completes.

Therefore: The more restrictive the isolation level (REPEATABLE_READ, SERIALIZABLE) the greater the chance of deadlock. This is not an issue "per se", it's a trade-off.

You can get very good results with READ_COMMITED, as you need application-level lost update prevention when using logical transactions that span over multiple HTTP requests. The optimistic locking approach targets lost updates that might happen even if you use the SERIALIZABLE isolation level while reducing the lock contention by allowing you to use READ_COMMITED.

CROSS JOIN vs INNER JOIN in SQL

Cross join does not combine the rows, if you have 100 rows in each table with 1 to 1 match, you get 10.000 results, Innerjoin will only return 100 rows in the same situation.

These 2 examples will return the same result:

Cross join

select * from table1 cross join table2 where table1.id = table2.fk_id

Inner join

select * from table1 join table2 on table1.id = table2.fk_id

Use the last method

How can I add a volume to an existing Docker container?

I've successfully mount /home/<user-name> folder of my host to the /mnt folder of the existing (not running) container. You can do it in the following way:

  1. Open configuration file corresponding to the stopped container, which can be found at /var/lib/docker/containers/99d...1fb/config.v2.json (may be config.json for older versions of docker).

  2. Find MountPoints section, which was empty in my case: "MountPoints":{}. Next replace the contents with something like this (you can copy proper contents from another container with proper settings):

"MountPoints":{"/mnt":{"Source":"/home/<user-name>","Destination":"/mnt","RW":true,"Name":"","Driver":"","Type":"bind","Propagation":"rprivate","Spec":{"Type":"bind","Source":"/home/<user-name>","Target":"/mnt"},"SkipMountpointCreation":false}}

or the same (formatted):

  "MountPoints": {
    "/mnt": {
      "Source": "/home/<user-name>",
      "Destination": "/mnt",
      "RW": true,
      "Name": "",
      "Driver": "",
      "Type": "bind",
      "Propagation": "rprivate",
      "Spec": {
        "Type": "bind",
        "Source": "/home/<user-name>",
        "Target": "/mnt"
      },
      "SkipMountpointCreation": false
    }
  }
  1. Restart the docker service: service docker restart

This works for me with Ubuntu 18.04.1 and Docker 18.09.0

Converting a String to Object

A String is a type of Object. So any method that accepts Object as parameter will surely accept String also. Please provide more of your code if you still do not find a solution.

How to remove border from specific PrimeFaces p:panelGrid?

I placed the panelgrid inside datatable, and hence my working solution is

.ui-datatable-scrollable-body .myStyleClass tbody td{border:none;}

for

<h:panelGrid  styleClass="myStyleClass" >...</h:panelGrid>

What is the difference between HTML tags <div> and <span>?

I would say that if you know a bit of spanish to look at this page, where is properly explained.

However, a fast definition would be that div is for dividing sections and span is for applying some kind of style to an element within another block element like div.

Converting Date and Time To Unix Timestamp

Seems like getTime is not function on above answer.

Date.parse(currentDate)/1000

a tag as a submit button?

Supposing the form is the direct parent you can do:

<a href='#' onclick='this.parentNode.submit(); return false;'>submit</a>

If not you can access through the forms name attribute like this:

<a href='#' onclick='document.forms["myform"].submit(); return false;'>submit</a>

See both examples here: http://jsfiddle.net/WEZDC/1/

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

Just to elaborate a bit more on Henry's answer, you can also use specific error codes, from raise_application_error and handle them accordingly on the client side. For example:

Suppose you had a PL/SQL procedure like this to check for the existence of a location record:

   PROCEDURE chk_location_exists
   (
      p_location_id IN location.gie_location_id%TYPE
   )
   AS
      l_cnt INTEGER := 0;
   BEGIN
      SELECT COUNT(*)
        INTO l_cnt
        FROM location
       WHERE gie_location_id = p_location_id;

       IF l_cnt = 0
       THEN
          raise_application_error(
             gc_entity_not_found,
             'The associated location record could not be found.');
       END IF;
   END;

The raise_application_error allows you to raise a specific error code. In your package header, you can define: gc_entity_not_found INTEGER := -20001;

If you need other error codes for other types of errors, you can define other error codes using -20002, -20003, etc.

Then on the client side, you can do something like this (this example is for C#):

/// <summary>
/// <para>Represents Oracle error number when entity is not found in database.</para>
/// </summary>
private const int OraEntityNotFoundInDB = 20001;

And you can execute your code in a try/catch

try
{
   // call the chk_location_exists SP
}
catch (Exception e)
{
    if ((e is OracleException) && (((OracleException)e).Number == OraEntityNotFoundInDB))
    {
        // create an EntityNotFoundException with message indicating that entity was not found in
        // database; use the message of the OracleException, which will indicate the table corresponding
        // to the entity which wasn't found and also the exact line in the PL/SQL code where the application
        // error was raised
        return new EntityNotFoundException(
            "A required entity was not found in the database: " + e.Message);
    }
}

Android: Tabs at the BOTTOM

This may not be exactly what you're looking for (it's not an "easy" solution to send your Tabs to the bottom of the screen) but is nevertheless an interesting alternative solution I would like to flag to you :

ScrollableTabHost is designed to behave like TabHost, but with an additional scrollview to fit more items ...

maybe digging into this open-source project you'll find an answer to your question. If I see anything easier I'll come back to you.

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

The problem is that dataTable is not defined at the point you are calling this method.

Ensure that you are loading the .js files in the correct order:

<script src="/Scripts/jquery.dataTables.js"></script>
<script src="/Scripts/dataTables.bootstrap.js"></script>

Transactions in .net

You could also wrap the transaction up into it's own stored procedure and handle it that way instead of doing transactions in C# itself.

What is the "Temporary ASP.NET Files" folder for?

Thats where asp.net puts dynamically compiled assemblies.

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

Great answers, but you could just open the command prompt and type in

 SET PATH=C:\Program Files\Nodejs;%PATH%

Currency format for display

You can use string.Format("{0:c}", value).

See also here:

Plotting a list of (x, y) coordinates in python matplotlib

If you want to plot a single line connecting all the points in the list

plt.plot(li[:])

plt.show()

This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.

Linq with group by having count

Like this:

from c in db.Company
group c by c.Name into grp
where grp.Count() > 1
select grp.Key

Or, using the method syntax:

Company
    .GroupBy(c => c.Name)
    .Where(grp => grp.Count() > 1)
    .Select(grp => grp.Key);

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

$ git fetch --unshallow origin
$ git push you remote name

Directory Chooser in HTML page

If you do not have too many folders then I suggest you use if statements to choose an upload folder depending on the user input details. E.g.

String user= request.getParameter("username");
if (user=="Alfred"){
//Path A;
}
if (user=="other"){
//Path B;
}

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

With MySQL 8+ the new default authentication is caching_sha2_password instead of mysql_native_password. The new and more secure authentication method is not supported by the native mysql package yet, but you should consider using the package @mysql/xdevapi instead, which is officially supported and maintained by Oracle.

To install the new package, run:

npm install @mysql/xdevapi --save --save-exact

To connect to the database and INSERT some VALUES:

const mysqlx = require('@mysql/xdevapi');
var myTable;

mysqlx
    .getSession({
        user: 'root',
        password: '*****',
        host: 'localhost',
        port: 33060
    })
    .then(function (session) {

    // Accessing an existing table
    myTable = session.getSchema('Database_Name').getTable('Table_Name');

    // Insert SQL Table data
    return myTable
        .insert(['first_name', 'last_name'])
        .values(['John', 'Doe'])
        .execute()
    });

The official package documentation can be found here: https://dev.mysql.com/doc/dev/connector-nodejs/8.0/

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

Depending on what you want to accomplish, you might replace INSERT with INSERT IGNORE in your file. This will avoid generating an error for the rows that you are trying to insert and already exist.

See http://dev.mysql.com/doc/refman/5.5/en/insert.html.

How to refresh the data in a jqGrid?

var newdata= //You call Ajax peticion//

$("#idGrid").clearGridData();

$("#idGrid").jqGrid('setGridParam', {data:newdata)});
$("#idGrid").trigger("reloadGrid");

in event update data table

How to include() all PHP files from a directory?

Do no write a function() to include files in a directory. You may lose the variable scopes, and may have to use "global". Just loop on the files.

Also, you may run into difficulties when an included file has a class name that will extend to the other class defined in the other file - which is not yet included. So, be careful.

How to run Nginx within a Docker container without halting?

Adding this command to Dockerfile can disable it:

RUN echo "daemon off;" >> /etc/nginx/nginx.conf

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

You can use a vector. Instead of worry about different screen sizes you only need to create an .svg file and import it to your project using Vector Asset Studio.

Spark dataframe: collect () vs select ()

calling select will result is lazy evaluation: for example:

val df1 = df.select("col1")
val df2 = df1.filter("col1 == 3")

both above statements create lazy path that will be executed when you call action on that df, such as show, collect etc.

val df3 = df2.collect()

use .explain at the end of your transformation to follow its plan here is more detailed info Transformations and Actions

What are the rules for calling the superclass constructor?

If you have default parameters in your base constructor the base class will be called automatically.

using namespace std;

class Base
{
    public:
    Base(int a=1) : _a(a) {}

    protected:
    int _a;
};

class Derived : public Base
{
  public:
  Derived() {}

  void printit() { cout << _a << endl; }
};

int main()
{
   Derived d;
   d.printit();
   return 0;
}

Output is: 1

Webpack not excluding node_modules

From your config file, it seems like you're only excluding node_modules from being parsed with babel-loader, but not from being bundled.

In order to exclude node_modules and native node libraries from bundling, you need to:

  1. Add target: 'node' to your webpack.config.js. This will exclude native node modules (path, fs, etc.) from being bundled.
  2. Use webpack-node-externals in order to exclude other node_modules.

So your result config file should look like:

var nodeExternals = require('webpack-node-externals');
...
module.exports = {
    ...
    target: 'node', // in order to ignore built-in modules like path, fs, etc. 
    externals: [nodeExternals()], // in order to ignore all modules in node_modules folder 
    ...
};

How to send email via Django?

For Django version 1.7, if above solutions dont work then try the following

in settings.py add

#For email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_USE_TLS = True

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_HOST_USER = '[email protected]'

#Must generate specific password for your app in [gmail settings][1]
EMAIL_HOST_PASSWORD = 'app_specific_password'

EMAIL_PORT = 587

#This did the trick
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

The last line did the trick for django 1.7

What does '?' do in C++?

You can just rewrite it as:

int qempty(){ return(f==r);}

Which does the same thing as said in the other answers.

SimpleDateFormat and locale based format string

Localization of date string:

Based on redsonic's post:

private String localizeDate(String inputdate, Locale locale) { 

    Date date = new Date();
    SimpleDateFormat dateFormatCN = new SimpleDateFormat("dd-MMM-yyyy", locale);       
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");


    try {
        date = dateFormat.parse(inputdate);
    } catch (ParseException e) {
        log.warn("Input date was not correct. Can not localize it.");
        return inputdate;
    }
    return dateFormatCN.format(date);
}

String localizedDate = localizeDate("05-Sep-2013", new Locale("zh","CN"));

will be like 05-??-2013

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

Check to see if cURL is installed locally?

In the Terminal, type:

$ curl -V

That's a capital V for the version

Create an ISO date object in javascript

This worked for me:

_x000D_
_x000D_
var start = new Date("2020-10-15T00:00:00.000+0000");
 //or
start = new date("2020-10-15T00:00:00.000Z");

collection.find({
    start_date:{
        $gte: start
    }
})...etc
_x000D_
_x000D_
_x000D_ new Date(2020,9,15,0,0,0,0) may lead to wrong date: i mean non ISO format (remember javascript count months from 0 to 11 so it's 9 for october)

MySql difference between two timestamps in days?

SELECT DATEDIFF(max_date, min_date) as days from my table. This works even if the col max_date and min_date are in string data types.

How do I discover memory usage of my application in Android?

Yes, you can get memory info programmatically and decide whether to do memory intensive work.

Get VM Heap Size by calling:

Runtime.getRuntime().totalMemory();

Get Allocated VM Memory by calling:

Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

Get VM Heap Size Limit by calling:

Runtime.getRuntime().maxMemory()

Get Native Allocated Memory by calling:

Debug.getNativeHeapAllocatedSize();

I made an app to figure out the OutOfMemoryError behavior and monitor memory usage.

https://play.google.com/store/apps/details?id=net.coocood.oomresearch

You can get the source code at https://github.com/coocood/oom-research

Add Bootstrap Glyphicon to Input Box

Here is a non-bootstrap solution that keeps your markup simple by embedding the image representation of the glyphicon directly in the CSS using base64 URI encoding.

_x000D_
_x000D_
input {_x000D_
  border:solid 1px #ddd;_x000D_
}_x000D_
input.search {_x000D_
 padding-left:20px;_x000D_
 background-repeat: no-repeat;_x000D_
 background-position-y: 1px;_x000D_
 background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAASCAYAAABb0P4QAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADbSURBVDhP5ZI9C4MwEIb7//+BEDgICA6C4OQgBJy6dRIEB6EgCNkEJ4e3iT2oHzH9wHbpAwfyJvfkJDnhYH4kHDVKlSAigSAQoCiBKjVGXvaxFXZnxBQYkSlBICII+22K4jM63rbHSthCSdsskVX9Y6KxR5XJSSpVy6GbpbBKp6aw0BzM0ShCe1iKihMXC6EuQtMQwukzPFu3fFd4+C+/cimUNxy6WQkNnmdzL3NYPfDmLVuhZf2wZYz80qDkKX1St3CXAfVMqq4cz3hTaGEpmctxDPmB0M/fCYEbAwZYyVKYcroAAAAASUVORK5CYII=);_x000D_
}
_x000D_
<input class="search">
_x000D_
_x000D_
_x000D_

How to Correctly Check if a Process is running and Stop it

If you don't need to display exact result "running" / "not runnuning", you could simply:

ps notepad -ErrorAction SilentlyContinue | kill -PassThru

If the process was not running, you'll get no results. If it was running, you'll receive get-process output, and the process will be stopped.

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Issue with adding common code as git submodule: "already exists in the index"

if there exists a folder named x under git control, you want add a same name submodule , you should delete folder x and commit it first.

Updated by @ujjwal-singh:

Committing is not needed, staging suffices.. git add / git rm -r

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

I had same issue got it fixed. Use below steps to resolve issue in Xcode 6.4.

  1. Click on Show project navigator in Navigator window
  2. Now Select project immediately below navigator window
  3. Select Targets
  4. Select Build Phases tab
  5. Open Run Script drop-down option
  6. Select Run script only when installing checkbox

Screenshot for steps

Now, clean your project (cmd+shift+k) and build your project.

Check if a given key already exists in a dictionary

What about using EAFP (easier to ask forgiveness than permission):

try:
   blah = dict["mykey"]
   # key exists in dict
except KeyError:
   # key doesn't exist in dict

See other SO posts:

Using try vs if in python or

Checking for member existence in Python

Entity Framework select distinct name

use Select().Distinct()

for example

DBContext db = new DBContext();
var data= db.User_Food_UserIntakeFood .Select( ).Distinct();

URL to load resources from the classpath in Java

If you have tomcat on the classpath, it's as simple as:

TomcatURLStreamHandlerFactory.register();

This will register handlers for "war" and "classpath" protocols.

Recommended date format for REST GET API

REST doesn't have a recommended date format. Really it boils down to what works best for your end user and your system. Personally, I would want to stick to a standard like you have for ISO 8601 (url encoded).

If not having ugly URI is a concern (e.g. not including the url encoded version of :, -, in you URI) and (human) addressability is not as important, you could also consider epoch time (e.g. http://example.com/start/1331162374). The URL looks a little cleaner, but you certainly lose readability.

The /2012/03/07 is another format you see a lot. You could expand upon that I suppose. If you go this route, just make sure you're either always in GMT time (and make that clear in your documentation) or you might also want to include some sort of timezone indicator.

Ultimately it boils down to what works for your API and your end user. Your API should work for you, not you for it ;-).

For-loop vs while loop in R

And about timing:

fn1 <- function (N) {
    for(i in as.numeric(1:N)) { y <- i*i }
}
fn2 <- function (N) {
    i=1
    while (i <= N) {
        y <- i*i
        i <- i + 1
    }
}

system.time(fn1(60000))
# user  system elapsed 
# 0.06    0.00    0.07 
system.time(fn2(60000))
# user  system elapsed 
# 0.12    0.00    0.13

And now we know that for-loop is faster than while-loop. You cannot ignore warnings during timing.

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

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

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

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

Nested or Inner Class in PHP

Real nested classes with public/protected/private accessibility were proposed in 2013 for PHP 5.6 as an RFC but did not make it (No voting yet, no update since 2013 - as of 2021/02/03):

https://wiki.php.net/rfc/nested_classes

class foo {
    public class bar {
 
    }
}

At least, anonymous classes made it into PHP 7

https://wiki.php.net/rfc/anonymous_classes

From this RFC page:

Future Scope

The changes made by this patch mean named nested classes are easier to implement (by a tiny bit).

So, we might get nested classes in some future version, but it's not decided yet.

Get current location of user in Android without using GPS or internet

By getting the getLastKnownLocation you do not actually initiate a fix yourself.

Be aware that this could start the provider, but if the user has ever gotten a location before, I don't think it will. The docs aren't really too clear on this.

According to the docs getLastKnownLocation:

Returns a Location indicating the data from the last known location fix obtained from the given provider. This can be done without starting the provider.

Here is a quick snippet:

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import java.util.List;

public class UtilLocation {
    public static Location getLastKnownLoaction(boolean enabledProvidersOnly, Context context){
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location utilLocation = null;
        List<String> providers = manager.getProviders(enabledProvidersOnly);
        for(String provider : providers){

            utilLocation = manager.getLastKnownLocation(provider);
            if(utilLocation != null) return utilLocation;
        }
        return null;
    }
}

You also have to add new permission to AndroidManifest.xml

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

How can I check whether a radio button is selected with JavaScript?

if(document.querySelectorAll('input[type="radio"][name="name_of_radio"]:checked').length < 1)

Convert a 1D array to a 2D array in numpy

You can useflatten() from the numpy package.

import numpy as np
a = np.array([[1, 2],
       [3, 4],
       [5, 6]])
a_flat = a.flatten()
print(f"original array: {a} \nflattened array = {a_flat}")

Output:

original array: [[1 2]
 [3 4]
 [5 6]] 
flattened array = [1 2 3 4 5 6]

how to permit an array with strong parameters

This https://github.com/rails/strong_parameters seems like the relevant section of the docs:

The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.

To declare that the value in params must be an array of permitted scalar values map the key to an empty array:

params.permit(:id => [])

In my app, the category_ids are passed to the create action in an array

"category_ids"=>["", "2"],

Therefore, when declaring strong parameters, I explicitly set category_ids to be an array

params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids => [])

Works perfectly now!

(IMPORTANT: As @Lenart notes in the comments, the array declarations must be at the end of the attributes list, otherwise you'll get a syntax error.)

Changing background color of selected cell?

// animate between regular and selected state
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    if (selected) {
        self.backgroundColor = [UIColor colorWithRed:234.0f/255 green:202.0f/255 blue:255.0f/255 alpha:1.0f];
    }
    else {
        self.backgroundColor = [UIColor clearColor];
    }
}

Save the plots into a PDF

Never mind got the way to do it.

def plotGraph(X,Y):
     fignum = random.randint(0,sys.maxint)
     fig = plt.figure(fignum)
     ### Plotting arrangements ###
     return fig

------ plotting module ------

----- mainModule ----

 import matplotlib.pyplot as plt
 ### tempDLStats, tempDLlabels are the argument
 plot1 = plotGraph(tempDLstats, tempDLlabels)
 plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
 plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
 plt.show()
 plot1.savefig('plot1.png')
 plot2.savefig('plot2.png')
 plot3.savefig('plot3.png')

----- mainModule -----

How to obtain the number of CPUs/cores in Linux from the command line?

It is very simple. Just use this command:

lscpu