Programs & Examples On #Mediawiki api

The MediaWiki API is the interface for automated editing processes ("bots") and other programs to access data in a MediaWiki wiki.

Is there a Wikipedia API?

If you want to extract structured data from Wikipedia, you may consider using DbPedia http://dbpedia.org/

It provides means to query data using given criteria using SPARQL and returns data from parsed Wikipedia infobox templates

Here is a quick example how it could be done in .NET http://www.kozlenko.info/blog/2010/07/20/executing-sparql-query-on-wikipedia-in-net/

There are some SPARQL libraries available for multiple platforms to make queries easier

MySQL: selecting rows where a column is null

SQL NULL's special, and you have to do WHERE field IS NULL, as NULL cannot be equal to anything,

including itself (ie: NULL = NULL is always false).

See Rule 3 https://en.wikipedia.org/wiki/Codd%27s_12_rules

Prompt for user input in PowerShell

Read-Host is a simple option for getting string input from a user.

$name = Read-Host 'What is your username?'

To hide passwords you can use:

$pass = Read-Host 'What is your password?' -AsSecureString

To convert the password to plain text:

[Runtime.InteropServices.Marshal]::PtrToStringAuto(
    [Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))

As for the type returned by $host.UI.Prompt(), if you run the code at the link posted in @Christian's comment, you can find out the return type by piping it to Get-Member (for example, $results | gm). The result is a Dictionary where the key is the name of a FieldDescription object used in the prompt. To access the result for the first prompt in the linked example you would type: $results['String Field'].

To access information without invoking a method, leave the parentheses off:

PS> $Host.UI.Prompt

MemberType          : Method
OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr
                    ompt(string caption, string message, System.Collections.Ob
                    jectModel.Collection[System.Management.Automation.Host.Fie
                    ldDescription] descriptions)}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : System.Collections.Generic.Dictionary[string,psobject] Pro
                    mpt(string caption, string message, System.Collections.Obj
                    ectModel.Collection[System.Management.Automation.Host.Fiel
                    dDescription] descriptions)
Name                : Prompt
IsInstance          : True

$Host.UI.Prompt.OverloadDefinitions will give you the definition(s) of the method. Each definition displays as <Return Type> <Method Name>(<Parameters>).

Tooltip with HTML content without JavaScript

Pure CSS:

_x000D_
_x000D_
.app-tooltip {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.app-tooltip:before {_x000D_
  content: attr(data-title);_x000D_
  background-color: rgba(97, 97, 97, 0.9);_x000D_
  color: #fff;_x000D_
  font-size: 12px;_x000D_
  padding: 10px;_x000D_
  position: absolute;_x000D_
  bottom: -50px;_x000D_
  opacity: 0;_x000D_
  transition: all 0.4s ease;_x000D_
  font-weight: 500;_x000D_
  z-index: 2;_x000D_
}_x000D_
_x000D_
.app-tooltip:after {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  opacity: 0;_x000D_
  left: 5px;_x000D_
  bottom: -16px;_x000D_
  border-style: solid;_x000D_
  border-width: 0 10px 10px 10px;_x000D_
  border-color: transparent transparent rgba(97, 97, 97, 0.9) transparent;_x000D_
  transition: all 0.4s ease;_x000D_
}_x000D_
_x000D_
.app-tooltip:hover:after,_x000D_
.app-tooltip:hover:before {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div href="#" class="app-tooltip" data-title="Your message here"> Test here</div>
_x000D_
_x000D_
_x000D_

jQuery - find child with a specific class

$(this).find(".bgHeaderH2").html();

or

$(this).find(".bgHeaderH2").text();

How to add minutes to my Date

Work for me DateUtils

//import
import org.apache.commons.lang.time.DateUtils

...

        //Added and removed minutes to increase current range dates
        Date horaInicialCorteEspecial = DateUtils.addMinutes(new Date(corteEspecial.horaInicial.getTime()),-1)
        Date horaFinalCorteEspecial = DateUtils.addMinutes(new Date(corteEspecial.horaFinal.getTime()),1)

WindowsError: [Error 126] The specified module could not be found

if you come across this error when you try running PyTorch related libraries you may have to consider installing PyTorch with CPU only version i.e. if you don't have Nvidia GPU in your system.

Pytorch with CUDA worked in Nvidia installed systems but not in others.

How to copy a dictionary and only edit the copy

the following code, which is on dicts which follows json syntax more than 3 times faster than deepcopy

def CopyDict(dSrc):
    try:
        return json.loads(json.dumps(dSrc))
    except Exception as e:
        Logger.warning("Can't copy dict the preferred way:"+str(dSrc))
        return deepcopy(dSrc)

How to assign bean's property an Enum value in Spring config file?

To be specific, set the value to be the name of a constant of the enum type, e.g., "TYPE1" or "TYPE2" in your case, as shown below. And it will work:

<bean name="someName" class="my.pkg.classes">
   <property name="type" value="TYPE1" />
</bean>

Specifying row names when reading in a file

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1]  ## set rownames
obj <- obj[, -1]           ## remove the first variable

Simplest way to restart service on a remote computer

If you attempting to do this on a server on different domain you will need to a little bit more than what has been suggested by most answers so far, this is what I use to accomplish this:

#Configuration
$servername = "ABC",
$serviceAccountUsername = "XYZ",
$serviceAccountPassword = "XXX"

#Establish connection
try {
    if (-not ([System.IO.Directory]::Exists('\\' + $servername))) {
        net use \\$servername /user:$serviceAccountUsername $serviceAccountPassword
    }
}
catch {
    #May already exists, if so just continue
    Write-Output $_.Exception.Message
}

#Restart Service
sc.exe \\$servername stop "ServiceNameHere"
sc.exe \\$servername start "ServiceNameHere"

How to reset index in a pandas dataframe?

DataFrame.reset_index is what you're looking for. If you don't want it saved as a column, then do:

df = df.reset_index(drop=True)

If you don't want to reassign:

df.reset_index(drop=True, inplace=True)

What is the optimal way to compare dates in Microsoft SQL server?

Here is an example:

I've an Order table with a DateTime field called OrderDate. I want to retrieve all orders where the order date is equals to 01/01/2006. there are next ways to do it:

1) WHERE DateDiff(dd, OrderDate, '01/01/2006') = 0
2) WHERE Convert(varchar(20), OrderDate, 101) = '01/01/2006'
3) WHERE Year(OrderDate) = 2006 AND Month(OrderDate) = 1 and Day(OrderDate)=1
4) WHERE OrderDate LIKE '01/01/2006%'
5) WHERE OrderDate >= '01/01/2006'  AND OrderDate < '01/02/2006'

Is found here

HTML5 Canvas Resize (Downscale) Image High Quality?

Why use the canvas to resize images? Modern browsers all use bicubic interpolation — the same process used by Photoshop (if you're doing it right) — and they do it faster than the canvas process. Just specify the image size you want (use only one dimension, height or width, to resize proportionally).

This is supported by most browsers, including later versions of IE. Earlier versions may require browser-specific CSS.

A simple function (using jQuery) to resize an image would be like this:

function resizeImage(img, percentage) {
    var coeff = percentage/100,
        width = $(img).width(),
        height = $(img).height();

    return {"width": width*coeff, "height": height*coeff}           
}

Then just use the returned value to resize the image in one or both dimensions.

Obviously there are different refinements you could make, but this gets the job done.

Paste the following code into the console of this page and watch what happens to the gravatars:

function resizeImage(img, percentage) {
    var coeff = percentage/100,
        width = $(img).width(),
        height = $(img).height();

    return {"width": width*coeff, "height": height*coeff}           
}

$('.user-gravatar32 img').each(function(){
  var newDimensions = resizeImage( this, 150);
  this.style.width = newDimensions.width + "px";
  this.style.height = newDimensions.height + "px";
});

sprintf like functionality in Python

Take a look at "Literal String Interpolation" https://www.python.org/dev/peps/pep-0498/

I found it through the http://www.malemburg.com/

The name does not exist in the namespace error in XAML

This happened to me already twice in a complex WPF app, in it there are 4 multi platform projects, 1 shared project, 2 support libraries, and 1 test project..

This very specific XAML namespace error happened twice on very recently modified files on the Shared project. In both of my cases, it was a new c# file added with a repeating namespace entry;

Like namespace MyProgram.MyFolder.MyProgram.MyFolder

I double pasted it once by mistake, and once it was due to JetBrains Rider double pasting the namespace. (If you ever rename a project in Rider, it time to time starts double pasting namespaces on new file creations, especially on Shared projects..). These c# files with repeating namespaces were then called in the ViewModels where XAML files were referencing to. Well you then get these unrelated and misleading errors, you can have a problem with one file, all your Xaml files will start erroring out eventually.

Anyways, if you get these kind of errors, it's most of the time an issue on a very newly added file or code change. My suggestions would be to look at your very recent changes.

Hash function that produces short hashes?

It is now 2019 and there are better options. Namely, xxhash.

~ echo test | xxhsum                                                           
2d7f1808da1fa63c  stdin

How do I sum values in a column that match a given condition using pandas?

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8

What is the 'realtime' process priority setting for?

Once Windows learns a program uses higher than normal priority it seems like it limits the priority on the process.

Setting the priority from IDLE to REALTIME does NOT change the CPU usage.

I found on My multi-processor AMD CPU that if I drop one of the CPUs ot like the LAST one the CPU usage will MAX OUT and the last CPU remains idle. The processor speed increases to 75% on my Quad AMD.

Use Task Manager->select process->Right Click on the process->Select->Set Affinity Click all but the last processor. The CPU usage will increase to the MAX on the remaining processors and Frame counts if processing video will increase.

Relationship between hashCode and equals method in Java

According to the doc, the default implementation of hashCode will return some integer that differ for every object

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation
technique is not required by the JavaTM programming language.)

However some time you want the hash code to be the same for different object that have the same meaning. For example

Student s1 = new Student("John", 18);
Student s2 = new Student("John", 18);
s1.hashCode() != s2.hashCode(); // With the default implementation of hashCode

This kind of problem will be occur if you use a hash data structure in the collection framework such as HashTable, HashSet. Especially with collection such as HashSet you will end up having duplicate element and violate the Set contract.

Send file using POST from a Python script

From: https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file

Requests makes it very simple to upload Multipart-encoded files:

with open('report.xls', 'rb') as f:
    r = requests.post('http://httpbin.org/post', files={'report.xls': f})

That's it. I'm not joking - this is one line of code. The file was sent. Let's check:

>>> r.text
{
  "origin": "179.13.100.4",
  "files": {
    "report.xls": "<censored...binary...data>"
  },
  "form": {},
  "url": "http://httpbin.org/post",
  "args": {},
  "headers": {
    "Content-Length": "3196",
    "Accept-Encoding": "identity, deflate, compress, gzip",
    "Accept": "*/*",
    "User-Agent": "python-requests/0.8.0",
    "Host": "httpbin.org:80",
    "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"
  },
  "data": ""
}

How to discard local commits in Git?

You need to run

git fetch

To get all changes and then you will not receive message with "your branch is ahead".

Adding placeholder text to textbox

Attached properties to the rescue:

public static class TextboxExtensions
{
    public static readonly DependencyProperty PlaceholderProperty = 
        DependencyProperty.RegisterAttached(
            "Placeholder", 
            typeof(string), 
            typeof(TextboxExtensions), 
            new PropertyMetadata(default(string), propertyChangedCallback: PlaceholderChanged)
            );

    private static void PlaceholderChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
    {
        var tb = dependencyObject as TextBox;

        if (tb == null)
            return;

        tb.LostFocus -= OnLostFocus;
        tb.GotFocus -= OnGotFocus;

        if (args.NewValue != null)
        {
            tb.GotFocus += OnGotFocus;
            tb.LostFocus += OnLostFocus;
        }

        SetPlaceholder(dependencyObject, args.NewValue as string);

        if (!tb.IsFocused)
            ShowPlaceholder(tb);
    }

    private static void OnLostFocus(object sender, RoutedEventArgs routedEventArgs)
    {
        ShowPlaceholder(sender as TextBox);
    }

    private static void OnGotFocus(object sender, RoutedEventArgs routedEventArgs)
    {
        HidePlaceholder(sender as TextBox);
    }

    [AttachedPropertyBrowsableForType(typeof(TextBox))]
    public static void SetPlaceholder(DependencyObject element, string value)
    {
        element.SetValue(PlaceholderProperty, value);
    }

    [AttachedPropertyBrowsableForType(typeof(TextBox))]
    public static string GetPlaceholder(DependencyObject element)
    {
        return (string)element.GetValue(PlaceholderProperty);
    }

    private static void ShowPlaceholder(TextBox textBox)
    {
        if (string.IsNullOrWhiteSpace(textBox.Text))
        {
            textBox.Text = GetPlaceholder(textBox);
        }
    }

    private static void HidePlaceholder(TextBox textBox)
    {
        string placeholderText = GetPlaceholder(textBox);

        if (textBox.Text == placeholderText)
            textBox.Text = string.Empty;
    }
}

Usage:

<TextBox Text="hi" local:TextboxExtensions.Placeholder="Hello there"></TextBox>

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

For most of the people still receiving the error after fixing project properties, you probably installed Java 7 SDK when setting up your environment, but it is not currently supported for Android development.

As the error message sais, you should have installed Java 5.0 or 6.0, but Java 7 was found.

If you fix project properties without first installing Java 5 or 6, you will see the same error again.

  • So first, ensure you have Java SDK 5 or 6 installed, or install it.
  • Check your environment variable (JAVA_HOME) is pointing to SDK 5/6.

And then:

  • Check that Eclipse is using SDK 5/6 by default (Window => Prefs. => Java => Compiler
  • Disable Project Specific Settings (Project Properties => Java Compiler)
  • Fix Project Properties

OR

  • Leave Eclipse using JDK 7 by default.
  • Enable Project Specific Settings (Project Properties => Java Compiler)
  • Select Compiler Compliance 1.5 or 1.6 (Project Properties => Java Compiler)

curl: (6) Could not resolve host: application

I replaced all the single quotes ['] to double quotes ["] and then it worked perfectly. Thanks for the input by @LogicalKip.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

Upload the file Microsoft.ReportViewer.WebForms.dll to your bin directory of your web applicaion.

You can find this dll file in the bin directory of your local web application.

Spring MVC - How to get all request params in a map in Spring controller?

While the other answers are correct it certainly is not the "Spring way" to use the HttpServletRequest object directly. The answer is actually quite simple and what you would expect if you're familiar with Spring MVC.

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
@RequestParam Map<String,String> allRequestParams, ModelMap model) {
   return "viewName";
}

How to hide a div with jQuery?

$("myDiv").hide(); and $("myDiv").show(); does not work in Internet Explorer that well.

The way I got around this was to get the html content of myDiv using .html().

I then wrote it to a newly created DIV. I then appended the DIV to the body and appended the content of the variable Content to the HiddenField then read that contents from the newly created div when I wanted to show the DIV.

After I used the .remove() method to get rid of the DIV that was temporarily holding my DIVs html.

var Content = $('myDiv').html(); 
        $('myDiv').empty();
        var hiddenField = $("<input type='hidden' id='myDiv2'>");
        $('body').append(hiddenField);
        HiddenField.val(Content);

and then when I wanted to SHOW the content again.

        var Content = $('myDiv');
        Content.html($('#myDiv2').val());
        $('#myDiv2').remove();

This was more reliable that the .hide() & .show() methods.

How to clear form after submit in Angular 2?

Hm, now (23 Jan 2017 with angular 2.4.3) I made it work like this:

newHero() {
    return this.model = new Hero(42, 'APPLIED VALUE', '');
}
<button type="button" class="btn btn-default" (click)="heroForm.resetForm(newHero())">New Hero</button>

CSS: image link, change on hover

You could do the following, without needing CSS...

<a href="ENTER_DESTINATION_URL"><img src="URL_OF_FIRST_IMAGE_SOURCE" onmouseover="this.src='URL_OF_SECOND_IMAGE_SOURCE'" onmouseout="this.src='URL_OF_FIRST_IMAGE_SOURCE_AGAIN'" /></a>

Example: https://jsfiddle.net/jord8on/k1zsfqyk/

This solution was PERFECT for my needs! I found this solution here.

Disclaimer: Having a solution that is possible without CSS is important to me because I design content on the Jive-x cloud community platform which does not give us access to global CSS.

Use jQuery to change a second select list based on the first select list option

_x000D_
_x000D_
$("#select1").change(function() {_x000D_
  if ($(this).data('options') === undefined) {_x000D_
    /*Taking an array of all options-2 and kind of embedding it on the select1*/_x000D_
    $(this).data('options', $('#select2 option').clone());_x000D_
  }_x000D_
  var id = $(this).val();_x000D_
  var options = $(this).data('options').filter('[value=' + id + ']');_x000D_
  $('#select2').html(options);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<select name="select1" id="select1">_x000D_
  <option value="1">Fruit</option>_x000D_
  <option value="2">Animal</option>_x000D_
  <option value="3">Bird</option>_x000D_
  <option value="4">Car</option>_x000D_
</select>_x000D_
_x000D_
_x000D_
<select name="select2" id="select2">_x000D_
  <option value="1">Banana</option>_x000D_
  <option value="1">Apple</option>_x000D_
  <option value="1">Orange</option>_x000D_
  <option value="2">Wolf</option>_x000D_
  <option value="2">Fox</option>_x000D_
  <option value="2">Bear</option>_x000D_
  <option value="3">Eagle</option>_x000D_
  <option value="3">Hawk</option>_x000D_
  <option value="4">BWM<option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Using jQuery data() to store data

I guess hiding elements doesn't work cross-browser(2012), I have'nt tested it myself.

Comparing two input values in a form validation with AngularJS

I need to do this just in one form in my entire application and i see a directive like a super complicate for my case, so i use the ng-patter like some has point, but have some problems, when the string has special characters like .[\ this broke, so i create a function for scape special characters.

$scope.escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

and in the view

<form name="ExampleForm">
  <label>Password</label>
  <input ng-model="password" required />
  <br>
   <label>Confirm password</label>
  <input ng-model="confirmPassword" required ng-pattern="escapeRegExp(password)"/>  
</form>

Disable submit button ONLY after submit

As a number of people have pointed out, disabling the submit button has some negative side effects (at least in Chrome it prevents the name/value of the button pressed from being submitted). My solution was to simply add an attribute to indicate that submit has been requested, and then check for the presence of this attribute on every submit. Because I'm using the submit function, this is only called after all HTML 5 validation is successful. Here is my code:

  $("form.myform").submit(function (e) {
    // Check if we have submitted before
    if ( $("#submit-btn").attr('attempted') == 'true' ) {
      //stop submitting the form because we have already clicked submit.
      e.preventDefault();
    }
    else {
      $("#submit-btn").attr("attempted", 'true');
    }
  });

How to rename with prefix/suffix?

In Bash and zsh you can do this with Brace Expansion. This simply expands a list of items in braces. For example:

# echo {vanilla,chocolate,strawberry}-ice-cream
vanilla-ice-cream chocolate-ice-cream strawberry-ice-cream

So you can do your rename as follows:

mv {,new.}original.filename

as this expands to:

mv original.filename new.original.filename

Flutter: Setting the height of the AppBar

At the time of writing this, I was not aware of PreferredSize. Cinn's answer is better to achieve this.

You can create your own custom widget with a custom height:

import "package:flutter/material.dart";

class Page extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Column(children : <Widget>[new CustomAppBar("Custom App Bar"), new Container()],);
  }
}


class CustomAppBar extends StatelessWidget {

  final String title;
  final double barHeight = 50.0; // change this for different heights 

  CustomAppBar(this.title);

  @override
  Widget build(BuildContext context) {
    final double statusbarHeight = MediaQuery
        .of(context)
        .padding
        .top;

    return new Container(
      padding: new EdgeInsets.only(top: statusbarHeight),
      height: statusbarHeight + barHeight,
      child: new Center(
        child: new Text(
          title,
          style: new TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
}

Summing elements in a list

You can sum numbers in a list simply with the sum() built-in:

sum(your_list)

It will sum as many number items as you have. Example:

my_list = range(10, 17)
my_list
[10, 11, 12, 13, 14, 15, 16]

sum(my_list)
91

For your specific case:

For your data convert the numbers into int first and then sum the numbers:

data = ['5', '4', '9']

sum(int(i) for i in data)
18

This will work for undefined number of elements in your list (as long as they are "numbers")

Thanks for @senderle's comment re conversion in case the data is in string format.

How do I dynamically set HTML5 data- attributes using react?

Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.

2 options

Don't use camel case

<Option data-img-src='value' ... />

And then in the component, because of the dashes, you need to refer to the prop in quotes.

// @flow
class Option extends React.Component {

  props: {
    'data-img-src': string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props['data-img-src']} >...</option>
    )
  }
}

Or use camel case

<Option dataImgSrc='value' ... />

And then in the component, you need to convert.

// @flow
class Option extends React.Component {

  props: {
    dataImgSrc: string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props.dataImgSrc} >...</option>
    )
  }
}

Mainly just realize data- attributes and aria- attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.

What exactly is a Context in Java?

Simply saying, Java context means Java native methods all together.

In next Java code two lines of code needs context: // (1) and // (2)

import java.io.*;

public class Runner{
    public static void main(String[] args) throws IOException { // (1)           
        File file = new File("D:/text.txt");
        String text = "";
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        while ((line = reader.readLine()) != null){ // (2)
            text += line;
        }
        System.out.println(text);
    }
}

(1) needs context because is invoked by Java native method private native void java.lang.Thread.start0();

(2) reader.readLine() needs context because invokes Java native method public static native void java.lang.System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length);

PS.

That is what BalusC is sayed about pattern Facade more strictly.

font-family is inherit. How to find out the font-family in chrome developer pane?

The inherit value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.

The font-family property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.

If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family set to inherit or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.

This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.

Is there a "goto" statement in bash?

There is no goto in bash.

Here is some dirty workaround using trap which jumps only backwards:)

#!/bin/bash -e
trap '
echo I am
sleep 1
echo here now.
' EXIT

echo foo
goto trap 2> /dev/null
echo bar

Output:

$ ./test.sh 
foo
I am
here now.

This shouldn't be used in that way, but only for educational purposes. Here is why this works:

trap is using exception handling to achieve the change in code flow. In this case the trap is catching anything that causes the script to EXIT. The command goto doesn't exist, and hence throws an error, which would ordinarily exit the script. This error is being caught with trap, and the 2>/dev/null hides the error message that would ordinarily be displayed.

This implementation of goto is obviously not reliable, since any non-existent command (or any other error, for that manner), would execute the same trap command. In particular, you cannot choose which label to go-to.


Basically in real scenario you don't need any goto statements, they're redundant as random calls to different places only make your code difficult to understand.

If your code is invoked many times, then consider to use loop and changing its workflow to use continue and break.

If your code repeats it-self, consider writing the function and calling it as many times as you want.

If your code needs to jump into specific section based on the variable value, then consider using case statement.

If you can separate your long code into smaller pieces, consider moving it into separate files and call them from the parent script.

Create a directory if it doesn't exist

Use CreateDirectory (char *DirName, SECURITY_ATTRIBUTES Attribs);

If the function succeeds it returns non-zero otherwise NULL.

Convert a Unicode string to an escaped ASCII string

A small patch to @Adam Sills's answer which solves FormatException on cases where the input string like "c:\u00ab\otherdirectory\" plus RegexOptions.Compiled makes the Regex compilation much faster:

    private static Regex DECODING_REGEX = new Regex(@"\\u(?<Value>[a-fA-F0-9]{4})", RegexOptions.Compiled);
    private const string PLACEHOLDER = @"#!#";
    public static string DecodeEncodedNonAsciiCharacters(this string value)
    {
        return DECODING_REGEX.Replace(
            value.Replace(@"\\", PLACEHOLDER),
            m => { 
                return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString(); })
            .Replace(PLACEHOLDER, @"\\");
    }

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

How does one check if a table exists in an Android SQLite database?

You mentioned that you've created an class that extends SQLiteOpenHelper and implemented the onCreate method. Are you making sure that you're performing all your database acquire calls with that class? You should only be getting SQLiteDatabase objects via the SQLiteOpenHelper#getWritableDatabase and getReadableDatabase otherwise the onCreate method will not be called when necessary. If you are doing that already check and see if th SQLiteOpenHelper#onUpgrade method is being called instead. If so, then the database version number was changed at some point in time but the table was never created properly when that happened.

As an aside, you can force the recreation of the database by making sure all connections to it are closed and calling Context#deleteDatabase and then using the SQLiteOpenHelper to give you a new db object.

Target WSGI script cannot be loaded as Python module

Adding on to the list this is how I got it working.

I was trying to install CKAN 2.7.2 on CentOS 7 from source and kept coming up against this error. For me it was because SELinux was enabled. I didn't need to disable it. Instead, after reading https://www.endpoint.com/blog/2010/10/13/selinux-httpd-modwsgi-26-rhel-centos-5, I found that turning on httpd_can_network_connect fixed it:

setsebool -P httpd_can_network_connect on

From that page:

httpd_can_network_connect - Allows httpd to make network connections, including the local ones you'll be making to a database

How can I append a string to an existing field in MySQL?

Update image field to add full URL, ignoring null fields:

UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;

How to launch PowerShell (not a script) from the command line

The color and window sizing are defined by the shortcut LNK file. I think I found a way that will do what you need, try this:

explorer.exe "Windows PowerShell.lnk"

The LNK file is in the all user start menu which is located in different places depending whether your on XP or Windows 7. In 7 the LNK file is here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell

Can we write our own iterator in Java?

Here is the complete answer to the question.

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

class ListIterator implements Iterator<String>{
    List<String> list;
    int pos = 0;

    public ListIterator(List<String> list) {
        this.list = list;
    }

    @Override
    public boolean hasNext() {
        while(pos < list.size()){
            if (list.get(pos).startsWith("a"))
                return true;
            pos++;
        }
        return false;

    }

    @Override
    public String next() {
        if (hasNext())
            return list.get(pos++);
        throw new NoSuchElementException();
    }
}

public class IteratorTest {

    public static void main(String[] args) {
        List<String> list = Arrays.asList("alice", "bob", "abigail", "charlie");
        ListIterator itr = new ListIterator(list);

        while(itr.hasNext())
            System.out.println(itr.next()); // prints alice, abigail
    }
}
  • ListIterator is the iterator for the array which returns the elements that start with 'a'.
  • There is no need for implementing an Iterable interface. But that is a possibility.
  • There is no need to implement this generically.
  • It fully satisfies the contract for hasNext() and next(). ie if hasNext() says there are still elements, next() will return those elements. And if hasNext() says no more elements, it returns a valid NoSuchElementException exception.

When to use IMG vs. CSS background-image?

Using a background image, you need to absolutely specify the dimensions. This can be a significant problem if you don't actually know them in advance or cannot determine them.

A big problem with <img /> is overlays. What if I want an CSS inner shadow on my image (box-shadow:inset 0 0 5px rgb(0,0,0,.5))? In this case, since <img /> can't have child elements, you need to use positioning and add empty elements which equates to useless markup.

In conclusion, it's quite situational.

modal View controllers - how to display and dismiss

I have solved the issue by using UINavigationController when presenting. In MainVC, when presenting VC1

let vc1 = VC1()
let navigationVC = UINavigationController(rootViewController: vc1)
self.present(navigationVC, animated: true, completion: nil)

In VC1, when I would like to show VC2 and dismiss VC1 in same time (just one animation), I can have a push animation by

let vc2 = VC2()
self.navigationController?.setViewControllers([vc2], animated: true)

And in VC2, when close the view controller, as usual we can use:

self.dismiss(animated: true, completion: nil)

Barcode scanner for mobile phone for Website in form

We have an app in Google Play and the App Store that will scan barcodes into a web site. The app is called Scan to Web. http://berrywing.com/scantoweb.html

You can even embed a link or button to start the scanner yourself within your web page.

<a href="bwstw://startscanner">Link to start scanner</a>

The developer documentation website for the app covers how to use the app and use JavaScript for processing the barcode scan. http://berrywing.com/scantoweb/#htmlscanbutton

Globally catch exceptions in a WPF application?

Use the Application.DispatcherUnhandledException Event. See this question for a summary (see Drew Noakes' answer).

Be aware that there'll be still exceptions which preclude a successful resuming of your application, like after a stack overflow, exhausted memory, or lost network connectivity while you're trying to save to the database.

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

One of my variables was categorical with one alternative being multi string ("no event"). When I used read.table, it assumed that the space after the first string meant the end of the data point and the second string was pushed to the next variable. I used sep= "\t" to solve the problem. I was using RStudio in a Mac OX environment. A previous solution was to transform .txt files to .csv in Excel, and afterwards open them with read.csv function.

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had a similar problem with 'org.codehaus.mojo'-'jaxws-maven-plugin': could not resolve dependencies. Fortunately, I was able to do a Project > Clean in Eclipse, which resolved the issue.

How to check if character is a letter in Javascript?

I made a function to do this:

var isLetter = function (character) {
  if( (character.charCodeAt() >= 65 && character.charCodeAt() <= 90) || (character.charCodeAt() >= 97 && character.charCodeAt() <= 122) ) {
    return true;
  }
  else{
    return false;
  }
}

This basically verifies in the ASCII table if the code of the character refers to a Letter.

You can see the ASCII table on this link and compare columns DEC (where is the code) and symbol: https://www.ascii-code.com/

Note: My function is true only to "simple" letters (things like "Á", "é", "ç", "Ü" it will return false... but if you needed you can adapt this function to de other conditions).

How to capture a list of specific type with mockito

I had the same issue with testing activity in my Android app. I used ActivityInstrumentationTestCase2 and MockitoAnnotations.initMocks(this); didn't work. I solved this issue with another class with respectively field. For example:

class CaptorHolder {

        @Captor
        ArgumentCaptor<Callback<AuthResponse>> captor;

        public CaptorHolder() {
            MockitoAnnotations.initMocks(this);
        }
    }

Then, in activity test method:

HubstaffService hubstaffService = mock(HubstaffService.class);
fragment.setHubstaffService(hubstaffService);

CaptorHolder captorHolder = new CaptorHolder();
ArgumentCaptor<Callback<AuthResponse>> captor = captorHolder.captor;

onView(withId(R.id.signInBtn))
        .perform(click());

verify(hubstaffService).authorize(anyString(), anyString(), captor.capture());
Callback<AuthResponse> callback = captor.getValue();

ORDER BY the IN value list

Another way to do it in Postgres would be to use the idx function.

SELECT *
FROM comments
ORDER BY idx(array[1,3,2,4], comments.id)

Don't forget to create the idx function first, as described here: http://wiki.postgresql.org/wiki/Array_Index

Right align text in android TextView

Below works for me:

<TextView
    android:id="@+id/tv_username"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Sarah" />

<TextView
    android:id="@+id/tv_distance"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/tv_username"
    android:layout_alignParentEnd="true"
    android:layout_toEndOf="@+id/tv_username"
    android:text="San Marco"
    android:textAlignment="viewEnd" />

Please note the android:layout_alignParentEnd and android:textAlignment settings of the second TextView.

Unable to install pyodbc on Linux

In my case (Amazon Linux AMI) none of the above worked. The following worked (idea from here):

  • Find the path to the file cc1plus. For me it was in /usr/libexec/gcc/x86_64-amazon-linux/4.8.5/cc1plus. For you it may vary a bit. Try ls -l /usr/libexec/gcc to find the proper directory name and go ahead.
  • Find directories in your path: echo $PATH (for me it was /sbin:/bin:/usr/sbin:/usr/bin:/opt/aws/bin)
  • Put a link to cc1plus in one of the directories in your PATH: sudo ln -s /PATH/TO/cc1plus /DIRinPATH/
    For example in my case:
    sudo ln -s /usr/libexec/gcc/x86_64-amazon-linux/4.8.5/cc1plus /usr/bin/

SQL Server insert if not exists best practice

You will need to join the tables together and get a list of unique competitors that don't already exist in Competitors.

This will insert unique records.

INSERT Competitors (cName) 
SELECT DISTINCT Name
FROM CompResults cr LEFT JOIN Competitors c ON cr.Name = c.cName
WHERE c.Name IS NULL

There may come a time when this insert needs to be done quickly without being able to wait for the selection of unique names. In that case, you could insert the unique names into a temporary table, and then use that temporary table to insert into your real table. This works well because all the processing happens at the time you are inserting into a temporary table, so it doesn't affect your real table. Then when you have all the processing finished, you do a quick insert into the real table. I might even wrap the last part, where you insert into the real table, inside a transaction.

Uri not Absolute exception getting while calling Restful Webservice

For others who landed in this error and it's not 100% related to the OP question, please check that you are passing the value and it is not null in case of spring-boot: @Value annotation.

open the file upload dialogue box onclick the image

<input type="file" id="imgupload" style="display:none"/>
<label for='imgupload'> <button id="OpenImgUpload">Image Upload</button></label>

On click of for= attribute will automatically focus on "file input" and upload dialog box will open

Get a Windows Forms control by name in C#

Use the Control.ControlCollection.Find method.

Try this:

this.Controls.Find()

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

I would prefer (RHEL) - pip download package==version --no-deps --no-binary=:all:

Getting the WordPress Post ID of current post

In some cases, such as when you're outside The Loop, you may need to use get_queried_object_id() instead of get_the_ID().

$postID = get_queried_object_id();

Send a file via HTTP POST with C#

Using .NET 4.5 trying to perform form POST file upload. Tried most of the methods above but to no avail. Found the solution here https://www.c-sharpcorner.com/article/upload-any-file-using-http-post-multipart-form-data

But I am not not keen as I do not understand why we still need to deal with such low level programming in these common usages (should be handled nicely by framework)

mysql query order by multiple items

Sort by picture and then by activity:

SELECT some_cols
FROM `prefix_users`
WHERE (some conditions)
ORDER BY pic_set, last_activity DESC;

How do I specify the JDK for a GlassFish domain?

Adding the actual content from dbf's link in order to keep the solution within stackoverflow.

It turns out that when I first installed Glassfish on my Windows system I had JDK 6 installed, and recently I had to downgrade to JDK 5 to compile some code for another project.

Apparently when Glassfish is installed it hard-codes its reference to your JDK location, so to fix this problem I ended up having to edit a file named asenv.bat. In short, I edited this file:

C:\glassfish\config\asenv.bat:

and I commented out the reference to JDK 6 and added a new reference to JDK 5, like this:

REM set AS_JAVA=C:\Program Files\Java\jdk1.6.0_04\jre/..
set AS_JAVA=C:\Program Files\Java\jdk1.5.0_16

Although the path doesn't appear to be case sensitive, I've spent hours debugging an issue around JMS Destination object not found due to my replacement path's case being incorrect.

Print Currency Number Format in PHP

with the intl extension in PHP 5.3+, you can use the NumberFormatter class:

$amount = '12345.67';

$formatter = new NumberFormatter('en_GB',  NumberFormatter::CURRENCY);
echo 'UK: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;

$formatter = new NumberFormatter('de_DE',  NumberFormatter::CURRENCY);
echo 'DE: ', $formatter->formatCurrency($amount, 'EUR'), PHP_EOL;

which prints :

 UK: €12,345.67
 DE: 12.345,67 €

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

Always use heading tags for headings. The clue is in the name :)

If you don’t want them to be bold, change their style with CSS. For example:

HTML:

<h3 class="list-heading">heading</h3>

<ul> 
    <li>list item </li>
    <li>list item </li>
    <li>list item </li>
</ul>

CSS

.list-heading {
    font-weight: normal;
}

In HTML5, you can associate the heading and the list more clearly by using the <section> element. (<section> doesn’t work properly in IE 8 and earlier without some JavaScript though.)

<section>
    <h1>heading</h1>

    <ul>
        <li>list item </li>
        <li>list item </li>
        <li>list item </li>
    </ul>
</section>

You could do something similar in HTML 4:

<div class="list-with-heading">
    <h3>Heading</h3>

    <ul>
        <li>list item </li>
        <li>list item </li>
        <li>list item </li>
    </ul>
</div>

Then style thus:

.list-with-heading h3 {
    font-weight: normal;
}

Batch file to copy directories recursively

Look into xcopy, which will recursively copy files and subdirectories.

There are examples, 2/3 down the page. Of particular use is:

To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type:

xcopy a: b: /s /e

How do I configure Notepad++ to use spaces instead of tabs?

I have NotePad++ v6.8.3, and it was in Settings ? Preferences ? Tab Settings ? [Default] ? Replace by space:

NotePad++ Preferences

NotePad++ Tab Settings

Postgresql, update if row with some unique value exists, else insert

If INSERTS are rare, I would avoid doing a NOT EXISTS (...) since it emits a SELECT on all updates. Instead, take a look at wildpeaks answer: https://dba.stackexchange.com/questions/5815/how-can-i-insert-if-key-not-exist-with-postgresql

CREATE OR REPLACE FUNCTION upsert_tableName(arg1 type, arg2 type) RETURNS VOID AS $$ 
    DECLARE 
    BEGIN 
        UPDATE tableName SET col1 = value WHERE colX = arg1 and colY = arg2; 
        IF NOT FOUND THEN 
        INSERT INTO tableName values (value, arg1, arg2); 
        END IF; 
    END; 
    $$ LANGUAGE 'plpgsql'; 

This way Postgres will initially try to do a UPDATE. If no rows was affected, it will fall back to emitting an INSERT.

How to filter (key, value) with ng-repeat in AngularJs?

Or simply use

ng-show="v.hasOwnProperty('secId')"

See updated solution here:

http://jsfiddle.net/RFontana/WA2BE/93/

WhatsApp API (java/python)

This is the developers page of the Open WhatsApp official page: http://openwhatsapp.org/develop/

You can find a lot of information there about Yowsup.

Or, you can just go the the library's link (which I copied from the Open WhatsApp page anyway): https://github.com/tgalal/yowsup

Enjoy!

PHP get dropdown value and text

Is there a reason you didn't just use this?

<select id="animal" name="animal">                      
  <option value="0">--Select Animal--</option>
  <option value="Cat">Cat</option>
  <option value="Dog">Dog</option>
  <option value="Cow">Cow</option>
</select>

if($_POST['submit'] && $_POST['submit'] != 0)
{
   $animal=$_POST['animal'];
}

How do you dynamically add elements to a ListView on Android?

First, you have to add a ListView, an EditText and a button into your activity_main.xml.

Now, in your ActivityMain:

private EditText editTxt;
private Button btn;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;

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

    editTxt = (EditText) findViewById(R.id.editText);
    btn = (Button) findViewById(R.id.button);
    list = (ListView) findViewById(R.id.listView);
    arrayList = new ArrayList<String>();

    // Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
    // and the array that contains the data
    adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);

    // Here, you set the data in your ListView
    list.setAdapter(adapter);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // this line adds the data of your EditText and puts in your array
            arrayList.add(editTxt.getText().toString());
            // next thing you have to do is check if your adapter has changed
            adapter.notifyDataSetChanged();
        }
    });
}

This works for me, I hope I helped you

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

Comparing two hashmaps for equal values and same key sets?

Simply use :

mapA.equals(mapB);

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings

Check that an email address is valid on iOS

Good cocoa function:

-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
   BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
   NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
   NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
   NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
   NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
   return [emailTest evaluateWithObject:checkString];
}

Discussion on Lax vs. Strict - http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/

And because categories are just better, you could also add an interface:

@interface NSString (emailValidation) 
  - (BOOL)isValidEmail;
@end

Implement

@implementation NSString (emailValidation)
-(BOOL)isValidEmail
{
  BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
  NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
  NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
  NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  return [emailTest evaluateWithObject:self];
}
@end

And then utilize:

if([@"[email protected]" isValidEmail]) { /* True */ }
if([@"InvalidEmail@notreallyemailbecausenosuffix" isValidEmail]) { /* False */ }

Get average color of image via Javascript

All-In-One Solution

I would personally combine Color Thief along with this modified version of Name that Color to obtain a more-than-sufficient array of dominant color results for images.

Example:

Consider the following image:

enter image description here

You can use the following code to extract image data relating to the dominant color:

let color_thief = new ColorThief();
let sample_image = new Image();

sample_image.onload = () => {
  let result = ntc.name('#' + color_thief.getColor(sample_image).map(x => {
    const hex = x.toString(16);
    return hex.length === 1 ? '0' + hex : hex;
    
  }).join(''));
  
  console.log(result[0]); // #f0c420     : Dominant HEX/RGB value of closest match
  console.log(result[1]); // Moon Yellow : Dominant specific color name of closest match
  console.log(result[2]); // #ffff00     : Dominant HEX/RGB value of shade of closest match
  console.log(result[3]); // Yellow      : Dominant color name of shade of closest match
  console.log(result[4]); // false       : True if exact color match
};

sample_image.crossOrigin = 'anonymous';
sample_image.src = document.getElementById('sample-image').src;

How to stop mysqld

To stop MariaDB and MySQL server instance:

sudo mysqladmin shutdown

To start MariaDB and MySQL server instance:

mysqld &

To change data ownership for MariaDB and MySQL server instance:

sudo chown -R 755 /usr/local/mariadb/data

Better way to revert to a previous SVN revision of a file?

If you only want to undo the last checkin, you can use the following

svn merge -r head:prev l3toks.dtx

That way, you don't have to hunt for the current and previous version numbers.

Difference between logical addresses, and physical addresses?

  1. An address generated by the CPU is commonly referred to as a logical address. The set of all logical addresses generated by a program is known as logical address space. Whereas, an address seen by the memory unit- that is, the one loaded into the memory-address register of the memory- is commonly referred to as physical address. The set of all physical addresses corresponding to the logical addresses is known as physical address space.
  2. The compile-time and load-time address-binding methods generate identical logical and physical addresses. However, in the execution-time address-binding scheme, the logical and physical-address spaces differ.
  3. The user program never sees the physical addresses. The program creates a pointer to a logical address, say 346, stores it in memory, manipulate it, compares it to other logical addresses- all as the number 346. Only when a logical address is used as memory address, it is relocated relative to the base/relocation register. The memory-mapping hardware device called the memory- management unit(MMU) converts logical addresses into physical addresses.
  4. Logical addresses range from 0 to max. User program that generates logical address thinks that the process runs in locations 0 to max. Logical addresses must be mapped to physical addresses before they are used. Physical addresses range from (R+0) to (R + max) for a base/relocation register value R.
  5. Example: enter image description here Mapping from logical to physical addresses using memory management unit (MMU) and relocation/base register The value in relocation/base register is added to every logical address generated by a user process, at the time it is sent to memory, to generate corresponding physical address. In the above figure, base/ relocation value is 14000, then an attempt by the user to access the location 346 is mapped to 14346.

How to send HTTP request in java?

Apache HttpComponents. The examples for the two modules - HttpCore and HttpClient will get you started right away.

Not that HttpUrlConnection is a bad choice, HttpComponents will abstract a lot of the tedious coding away. I would recommend this, if you really want to support a lot of HTTP servers/clients with minimum code. By the way, HttpCore could be used for applications (clients or servers) with minimum functionality, whereas HttpClient is to be used for clients that require support for multiple authentication schemes, cookie support etc.

How to use an image for the background in tkinter?

You can use the root.configure(background='your colour') example:- import tkinter root=tkiner.Tk() root.configure(background='pink')

Setting attribute disabled on a SPAN element does not prevent click events

Try this:

$("span").css("pointer-events", "none");

you can enabled those back by

$("span").css("pointer-events", "auto");

Determine when a ViewPager changes pages

Use the ViewPager.onPageChangeListener:

viewPager.addOnPageChangeListener(new OnPageChangeListener() {
    public void onPageScrollStateChanged(int state) {}
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

    public void onPageSelected(int position) {
        // Check if this is the page you want.
    }
});

Hide horizontal scrollbar on an iframe?

This answer is only applicable for websites which use Bootstrap. The responsive embed feature of the Bootstrap takes care of the scrollbars.

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="http://www.youtube.com/embed/WsFWhL4Y84Y"></iframe>
</div> 

jsfiddle: http://jsfiddle.net/00qggsjj/2/

http://getbootstrap.com/components/#responsive-embed

How to import CSV file data into a PostgreSQL table?

In Python, you can use this code for automatic PostgreSQL table creation with column names:

import pandas, csv

from io import StringIO
from sqlalchemy import create_engine

def psql_insert_copy(table, conn, keys, data_iter):
    dbapi_conn = conn.connection
    with dbapi_conn.cursor() as cur:
        s_buf = StringIO()
        writer = csv.writer(s_buf)
        writer.writerows(data_iter)
        s_buf.seek(0)
        columns = ', '.join('"{}"'.format(k) for k in keys)
        if table.schema:
            table_name = '{}.{}'.format(table.schema, table.name)
        else:
            table_name = table.name
        sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(table_name, columns)
        cur.copy_expert(sql=sql, file=s_buf)

engine = create_engine('postgresql://user:password@localhost:5432/my_db')

df = pandas.read_csv("my.csv")
df.to_sql('my_table', engine, schema='my_schema', method=psql_insert_copy)

It's also relatively fast, I can import more than 3.3 million rows in about 4 minutes.

MySQL select all rows from last month until (now() - 1 month), for comparative purposes

My solution was to avoid using NOW() when writing sql with your programming language, and substitute with a string. The problem with NOW() as you indicate is it includes current time. So to capture from the beginning of the query day (0 hour and minute) instead of:

r.date <= DATE_SUB(NOW(), INTERVAL 99 DAY)

I did (php):

$current_sql_date = date('Y-m-d 00:00:00');

in the sql:

$sql_x = "r.date <= DATE_SUB('$current_sql_date', INTERVAL 99 DAY)"

With that, you will be retrieving data from midnight of the given day

Change url query string value using jQuery

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);

How to convert dataframe into time series?

With library fpp, you can easily create time series with date format: time_ser=ts(data,frequency=4,start=c(1954,2))

here we start at the 2nd quarter of 1954 with quarter fequency.

How do I make an http request using cookies on Android?

It turns out that Google Android ships with Apache HttpClient 4.0, and I was able to figure out how to do it using the "Form based logon" example in the HttpClient docs:

https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientFormLogin.java


import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

/**
 * A example that demonstrates how HttpClient APIs can be used to perform
 * form-based logon.
 */
public class ClientFormLogin {

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

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }
        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
                "org=self_registered_users&" +
                "goto=/portal/dt&" +
                "gotoOnFail=/portal/dt?error=true");

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("IDToken1", "username"));
        nvps.add(new BasicNameValuePair("IDToken2", "password"));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        response = httpclient.execute(httpost);
        entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());
        if (entity != null) {
            entity.consumeContent();
        }

        System.out.println("Post logon cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }

        // When HttpClient instance is no longer needed, 
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();        
    }
}

Why can I not push_back a unique_ptr into a vector?

You need to move the unique_ptr:

vec.push_back(std::move(ptr2x));

unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can't make copies of a unique_ptr (because then two unique_ptrs would have ownership), so you can only move it.

Note, however, that your current use of unique_ptr is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:

std::unique_ptr<int> ptr(new int(1));

In C++14 we have an even better way to do so:

make_unique<int>(5);

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

When do I use the PHP constant "PHP_EOL"?

I'd like to throw in an answer that addresses "When not to use it" as it hasn't been covered yet and can imagine it being used blindly and no one noticing the there is a problem till later down the line. Some of this contradicts some of the existing answers somewhat.

If outputting to a webpage in HTML, particularly text in <textarea>, <pre> or <code> you probably always want to use \n and not PHP_EOL.

The reason for this is that while code may work perform well on one sever - which happens to be a Unix-like platform - if deployed on a Windows host (such the Windows Azure platform) then it may alter how pages are displayed in some browsers (specifically Internet Explorer - some versions of which will see both the \n and \r).

I'm not sure if this is still an issue since IE6 or not, so it might be fairly moot but seems worth mentioning if it helps people prompt to think about the context. There might be other cases (such as strict XHTML) where suddently outputting \r's on some platforms could cause problems with the output, and I'm sure there are other edge cases like that.

As noted by someone already, you wouldn't want to use it when returning HTTP headers - as they should always follow the RFC on any platform.

I wouldn't use it for something like delimiters on CSV files (as someone has suggested). The platform the sever is running on shouldn't determine the line endings in generated or consumed files.

Count number of tables in Oracle

REM setting current_schema is required as the 2nd query depends on the current user referred in the session

ALTER SESSION SET CURRENT_SCHEMA=TABLE_OWNER;

SELECT table_name,
         TO_NUMBER (
            EXTRACTVALUE (
               xmltype (
                  DBMS_XMLGEN.getxml ('select count(*) c from ' || table_name)),
               '/ROWSET/ROW/C'))
            COUNT
    FROM dba_tables
   WHERE owner = 'TABLE_OWNER'
ORDER BY COUNT DESC;

How to switch between frames in Selenium WebDriver using Java

to switchto a frame:

driver.switchTo.frame("Frame_ID");

to switch to the default again.

driver.switchTo().defaultContent();

WordPress Get the Page ID outside the loop

I have done it in the following way and it has worked perfectly for me.

First declared a global variable in the header.php, assigning the ID of the post or page before it changes, since the LOOP assigns it the ID of the last entry shown:

$GLOBALS['pageid] = $wp_query->get_queried_object_id();

And to use anywhere in the template, example in the footer.php:

echo $GLOBALS['pageid];

How to get the number of characters in a string

There are several ways to get a string length:

package main

import (
    "bytes"
    "fmt"
    "strings"
    "unicode/utf8"
)

func main() {
    b := "?????"
    len1 := len([]rune(b))
    len2 := bytes.Count([]byte(b), nil) -1
    len3 := strings.Count(b, "") - 1
    len4 := utf8.RuneCountInString(b)
    fmt.Println(len1)
    fmt.Println(len2)
    fmt.Println(len3)
    fmt.Println(len4)

}

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

if you use external libraries in your program and you try to pack all together in a jar file it's not that simple, because of classpath issues etc.

I'd prefer to use OneJar for this issue.

how to convert numeric to nvarchar in sql command

If the culture of the result doesn't matters or we're only talking of integer values, CONVERT or CAST will be fine.

However, if the result must match a specific culture, FORMAT might be the function to go:

DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value)        -->  1505.5698
SELECT FORMAT(@value, 'N2', 'en-us')    --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de')    --> 1.505,57

For more information on FORMAT see here.

Of course, formatting the result should be a matter of the UI layer of the software.

Executing a stored procedure within a stored procedure

Inline Stored procedure we using as per our need. Example like different Same parameter with different values we have to use in queries..

Create Proc SP1
(
 @ID int,
 @Name varchar(40)
 -- etc parameter list, If you don't have any parameter then no need to pass.
 )

  AS
  BEGIN

  -- Here we have some opereations

 -- If there is any Error Before Executing SP2 then SP will stop executing.

  Exec SP2 @ID,@Name,@SomeID OUTPUT 

 -- ,etc some other parameter also we can use OutPut parameters like 

 -- @SomeID is useful for some other operations for condition checking insertion etc.

 -- If you have any Error in you SP2 then also it will stop executing.

 -- If you want to do any other operation after executing SP2 that we can do here.

END

Check if a string has white space

You can simply use the indexOf method on the input string:

function hasWhiteSpace(s) {
  return s.indexOf(' ') >= 0;
}

Or you can use the test method, on a simple RegEx:

function hasWhiteSpace(s) {
  return /\s/g.test(s);
}

This will also check for other white space characters like Tab.

Htaccess: add/remove trailing slash from URL

This is what I've used for my latest app.

# redirect the main page to landing
##RedirectMatch 302 ^/$ /landing

# remove php ext from url
# https://stackoverflow.com/questions/4026021/remove-php-extension-with-htaccess
RewriteEngine on 

# File exists but has a trailing slash
# https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*)/+$ /$1 [R=302,L,QSA]

# ok. It will still find the file but relative assets won't load
# e.g. page: /landing/  -> assets/js/main.js/main
# that's we have the rules above.
RewriteCond %{REQUEST_FILENAME} !\.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^/?(.*?)/?$ $1.php

Find and extract a number from a string

static string GetdigitFromString(string str)
    {
        char[] refArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        char[] inputArray = str.ToCharArray();
        string ext = string.Empty;
        foreach (char item in inputArray)
        {
            if (refArray.Contains(item))
            {
                ext += item.ToString();
            }
        }
        return ext;
    }

Bootstrap: How do I identify the Bootstrap version?

Open package.json and look under dependencies. You should see:

  "dependencies": {
    ...
    "bootstrap-less": "^3.8.8"
    ...
    }

for angular 5 and over

Java Date - Insert into database

You should be using java.sql.Timestamp instead of java.util.Date. Also using a PreparedStatement will save you worrying about the formatting.

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Getting random numbers in Java

int max = 50;
int min = 1;

1. Using Math.random()

double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);

This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double

Why?

random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.

2. Using Random class in Java.

Random rand = new Random(); 
int value = rand.nextInt(50); 

This will give value from 0 to 49.

For 1 to 50: rand.nextInt((max - min) + 1) + min;

Source of some Java Random awesomeness.

How to download/checkout a project from Google Code in Windows?

If you have a github account and don't want to download software, you can export to github, then download a zip from github.

Casting to string in JavaScript

There are differences, but they are probably not relevant to your question. For example, the toString prototype does not exist on undefined variables, but you can cast undefined to a string using the other two methods:

?var foo;

?var myString1 = String(foo); // "undefined" as a string

var myString2 = foo + ''; // "undefined" as a string

var myString3 = foo.toString(); // throws an exception

http://jsfiddle.net/f8YwA/

Is there a .NET/C# wrapper for SQLite?

I'd definitely go with System.Data.SQLite (as previously mentioned: http://sqlite.phxsoftware.com/)

It is coherent with ADO.NET (System.Data.*), and is compiled into a single DLL. No sqlite3.dll - because the C code of SQLite is embedded within System.Data.SQLite.dll. A bit of managed C++ magic.

How to search contents of multiple pdf files?

If You want to see file names with pdftotext use following command:

find . -name '*.pdf' -exec echo {} \; -exec pdftotext {} - \; | grep "pattern\|pdf" 

CSS/HTML: What is the correct way to make text italic?

Perhaps it has no special meaning and only needs to be rendered in italics to separate it presentationally from the text preceding it.

If it has no special meaning, why does it need to be separated presentationally from the text preceding it? This run of text looks a bit weird, because I’ve italicised it for no reason.

I do take your point though. It’s not uncommon for designers to produce designs that vary visually, without varying meaningfully. I’ve seen this most often with boxes: designers will give us designs including boxes with various combinations of colours, corners, gradients and drop-shadows, with no relation between the styles, and the meaning of the content.

Because these are reasonably complex styles (with associated Internet Explorer issues) re-used in different places, we create classes like box-1, box-2, so that we can re-use the styles.

The specific example of making some text italic is too trivial to worry about though. Best leave minutiae like that for the Semantic Nutters to argue about.

Make an image width 100% of parent div, but not bigger than its own width

I would use the property display: table-cell

Here is the link

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

  • public : it is a access specifier that means it will be accessed by publically.
  • static : it is access modifier that means when the java program is load then it will create the space in memory automatically.
  • void : it is a return type i.e it does not return any value.
  • main() : it is a method or a function name.
  • string args[] : its a command line argument it is a collection of variables in the string format.

Can you issue pull requests from the command line on GitHub?

With the Hub command-line wrapper you can link it to git and then you can do git pull-request

From the man page of hub:

   git pull-request [-f] [TITLE|-i ISSUE|ISSUE-URL] [-b BASE] [-h HEAD]
          Opens a pull request on GitHub for the project that the "origin" remote points to. The default head of the pull request is the current branch. Both base and head of the pull request can be explicitly given in one  of  the  following  formats:  "branch",  "owner:branch",
          "owner/repo:branch". This command will abort operation if it detects that the current topic branch has local commits that are not yet pushed to its upstream branch on the remote. To skip this check, use -f.

          If TITLE is omitted, a text editor will open in which title and body of the pull request can be entered in the same manner as git commit message.

          If instead of normal TITLE an issue number is given with -i, the pull request will be attached to an existing GitHub issue. Alternatively, instead of title you can paste a full URL to an issue on GitHub.

Android WebView not loading URL

In my Case, Adding the below functions to WebViewClient fixed the error. the functions are:onReceivedSslError and Depricated and new api versions of shouldOverrideUrlLoading

        webView.setWebViewClient(new WebViewClient() {

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            Log.i(TAG, "loading: deprecation");
            return  true;
            //return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        @TargetApi(Build.VERSION_CODES.N)
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            Log.i(TAG, "loading: build.VERSION_CODES.N");
            return true;
            //return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(
                WebView view, String url, Bitmap favicon) {
            Log.i(TAG, "page started:"+url);
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, final String url) {

            Log.i(TAG, "page finished:"+url);

        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError er) {
            handler.proceed();
        }

    });

How to convert a private key to an RSA private key?

This may be of some help (do not literally write out the backslashes '\' in the commands, they are meant to indicate that "everything has to be on one line"):

Which Command to Apply When

It seems that all the commands (in grey) take any type of key file (in green) as "in" argument. Which is nice.

Here are the commands again for easier copy-pasting:

openssl rsa                                                -in $FF -out $TF
openssl rsa -aes256                                        -in $FF -out $TF
openssl pkcs8 -topk8 -nocrypt                              -in $FF -out $TF
openssl pkcs8 -topk8 -v2 aes-256-cbc -v2prf hmacWithSHA256 -in $FF -out $TF

and

openssl rsa -check -in $FF
openssl rsa -text  -in $FF

Java 8 - Best way to transform a list: map or foreach?

If using 3rd Pary Libaries is ok cyclops-react defines Lazy extended collections with this functionality built in. For example we could simply write

ListX myListToParse;

ListX myFinalList = myListToParse.filter(elt -> elt != null) .map(elt -> doSomething(elt));

myFinalList is not evaluated until first access (and there after the materialized list is cached and reused).

[Disclosure I am the lead developer of cyclops-react]

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Migrator cannot identify all the functions that need @objc Inferred Objective-C thunks marked as deprecated to help you find them
• Build warnings about deprecated methods
• Console messages when running deprecated thunks

enter image description here

Find everything between two XML tags with RegEx

It is not a good idea to use regex for HTML/XML parsing...

However, if you want to do it anyway, search for regex pattern

<primaryAddress>[\s\S]*?<\/primaryAddress>

and replace it with empty string...

Marker in leaflet, click event

A little late to the party, found this while looking for an example of the marker click event. The undefined error the original poster got is because the onClick function is referred to before it's defined. Swap line 2 and 3 and it should work.

Android replace the current fragment with another fragment

it's very simple how to replace with Fragment.

DataFromDb changeActivity = new DataFromDb();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.changeFrg, changeActivity);
    transaction.commit();

What's the valid way to include an image with no src?

I've found that using:

<img src="file://null">

will not make a request and validates correctly.

The browsers will simply block the access to the local file system.

But there might be an error displayed in console log in Chrome for example:

Not allowed to load local resource: file://null/

What's the difference between display:inline-flex and display:flex?

The Difference between "flex" and "inline-flex"

Short answer:

One is inline and the other basically responds like a block element(but has some of it's own differences).

Longer answer:

Inline-Flex - The inline version of flex allows the element, and it's children, to have flex properties while still remaining in the regular flow of the document/webpage. Basically, you can place two inline flex containers in the same row, if the widths were small enough, without any excess styling to allow them to exist in the same row. This is pretty similar to "inline-block."

Flex - The container and it's children have flex properties but the container reserves the row, as it is taken out of the normal flow of the document. It responds like a block element, in terms of document flow. Two flexbox containers could not exist on the same row without excess styling.

The problem you may be having

Due to the elements you listed in your example, though I am guessing, I think you want to use flex to display the elements listed in an even row-by-row fashion but continue to see the elements side-by-side.

The reason you are likely having issues is because flex and inline-flex have the default "flex-direction" property set to "row." This will display the children side-by side. Changing this property to "column" will allow your elements to stack and reserve space(width) equal to the width of its parent.

Below are some examples to show how flex vs inline-flex works and also a quick demo of how inline vs block elements work...

display: inline-flex; flex-direction: row;

Fiddle

display: flex; flex-direction: row;

Fiddle

display: inline-flex; flex-direction: column;

Fiddle

display: flex; flex-direction: column;

Fiddle

display: inline;

Fiddle

display: block

Fiddle

Also, a great reference doc: A Complete Guide to Flexbox - css tricks

How to cancel a local git commit

Use below command:

$ git reset HEAD~1

After this you also able to view files what revert back like below response.

Unstaged changes after reset:
M   application/config/config.php
M   application/config/database.php

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

Converting camel case to underscore case in ruby

Short oneliner for CamelCases when you have spaces also included (doesn't work correctly if you have a word inbetween with small starting-letter):

a = "Test String"
a.gsub(' ', '').underscore

  => "test_string"

Change image size via parent div

I'm not sure about what you mean by "I have no access to image" But if you have access to parent div you can do the following:

Firs give id or class to your div:

<div class="parent">
   <img src="http://someimage.jpg">
</div>

Than add this to your css:

.parent {
   width: 42px; /* I took the width from your post and placed it in css */
   height: 42px;
}

/* This will style any <img> element in .parent div */
.parent img {
   height: 100%;
   width: 100%;
}

How can I loop over entries in JSON?

Actually, to query the team_name, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.

from urllib2 import urlopen
import json

url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)

for i in json_obj['team']:
    print i['team_name']

Using python's mock patch.object to change the return value of a method called within another method

Let me clarify what you're talking about: you want to test Foo in a testcase, which calls external method uses_some_other_method. Instead of calling the actual method, you want to mock the return value.

class Foo:
    def method_1():
       results = uses_some_other_method()
    def method_n():
       results = uses_some_other_method()

Suppose the above code is in foo.py and uses_some_other_method is defined in module bar.py. Here is the unittest:

import unittest
import mock

from foo import Foo


class TestFoo(unittest.TestCase):

    def setup(self):
        self.foo = Foo()

    @mock.patch('foo.uses_some_other_method')
    def test_method_1(self, mock_method):
        mock_method.return_value = 3
        self.foo.method_1(*args, **kwargs)

        mock_method.assert_called_with(*args, **kwargs)

If you want to change the return value every time you passed in different arguments, mock provides side_effect.

git add remote branch

I tested what @Samy Dindane suggested in the comment on the OP.

I believe it works, try

git fetch <remote_name> <remote_branch>:<local_branch>
git checkout <local_branch>

Here's an example for a fictitious remote repository named foo with a branch named bar where I create a local branch bar tracking the remote:

git fetch foo bar:bar
git checkout bar

How to order events bound with jQuery

just bind handler normally and then run:

element.data('events').action.reverse();

so for example:

$('#mydiv').data('events').click.reverse();

JOptionPane YES/No Options Confirm Dialog Box Issue

You need to look at the return value of the call to showConfirmDialog. I.E.:

int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
  // Saving code here
}

You were testing against dialogButton, which you were using to set the buttons that should be displayed by the dialog, and this variable was never updated - so dialogButton would never have been anything other than JOptionPane.YES_NO_OPTION.

Per the Javadoc for showConfirmDialog:

Returns: an integer indicating the option selected by the user

Convert UTC date time to local date time

Based on @digitalbath answer, here is a small function to grab the UTC timestamp and display the local time in a given DOM element (using jQuery for this last part):

https://jsfiddle.net/moriz/6ktb4sv8/1/

<div id="eventTimestamp" class="timeStamp">
   </div>
   <script type="text/javascript">
   // Convert UTC timestamp to local time and display in specified DOM element
   function convertAndDisplayUTCtime(date,hour,minutes,elementID) {
    var eventDate = new Date(''+date+' '+hour+':'+minutes+':00 UTC');
    eventDate.toString();
    $('#'+elementID).html(eventDate);
   }
   convertAndDisplayUTCtime('06/03/2015',16,32,'eventTimestamp');
   </script>

FileNotFoundException..Classpath resource not found in spring?

I was getting the same problem when running my project. On checking the files structure, I realised that Spring's xml file was inside the project's package and thus couldn't be found. I put it outside the package and it worked just fine.

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.


The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.


Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.

Note:

  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.


Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.


Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

Convert JSON String To C# Object

It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings.

For instance:

  class Test {

      String test; 

      String getTest() { return test; }
      void setTest(String test) { this.test = test; }

  }

Then your deserialization code would be:

   JavaScriptSerializer json_serializer = new JavaScriptSerializer();
   Test routes_list = 
          (Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");

More information can be found in this tutorial: http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx

Correct Way to Load Assembly, Find Class and Call Run() Method

You will need to use reflection to get the type "TestRunner". Use the Assembly.GetType method.

class Program
{
    static void Main(string[] args)
    {
        Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
        Type type = assembly.GetType("TestRunner");
        var obj = (TestRunner)Activator.CreateInstance(type);
        obj.Run();
    }
}

How to have a default option in Angular.js select box

Only one answer by Srivathsa Harish Venkataramana mentioned track by which is indeed a solution for this!

Here is an example along with Plunker (link below) of how to use track by in select ng-options:

<select ng-model="selectedCity"
        ng-options="city as city.name for city in cities track by city.id">
  <option value="">-- Select City --</option>
</select>

If selectedCity is defined on angular scope, and it has id property with the same value as any id of any city on the cities list, it'll be auto selected on load.

Here is Plunker for this: http://plnkr.co/edit/1EVs7R20pCffewrG0EmI?p=preview

See source documentation for more details: https://code.angularjs.org/1.3.15/docs/api/ng/directive/select

How to import jquery using ES6 syntax?

Import jquery (I installed with 'npm install [email protected]')

import 'jquery/jquery.js';

Put all your code that depends on jquery inside this method

+function ($) { 
    // your code
}(window.jQuery);

or declare variable $ after import

var $ = window.$

Logical XOR operator in C++?

There was some good code posted that solved the problem better than !a != !b

Note that I had to add the BOOL_DETAIL_OPEN/CLOSE so it would work on MSVC 2010

/* From: http://groups.google.com/group/comp.std.c++/msg/2ff60fa87e8b6aeb

   Proposed code    left-to-right?  sequence point?  bool args?  bool result?  ICE result?  Singular 'b'?
   --------------   --------------  ---------------  ---------- ------------  -----------  -------------
   a ^ b                  no              no             no          no           yes          yes
   a != b                 no              no             no          no           yes          yes
   (!a)!=(!b)             no              no             no          no           yes          yes
   my_xor_func(a,b)       no              no             yes         yes          no           yes
   a ? !b : b             yes             yes            no          no           yes          no
   a ? !b : !!b           yes             yes            no          no           yes          no
   [* see below]          yes             yes            yes         yes          yes          no
   (( a bool_xor b ))     yes             yes            yes         yes          yes          yes

   [* = a ? !static_cast<bool>(b) : static_cast<bool>(b)]

   But what is this funny "(( a bool_xor b ))"? Well, you can create some
   macros that allow you such a strange syntax. Note that the
   double-brackets are part of the syntax and cannot be removed! The set of
   three macros (plus two internal helper macros) also provides bool_and
   and bool_or. That given, what is it good for? We have && and || already,
   why do we need such a stupid syntax? Well, && and || can't guarantee
   that the arguments are converted to bool and that you get a bool result.
     Think "operator overloads". Here's how the macros look like:

   Note: BOOL_DETAIL_OPEN/CLOSE added to make it work on MSVC 2010
  */

#define BOOL_DETAIL_AND_HELPER(x) static_cast<bool>(x):false
#define BOOL_DETAIL_XOR_HELPER(x) !static_cast<bool>(x):static_cast<bool>(x)

#define BOOL_DETAIL_OPEN (
#define BOOL_DETAIL_CLOSE )

#define bool_and BOOL_DETAIL_CLOSE ? BOOL_DETAIL_AND_HELPER BOOL_DETAIL_OPEN
#define bool_or BOOL_DETAIL_CLOSE ? true:static_cast<bool> BOOL_DETAIL_OPEN
#define bool_xor BOOL_DETAIL_CLOSE ? BOOL_DETAIL_XOR_HELPER BOOL_DETAIL_OPEN

Display animated GIF in iOS

I would recommend using the following code, it's much more lightweight, and compatible with ARC and non-ARC project, it adds a simple category on UIImageView:

https://github.com/mayoff/uiimage-from-animated-gif/

White space at top of page

If nothing of the above helps, check if there is margin-top set on some of the (some levels below) nested DOM element(s).

It will be not recognizable when you inspect body element itself in the debugger. It will only be visible when you unfold several elements nested down in body element in Chrome Dev Tools elements debugger and check if there is one of them with margin-top set.

The below is the upper part of a site screen shot and the corresponding Chrome Dev Tools view when you inspect body tag.

No sign of top margin here and you have resetted all the browser-scpecific CSS properties as per answers above but that unwanted white space is still here.

The unwanted white space above the body element The corresponding debugger view

The following is a view when you inspect the right nested element. It is clearly seen the orange'ish top-margin is set on it. This is the one that causes the white space on top of body element.

Clearly visible top-margin enter image description here

On that found element replace margin-top with padding-top if you need space above it and yet not to leak it above the body tag.

Hope that helps :)

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

Go to cloud Messaging select:  Server key



function sendGCM($message, $deviceToken) {

    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array (
            'registration_ids' => array (
                $id
            ),
            'data' => array (
                "title" =>  "Notification title",
                "body" =>  $message,
            )
    );
    $fields = json_encode ( $fields );
    $headers = array (
        'Authorization: key=' . "YOUR_SERVER_KEY",
        'Content-Type: application/json'
    );
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_POST, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
    $result = curl_exec ( $ch );
    echo $result;

    curl_close ($ch);
}

Handling MySQL datetimes and timestamps in Java

In Java side, the date is usually represented by the (poorly designed, but that aside) java.util.Date. It is basically backed by the Epoch time in flavor of a long, also known as a timestamp. It contains information about both the date and time parts. In Java, the precision is in milliseconds.

In SQL side, there are several standard date and time types, DATE, TIME and TIMESTAMP (at some DB's also called DATETIME), which are represented in JDBC as java.sql.Date, java.sql.Time and java.sql.Timestamp, all subclasses of java.util.Date. The precision is DB dependent, often in milliseconds like Java, but it can also be in seconds.

In contrary to java.util.Date, the java.sql.Date contains only information about the date part (year, month, day). The Time contains only information about the time part (hours, minutes, seconds) and the Timestamp contains information about the both parts, like as java.util.Date does.

The normal practice to store a timestamp in the DB (thus, java.util.Date in Java side and java.sql.Timestamp in JDBC side) is to use PreparedStatement#setTimestamp().

java.util.Date date = getItSomehow();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("SELECT * FROM tbl WHERE ts > ?");
preparedStatement.setTimestamp(1, timestamp);

The normal practice to obtain a timestamp from the DB is to use ResultSet#getTimestamp().

Timestamp timestamp = resultSet.getTimestamp("ts");
java.util.Date date = timestamp; // You can just upcast.

How to use requirements.txt to install all dependencies in a python project

Python 3:

pip3 install -r requirements.txt

Python 2:

pip install -r requirements.txt

To get all the dependencies for the virtual environment or for the whole system:

pip freeze

To push all the dependencies to the requirements.txt (Linux):

pip freeze > requirements.txt

Posting JSON Data to ASP.NET MVC

If you've got ther JSON data coming in as a string (e.g. '[{"id":1,"name":"Charles"},{"id":8,"name":"John"},{"id":13,"name":"Sally"}]')

Then I'd use JSON.net and use Linq to JSON to get the values out...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

    if (Request["items"] != null)
    {
        var items = Request["items"].ToString(); // Get the JSON string
        JArray o = JArray.Parse(items); // It is an array so parse into a JArray
        var a = o.SelectToken("[0].name").ToString(); // Get the name value of the 1st object in the array
        // a == "Charles"
    }
}
}

What exactly do "u" and "r" string flags do, and what are raw string literals?

Let me explain it simply: In python 2, you can store string in 2 different types.

The first one is ASCII which is str type in python, it uses 1 byte of memory. (256 characters, will store mostly English alphabets and simple symbols)

The 2nd type is UNICODE which is unicode type in python. Unicode stores all types of languages.

By default, python will prefer str type but if you want to store string in unicode type you can put u in front of the text like u'text' or you can do this by calling unicode('text')

So u is just a short way to call a function to cast str to unicode. That's it!

Now the r part, you put it in front of the text to tell the computer that the text is raw text, backslash should not be an escaping character. r'\n' will not create a new line character. It's just plain text containing 2 characters.

If you want to convert str to unicode and also put raw text in there, use ur because ru will raise an error.

NOW, the important part:

You cannot store one backslash by using r, it's the only exception. So this code will produce error: r'\'

To store a backslash (only one) you need to use '\\'

If you want to store more than 1 characters you can still use r like r'\\' will produce 2 backslashes as you expected.

I don't know the reason why r doesn't work with one backslash storage but the reason isn't described by anyone yet. I hope that it is a bug.

Import Libraries in Eclipse?

If you want to get this library into your library and use it, follow these steps:

  1. You can create a new folder within Eclipse by right-clicking on your project, and selecting New Folder. The library folder is traditionally called lib.

  2. Drag and drop your jar folder into the new lib folder, and when prompted select Copy Files.

  3. Selecting the Project tab at the top of the screen, and click Properties.

  4. Select Java Build Path followed by the Libraries tab.

  5. Click the Add JARs… button and select your JAR file from within the lib folder.

  6. Your JAR file will now appear in both the lib and Referenced Libraries folders. You can explore the JAR's resources by clicking Referenced Libraries.

Android EditText for password with android:hint

If you set

android:inputType="textPassword"

this property and if you provide number as password example "1234567" it will take it as "123456/" the seventh character is not taken. Thats why instead of this approach use

android:password="true"

property which allows you to enter any type of password without any restriction.

If you want to provide hint use

android:hint="hint text goes here"

example:

android:hint="password"

Disable developer mode extensions pop up in Chrome

Now, we need to handle it using following -

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("chrome.switches", "--disable-extensions --disable-extensions-file-access-check --disable-extensions-http-throttling");

Apart from --disable-extensions, we also need to add --disable-extensions-file-access-check (and/or) --disable-extensions-http-throttling chrome switches.

How to increase memory limit for PHP over 2GB?

I had the same problem with commandline php even when ini_set("memory_limit", "-1"); was set, so the limit is in php not from apache.

You should check if you are using the 64bit version of php.

Look at this question about Checking if code is running on 64-bit PHP to find out what php you are using.

I think your php is compiled in 32 bit.

Python - Get path of root project structure

I had to implement a custom solution because it's not as simple as you might think. My solution is based on stack trace inspection (inspect.stack()) + sys.path and is working fine no matter the location of the python module in which the function is invoked nor the interpreter (I tried by running it in PyCharm, in a poetry shell and other...). This is the full implementation with comments:

def get_project_root_dir() -> str:
    """
    Returns the name of the project root directory.

    :return: Project root directory name
    """

    # stack trace history related to the call of this function
    frame_stack: [FrameInfo] = inspect.stack()

    # get info about the module that has invoked this function
    # (index=0 is always this very module, index=1 is fine as long this function is not called by some other
    # function in this module)
    frame_info: FrameInfo = frame_stack[1]

    # if there are multiple calls in the stacktrace of this very module, we have to skip those and take the first
    # one which comes from another module
    if frame_info.filename == __file__:
        for frame in frame_stack:
            if frame.filename != __file__:
                frame_info = frame
                break

    # path of the module that has invoked this function
    caller_path: str = frame_info.filename

    # absolute path of the of the module that has invoked this function
    caller_absolute_path: str = os.path.abspath(caller_path)

    # get the top most directory path which contains the invoker module
    paths: [str] = [p for p in sys.path if p in caller_absolute_path]
    paths.sort(key=lambda p: len(p))
    caller_root_path: str = paths[0]

    if not os.path.isabs(caller_path):
        # file name of the invoker module (eg: "mymodule.py")
        caller_module_name: str = Path(caller_path).name

        # this piece represents a subpath in the project directory
        # (eg. if the root folder is "myproject" and this function has ben called from myproject/foo/bar/mymodule.py
        # this will be "foo/bar")
        project_related_folders: str = caller_path.replace(os.sep + caller_module_name, '')

        # fix root path by removing the undesired subpath
        caller_root_path = caller_root_path.replace(project_related_folders, '')

    dir_name: str = Path(caller_root_path).name

    return dir_name

array.select() in javascript

Underscore.js is a good library for these sorts of operations - it uses the builtin routines such as Array.filter if available, or uses its own if not.

http://documentcloud.github.com/underscore/

The docs will give an idea of use - the javascript lambda syntax is nowhere near as succinct as ruby or others (I always forget to add an explicit return statement for example) and scope is another easy way to get caught out, but you can do most things quite easily with the exception of constructs such as lazy list comprehensions.

From the docs for .select() (.filter() is an alias for the same)

Looks through each value in the list, returning an array of all the values that pass a truth test (iterator). Delegates to the native filter method, if it exists.

  var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
  => [2, 4, 6]

Android failed to load JS bundle

I found this to be weird but I got a solution. I noticed that every once in a while my project folder went read-only and I couldn't save it from VS. So I read a suggestion to transfer NPM from local user PATH to system-wide PATH global variable, and it worked like a charm.

How to download dependencies in gradle

There is no task to download dependencies; they are downloaded on demand. To learn how to manage dependencies with Gradle, see "Chapter 8. Dependency Management Basics" in the Gradle User Guide.

How to convert an IPv4 address into a integer in C#?

As noone posted the code that uses BitConverter and actually checks the endianness, here goes:

byte[] ip = address.Split('.').Select(s => Byte.Parse(s)).ToArray();
if (BitConverter.IsLittleEndian) {
  Array.Reverse(ip);
}
int num = BitConverter.ToInt32(ip, 0);

and back:

byte[] ip = BitConverter.GetBytes(num);
if (BitConverter.IsLittleEndian) {
  Array.Reverse(ip);
}
string address = String.Join(".", ip.Select(n => n.ToString()));

How many bytes is unsigned long long?

Use the operator sizeof, it will give you the size of a type expressed in byte. One byte is eight bits. See the following program:

#include <iostream>

int main(int,char**)
{
 std::cout << "unsigned long long " << sizeof(unsigned long long) << "\n";
 std::cout << "unsigned long long int " << sizeof(unsigned long long int) << "\n";
 return 0;
}

Show percent % instead of counts in charts of categorical variables

Since version 3.3 of ggplot2, we have access to the convenient after_stat() function.

We can do something similar to @Andrew's answer, but without using the .. syntax:

# original example data
mydata <- c("aa", "bb", NULL, "bb", "cc", "aa", "aa", "aa", "ee", NULL, "cc")

# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
                     y = after_stat(count/sum(count)))) +
  geom_bar() +
  scale_y_continuous(labels = scales::percent)

You can find all the "computed variables" available to use in the documentation of the geom_ and stat_ functions. For example, for geom_bar(), you can access the count and prop variables. (See the documentation for computed variables.)

One comment about your NULL values: they are ignored when you create the vector (i.e. you end up with a vector of length 9, not 11). If you really want to keep track of missing data, you will have to use NA instead (ggplot2 will put NAs at the right end of the plot):

# use NA instead of NULL
mydata <- c("aa", "bb", NA, "bb", "cc", "aa", "aa", "aa", "ee", NA, "cc")
length(mydata)
#> [1] 11

# display percentages
library(ggplot2)
ggplot(mapping = aes(x = mydata,
                     y = after_stat(count/sum(count)))) +
  geom_bar() +
  scale_y_continuous(labels = scales::percent)

Created on 2021-02-09 by the reprex package (v1.0.0)

(Note that using chr or fct data will not make a difference for your example.)

String replacement in Objective-C

You could use the method

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target 
                                        withString:(NSString *)replacement

...to get a new string with a substring replaced (See NSString documentation for others)

Example use

NSString *str = @"This is a string";

str = [str stringByReplacingOccurrencesOfString:@"string"
                                     withString:@"duck"];

Uncaught Typeerror: cannot read property 'innerHTML' of null

While you should ideally highlight the code which is causing an error and post that within your question, the error is because you are trying to get the inner HTML of the 'status' element:

var idPost=document.getElementById("status").innerHTML;

However the 'status' element does not exist within your HTML - either add the necessary element or change the ID you are trying to locate to point to a valid element.

Spring Boot application can't resolve the org.springframework.boot package

If the below step not work:

Replaced my Spring Boot 1.4.2.RELEASE to 1.5.10.RELEASE

  • Right click on project and -> Maven-> Download Resources
  • right click on project -> Maven-> Update project

The reason for this error might be multiple version of the same is downloaded into your maven local repository folder.

So follow below steps to clear all existing repository jars and download all from beginning based on dependencies defined in your POM.xml..

  1. Go to build path . Check Maven Repository in the libraries added section.
  2. Choose any jar and mousehover .. it will show the local repository location. generally it is : user/.m2/repository/....
  3. Go to the location . and remove the repository folder contains.
  4. Now right click on your project .. do Maven --> maven update.
    This will solve your dependencies problem . as Maven will try to download all the items again from repository and build the project.

How do you create a yes/no boolean field in SQL server?

You can use the data type bit

Values inserted which are greater than 0 will be stored as '1'

Values inserted which are less than 0 will be stored as '1'

Values inserted as '0' will be stored as '0'

This holds true for MS SQL Server 2012 Express

Recover unsaved SQL query scripts

For SSMS 18, I found the files at:

C:\Users\YourUserName\Documents\Visual Studio 2017\Backup Files\Solution1

For SSMS 17, It was used to be at:

C:\Users\YourUserName\Documents\Visual Studio 2015\Backup Files\Solution1

Use PPK file in Mac Terminal to connect to remote connection over SSH

You can ssh directly from the Terminal on Mac, but you need to use a .PEM key rather than the putty .PPK key. You can use PuttyGen on Windows to convert from .PEM to .PPK, I'm not sure about the other way around though.

You can also convert the key using putty for Mac via port or brew:

sudo port install putty

or

brew install putty

This will also install puttygen. To get puttygen to output a .PEM file:

puttygen privatekey.ppk -O private-openssh -o privatekey.pem

Once you have the key, open a terminal window and:

ssh -i privatekey.pem [email protected]

The private key must have tight security settings otherwise SSH complains. Make sure only the user can read the key.

chmod go-rw privatekey.pem

django MultiValueDictKeyError error, how do I deal with it

First check if the request object have the 'is_private' key parameter. Most of the case's this MultiValueDictKeyError occurred for missing key in the dictionary-like request object. Because dictionary is an unordered key, value pair “associative memories” or “associative arrays”

In another word. request.GET or request.POST is a dictionary-like object containing all request parameters. This is specific to Django.

The method get() returns a value for the given key if key is in the dictionary. If key is not available then returns default value None.

You can handle this error by putting :

is_private = request.POST.get('is_private', False);

How does collections.defaultdict work?

The standard dictionary includes the method setdefault() for retrieving a value and establishing a default if the value does not exist. By contrast, defaultdict lets the caller specify the default up front when the container is initialized.

import collections

def default_factory():
    return 'default value'

d = collections.defaultdict(default_factory, foo='bar')
print 'd:', d
print 'foo =>', d['foo']
print 'bar =>', d['bar']

This works well as long as it is appropriate for all keys to have the same default. It can be especially useful if the default is a type used for aggregating or accumulating values, such as a list, set, or even int. The standard library documentation includes several examples of using defaultdict this way.

$ python collections_defaultdict.py

d: defaultdict(<function default_factory at 0x100468c80>, {'foo': 'bar'})
foo => bar
bar => default value

What is the correct JSON content type?

As many others have mentioned, application/json is the correct answer.

But what haven't been explained yet is what the other options you proposed mean.

  • application/x-javascript: Experimental MIME type for JavaScript before application/javascript was made standard.

  • text/javascript: Now obsolete. You should use application/javascript when using javascript.

  • text/x-javascript: Experimental MIME type for the above situation.

  • text/x-json: Experimental MIME type for JSON before application/json got officially registered.

All in all, whenever you have any doubts about content types, you should check this link

JetBrains / IntelliJ keyboard shortcut to collapse all methods

go to menu option Code > Folding to access all code folding related options and their shortcuts.

How to set JAVA_HOME for multiple Tomcat instances?

Linux based Tomcat6 should have /etc/tomcat6/tomcat6.conf

# System-wide configuration file for tomcat6 services
# This will be sourced by tomcat6 and any secondary service
# Values will be overridden by service-specific configuration
# files in /etc/sysconfig
#
# Use this one to change default values for all services
# Change the service specific ones to affect only one service
# (see, for instance, /etc/sysconfig/tomcat6)
#

# Where your java installation lives
#JAVA_HOME="/usr/lib/jvm/java-1.5.0"

# Where your tomcat installation lives
CATALINA_BASE="/usr/share/tomcat6"
...

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

Try below code :

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

Sub sample()

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

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

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

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

Callback function for JSONP with jQuery AJAX

$.ajax({
        url: 'http://url.of.my.server/submit',
        dataType: "jsonp",
        jsonp: 'callback',
        jsonpCallback: 'jsonp_callback'
    });

jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:

url: 'http://url.of.my.server/submit?callback=?'

the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.

$.ajax({
        url: 'http://url.of.my.server/submit?callback=?',
        success: function (data, status) {
            mySurvey.closePopup();
        },
        error: function (xOptions, textStatus) {
            mySurvey.closePopup();
        }
    });


The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:

$.getJSON('http://url.of.my.server/submit?callback=?',function(data){
//process data here
});

Can I have multiple :before pseudo-elements for the same element?

I've resolved this using:

.element:before {
    font-family: "Font Awesome 5 Free" , "CircularStd";
    content: "\f017" " Date";
}

Using the font family "font awesome 5 free" for the icon, and after, We have to specify the font that we are using again because if we doesn't do this, navigator will use the default font (times new roman or something like this).

Decimal or numeric values in regular expression validation

Try this code, hope it will help you

String regex = "(\\d+)(\\.)?(\\d+)?";  for integer and decimal like 232 232.12 

PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

In my case I was using XAMPP, and there was a log that told me the error. To find it, go to the XAMPP control panel, and click "Configure" for MySQL, then click on "Open Log."

The most current data of the log is at the bottom, and the log is organized by date, time, some number, and text in brackets that may say "Note" or "Error." One that says "Error" is likely causing the issue.

For me, my error was a tablespace that was causing an issue, so I deleted the database files at the given location.

Note: The tablespace files for your installation of XAMPP may be at a different location, but they were in /opt/lampp/var/mysql for me. I think that's typical of XAMPP on Debian-based distributions. Also, my instructions on what to click in the control panel to see the log may be a bit different for you because I'm running XAMPP on an Ubuntu-based distribution of Linux (Feren OS).

mongodb: insert if not exists

You could always make a unique index, which causes MongoDB to reject a conflicting save. Consider the following done using the mongodb shell:

> db.getCollection("test").insert ({a:1, b:2, c:3})
> db.getCollection("test").find()
{ "_id" : ObjectId("50c8e35adde18a44f284e7ac"), "a" : 1, "b" : 2, "c" : 3 }
> db.getCollection("test").ensureIndex ({"a" : 1}, {unique: true})
> db.getCollection("test").insert({a:2, b:12, c:13})      # This works
> db.getCollection("test").insert({a:1, b:12, c:13})      # This fails
E11000 duplicate key error index: foo.test.$a_1  dup key: { : 1.0 }

How to get Rails.logger printing to the console/stdout when running rspec?

A solution that I like, because it keeps rspec output separate from actual rails log output, is to do the following:

  • Open a second terminal window or tab, and arrange it so that you can see both the main terminal you're running rspec on as well as the new one.
  • Run a tail command in the second window so you see the rails log in the test environment. By default this can be like $ tail -f $RAILS_APP_DIR/logs/test.log or tail -f $RAILS_APP_DIR\logs\test.log for Window users
  • Run your rspec suites

If you are running a multi-pane terminal like iTerm, this becomes even more fun and you have rspec and the test.log output side by side.

How do I get the AM/PM value from a DateTime?

Very simple by using the string format

on .ToString("") :

  • if you use "hh" ->> The hour, using a 12-hour clock from 01 to 12.

  • if you use "HH" ->> The hour, using a 24-hour clock from 00 to 23.

  • if you add "tt" ->> The Am/Pm designator.

exemple converting from 23:12 to 11:12 Pm :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("hh:mm tt");   // this show  11:12 Pm
var res2 = d.ToString("HH:mm");  // this show  23:12

Console.WriteLine(res);
Console.WriteLine(res2);

Console.Read();

wait a second that is not all you need to care about something else is the system Culture because the same code executed on windows with other langage especialy with difrent culture langage will generate difrent result with the same code

exemple of windows set to Arabic langage culture will show like that :

// 23:12 ?

? means Evening (first leter of ????) .

in another system culture depend on what is set on the windows regional and language option, it will show // 23:12 du.

you can change between different format on windows control panel under windows regional and language -> current format (combobox) and change... apply it do a rebuild (execute) of your app and watch what iam talking about.

so who can I force showing Am and Pm Words in English event if the culture of the >current system isn't set to English ?

easy just by adding two lines : ->

the first step add using System.Globalization; on top of your code

and modifing the Previous code to be like this :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.InvariantCulture); // this show  11:12 Pm

InvariantCulture => using default English Format.

another question I want to have the pm to be in Arabic or specific language, even if I use windows set to English (or other language) regional format?

Soution for Arabic Exemple :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.CreateSpecificCulture("ar-AE")); 

this will show // 23:12 ?

event if my system is set to an English region format. you can change "ar-AE" if you want to another language format. there is a list of each language and its format.

exemples :

ar          ar-SA       Arabic
ar-BH       ar-BH       Arabic (Bahrain)
ar-DZ       ar-DZ       Arabic (Algeria)
ar-EG       ar-EG       Arabic (Egypt)

big list...

make me know if you have another question .

SQL Call Stored Procedure for each Row without using a cursor

DECLARE @SQL varchar(max)=''

-- MyTable has fields fld1 & fld2

Select @SQL = @SQL + 'exec myproc ' + convert(varchar(10),fld1) + ',' 
                   + convert(varchar(10),fld2) + ';'
From MyTable

EXEC (@SQL)

Ok, so I would never put such code into production, but it does satisfy your requirements.

string.split - by multiple character delimiter

More fast way using directly a no-string array but a string:

string[] StringSplit(string StringToSplit, string Delimitator)
{
    return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}

StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/

Changing background color of selected item in recyclerview

I managed to do this from my Activity where i'm setting my Rv and not from the adapter

If someone need to do something similar here's the code

In this case the color changes on a logClick

           @Override
        public void onLongClick(View view, int position) {
            Toast.makeText(UltimasConsultasActivity.this, "Item agregado a la lista de mails",
                    Toast.LENGTH_SHORT).show();

            sendMultipleMails.setVisibility(View.VISIBLE);
            valueEmail.setVisibility(View.VISIBLE);
            itemsSeleccionados.setVisibility(View.VISIBLE);

            listaEmails.add(superListItems.get(position));
            listaItems ="";
            NameOfyourRecyclerInActivity.findViewHolderForAdapterPosition(position).NameOfYourViewInTheViewholder.setBackgroundColor((Color.parseColor("#336F0D")));

            for(int itemsSelect = 0; itemsSelect <= listaEmails.size() -1; itemsSelect++){

             listaItems  +=  "*"+listaEmails.get(itemsSelect).getDescripcion() + "\n";
            }

            itemsSeleccionados.setText("Items Seleccionados : "+  "\n" + listaItems);


        }


    }));

PHPmailer sending HTML CODE

// Excuse my beginner's english

There is msgHTML() method, which, also, call IsHTML().

Hrm... name IsHTML is confusing...

/**
 * Create a message from an HTML string.
 * Automatically makes modifications for inline images and backgrounds
 * and creates a plain-text version by converting the HTML.
 * Overwrites any existing values in $this->Body and $this->AltBody
 * @access public
 * @param string $message HTML message string
 * @param string $basedir baseline directory for path
 * @param bool $advanced Whether to use the advanced HTML to text converter
 * @return string $message
 */
public function msgHTML($message, $basedir = '', $advanced = false)

How can I restart a Java application?

import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        StringBuilder cmd = new StringBuilder();
        cmd.append(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java ");
        for (String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
            cmd.append(jvmArg + " ");
        }
        cmd.append("-cp ").append(ManagementFactory.getRuntimeMXBean().getClassPath()).append(" ");
        cmd.append(Main.class.getName()).append(" ");
        for (String arg : args) {
            cmd.append(arg).append(" ");
        }
        Runtime.getRuntime().exec(cmd.toString());
        System.exit(0);
    }
}

Dedicated to all those who say it is impossible.

This program collects all information available to reconstruct the original commandline. Then, it launches it and since it is the very same command, your application starts a second time. Then we exit the original program, the child program remains running (even under Linux) and does the very same thing.

WARNING: If you run this, be aware that it never ends creating new processes, similar to a fork bomb.

Troubleshooting "Illegal mix of collations" error in mysql

Solution if literals are involved.

I am using Pentaho Data Integration and dont get to specify the sql syntax. Using a very simple DB lookup gave the error "Illegal mix of collations (cp850_general_ci,COERCIBLE) and (latin1_swedish_ci,COERCIBLE) for operation '='"

The generated code was "SELECT DATA_DATE AS latest_DATA_DATE FROM hr_cc_normalised_data_date_v WHERE PSEUDO_KEY = ?"

Cutting the story short the lookup was to a view and when I issued

mysql> show full columns from hr_cc_normalised_data_date_v;
+------------+------------+-------------------+------+-----+
| Field      | Type       | Collation         | Null | Key |
+------------+------------+-------------------+------+-----+
| PSEUDO_KEY | varchar(1) | cp850_general_ci  | NO   |     |
| DATA_DATE  | varchar(8) | latin1_general_cs | YES  |     |
+------------+------------+-------------------+------+-----+

which explains where the 'cp850_general_ci' comes from.

The view was simply created with 'SELECT 'X',......' According to the manual literals like this should inherit their character set and collation from server settings which were correctly defined as 'latin1' and 'latin1_general_cs' as this clearly did not happen I forced it in the creation of the view

CREATE OR REPLACE VIEW hr_cc_normalised_data_date_v AS
SELECT convert('X' using latin1) COLLATE latin1_general_cs        AS PSEUDO_KEY
    ,  DATA_DATE
FROM HR_COSTCENTRE_NORMALISED_mV
LIMIT 1;

now it shows latin1_general_cs for both columns and the error has gone away. :)

Convert date formats in bash

On OSX, I'm using -f to specify the input format, -j to not attempt to set any date, and an output format specifier. For example:

$ date -j -f "%m/%d/%y %H:%M:%S %p" "8/22/15 8:15:00 am" +"%m%d%y"
082215

Your example:

$ date -j -f "%d %b %Y" "27 JUN 2011" +%Y%m%d
20110627

Scatter plots in Pandas/Pyplot: How to plot by category

seaborn has a wrapper function scatterplot that does it more efficiently.

sns.scatterplot(data = df, x = 'one', y = 'two', data =  'key1'])

How do I set the classpath in NetBeans?

  1. Right-click your Project.
  2. Select Properties.
  3. On the left-hand side click Libraries.
  4. Under Compile tab - click Add Jar/Folder button.

Or

  1. Expand your Project.
  2. Right-click Libraries.
  3. Select Add Jar/Folder.

Using Python's ftplib to get a directory listing, portably

I found my way here while trying to get filenames, last modified stamps, file sizes etc and wanted to add my code. It only took a few minutes to write a loop to parse the ftp.dir(dir_list.append) making use of python std lib stuff like strip() (to clean up the line of text) and split() to create an array.

ftp = FTP('sick.domain.bro')
ftp.login()
ftp.cwd('path/to/data')

dir_list = []
ftp.dir(dir_list.append)

# main thing is identifing which char marks start of good stuff
# '-rw-r--r--   1 ppsrt    ppsrt      545498 Jul 23 12:07 FILENAME.FOO
#                               ^  (that is line[29])

for line in dir_list:
   print line[29:].strip().split(' ') # got yerself an array there bud!
   # EX ['545498', 'Jul', '23', '12:07', 'FILENAME.FOO']

How to open CSV file in R when R says "no such file or directory"?

In my case this very problem was raised by wrong spelling, lower case 'c:' instead of upper case 'C:' in the path. I corrected spelling and problem vanished.

Cookies vs. sessions

A session is a group of information on the server that is associated with the cookie information. If you're using PHP you can check the session. save _ path location and actually "see sessions". A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitate sessions since it tells the server which client handled which session. There are other ways to do this (query string magic etc) but cookies are likely most common for this.

How to retrieve value from elements in array using jQuery?

Your syntax is incorrect.

card_value = $(array[i]).val(); or card_value = array[i].value;

array[i] is not a jQuery object (for some reason).

Checking your browser's console can be helpful for things like this.

How to detect the device orientation using CSS media queries?

In Javascript it is better to use screen.width and screen.height. These two values are available in all modern browsers. They give the real dimensions of the screen, even if the browser has been scaled down when the app fires up. window.innerWidth changes when the browser is scaled down, which can't happen on mobile devices but can happen on PCs and laptops.

The values of screen.width and screen.height change when the mobile device flips between portrait and landscape modes, so it is possible to determine the mode by comparing the values. If screen.width is greater than 1280px you're dealing with a PC or laptop.

You can construct an event listener in Javascript to detect when the two values are flipped. The portrait screen.width values to concentrate on are 320px (mainly iPhones), 360px (most other phones), 768px (small tablets) and 800px (regular tablets).

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.