Programs & Examples On #Plinq

PLINQ is a parallel query execution engine for LINQ. PLINQ supports the data parallelism pattern by adding additional syntax to allow queries to be declared as running in parallel.

Python - Count elements in list

len()

>>> someList=[]
>>> print len(someList)
0

phpMyAdmin on MySQL 8.0

Another idea: as long as the phpmyadmin and other php tools don't work with it, just add this line to your file /etc/mysql/my.cnf

default_authentication_plugin = mysql_native_password

See also: Mysql Ref

I know that this is a security issue, but what to do if the tools don't work with caching_sha2_password?

How to create relationships in MySQL

Certain MySQL engines support foreign keys. For example, InnoDB can establish constraints based on foreign keys. If you try to delete an entry in one table that has dependents in another, the delete will fail.

If you are using a table type in MySQL, such as MyISAM, that doesn't support foreign keys, you don't link the tables anywhere except your diagrams and queries.

For example, in a query you link two tables in a select statement with a join:

SELECT a, b from table1 LEFT JOIN table2 USING (common_field);

How do I make text bold in HTML?

Could someone tell me what I'm doing wrong?"

"bold" has never been an HTML element ("b" is the closest match).

HTML should contain structured content; publisher CSS should suggest styles for that content. That way user agents can expose the structured content with useful styling and navigational controls to users who can't see your suggested bold styling (e.g. users of search engines, totally blind users using screen readers, poorly sighted users using their own colors and fonts, geeky users using text browsers, users of voice-controlled, speaking browsers like Opera for Windows). Thus the right way to make text bold depends on why you want to style it bold. For example:

  • Want to distinguish headings from other text? Use heading elements ("h1" to "h6") and suggest a bold style for them within your CSS ("h1, h2, h3, h4, h5, h6 {font-weight: bold;}".

  • Want to embolden labels for form fields? Use a "label" element, programmatically associate it with the the relevant "select", "input" or "textarea" element by giving it a "for" attribute matching an "id" attribute on the target, and suggest a bold style for it within your CSS ("label {font-weight: bold;"}).

  • Want to embolden a heading for a group of related fields in a form, such as a group of radio choices? Surround them with a "fieldset" element, give it a "legend" element, and suggest a bold style for it within your CSS ("legend {font-weight: bold;}").

  • Want to distinguish a table caption from the table it captions? Use a "caption" element and suggest a bold style for it within your CSS ("caption {font-weight: bold;}").

  • Want to distinguish table headings from table data cells? Use a "th" element and suggest a bold style for it within your CSS ("th {font-weight: bold;}").

  • Want to distinguish the title of a referenced film or album from surrounding text? Use a "cite" element with a class ("cite class="movie-title"), and suggest a bold style for it within your CSS (".movie-title {font-weight: bold;}").

  • Want to distinguish a defined keyword from the surrounding text defining or explaining it? Use a "dfn" element and suggest a bold style for it within your CSS ("dfn {font-weight: bold;}").

  • Want to distinguish some computer code from surrounding text? Use a "code" element and suggest a bold style for it within your CSS ("code {font-weight: bold;}").

  • Want to distinguish a variable name from surrounding text? Use a "var" element and suggest a bold style for it within your CSS ("var {font-weight: bold;}").

  • Want to indicate that some text has been added as an update? Use an "ins" element and suggest a bold style for it within your CSS ("ins {font-weight: bold;}").

  • Want to lightly stress some text ("I love kittens!")? Use an "em" element and suggest a bold style for it within your CSS (e.g. "em {font-weight: bold;}").

  • Want to heavily stress some text, perhaps for a warning ("Beware the dog!")? Use a "strong" element and suggest a bold style for it within your CSS (e.g. "strong {font-weight: bold;}").

… You get the idea (hopefully).

Can't find an HTML element with the right semantics to express /why/ you want to make this particular text bold? Wrap it in a generic "span" element, give it a meaningful class name that expresses your rationale for distinguishing that text ("<span class="lede">Let me begin this news article with a sentence that summarizes it.</span>), and suggest a bold style for it within your CSS (".lede {font-weight: bold;"}. Before making up your own class names, you might want to check if there's a microformat (microformats.org) or common convention for what you want to express.

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

I was facing same issue so I have reinstall MySQL 8 with different Authentication Method "Use Legacy Authentication Method (Retain MySQL 5.x compatibility)" then work properly.

Choose Second Method of Authentication while installing.

Execute external program

import java.io.*;

public class Code {
  public static void main(String[] args) throws Exception {
    ProcessBuilder builder = new ProcessBuilder("ls", "-ltr");
    Process process = builder.start();

    StringBuilder out = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line = null;
      while ((line = reader.readLine()) != null) {
        out.append(line);
        out.append("\n");
      }
      System.out.println(out);
    }
  }
}

Try online

Get UTC time in seconds

You say you're using:

time.asctime(time.localtime(date_in_seconds_from_bash))

where date_in_seconds_from_bash is presumably the output of date +%s.

The time.localtime function, as the name implies, gives you local time.

If you want UTC, use time.gmtime() rather than time.localtime().

As JamesNoonan33's answer says, the output of date +%s is timezone invariant, so date +%s is exactly equivalent to date -u %s. It prints the number of seconds since the "epoch", which is 1970-01-01 00:00:00 UTC. The output you show in your question is entirely consistent with that:

date -u
Thu Jul 3 07:28:20 UTC 2014

date +%s
1404372514   # 14 seconds after "date -u" command

date -u +%s
1404372515   # 15 seconds after "date -u" command

How can I delay a :hover effect in CSS?

For a more aesthetic appearance :) can be:

left:-9999em; 
top:-9999em; 

position for .sNv2 .nav UL can be replaced by z-index:-1 and z-index:1 for .sNv2 .nav LI:Hover UL

Better way to check if a Path is a File or a Directory?

As an alternative to Directory.Exists(), you can use the File.GetAttributes() method to get the attributes of a file or a directory, so you could create a helper method like this:

private static bool IsDirectory(string path)
{
    System.IO.FileAttributes fa = System.IO.File.GetAttributes(path);
    return (fa & FileAttributes.Directory) != 0;
}

You could also consider adding an object to the tag property of the TreeView control when populating the control that contains additional metadata for the item. For instance, you could add a FileInfo object for files and a DirectoryInfo object for directories and then test for the item type in the tag property to save making additional system calls to get that data when clicking on the item.

How to resolve "Input string was not in a correct format." error?

The problem is with line

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Label1.Text may or may not be int. Check.

Use Int32.TryParse(value, out number) instead. That will solve your problem.

int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
    Image1.Width= imageWidth;
}

How do I install Composer on a shared hosting?

I have successfully installed Composer (and Laravel) on my shared hosting with only FTP access:

  1. Download and install PHPShell on a shared hosting

  2. In PHPShell's config.php add a user and an alias:

    php = "php -d suhosin.executor.include.whitelist=phar"

  3. Log in to PHPShell and type: curl -sS https://getcomposer.org/installer | php

  4. When successfully installed, run Composer: php composer.phar

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

Copy conditionally formatted cells into Word (using CTRL+C, CTRL+V). Copy them back into Excel, keeping the source formatting. Now the conditional formatting is lost but you still have the colors and can check the RGB choosing Home > Fill color (or Font color) > More colors.

How do detect Android Tablets in general. Useragent?

Based on Agents strings on this site:

http://www.webapps-online.com/online-tools/user-agent-strings

This results came up:
First:

All Tablet Devices have:
1. Tablet
2. iPad

Second:

All Phone Devices have:
1. Mobile
2. Phone

Third:

Tablet and Phone Devices have:
1. Android

If you can detect level by level, I thing the result is 90 percent true. Like SharePoint Device Channels.

How to import a JSON file in ECMAScript 6?

If you're using node you can:

const fs = require('fs');

const { config } = JSON.parse(fs.readFileSync('../config.json', 'utf8')) // May be incorrect, haven't used fs in a long time

OR

const evaluation = require('../config.json');
// evaluation will then contain all props, so evaluation.config
// or you could use:
const { config } = require('../config.json');

Else:

// config.js
{
// json object here
}

// script.js

import { config } from '../config.js';

OR

import * from '../config.json'

GROUP BY having MAX date

Another way that doesn't use group by:

SELECT * FROM tblpm n 
  WHERE date_updated=(SELECT date_updated FROM tblpm n 
                        ORDER BY date_updated desc LIMIT 1)

Copy and Paste a set range in the next empty row

Below is the code that works well but my values overlap in sheet "Final" everytime the condition of <=11 meets in sheet "Calculator"

I would like you to kindly support me to modify the code so that the cursor should move to next blank cell and values keeps on adding up like a list.

Dim i As Integer
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Calculator")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Final")

For i = 2 To ws1.Range("A65536").End(xlUp).Row

    If ws1.Cells(i, 4) <= 11 Then

        ws2.Cells(i, 1).Value = Left(Worksheets("Calculator").Cells(i, 1).Value, Len(Worksheets("Calculator").Cells(i, 1).Value) - 0)
        ws2.Cells(i, 2) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:D"), 4, False)
        ws2.Cells(i, 3) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:E"), 5, False)
        ws2.Cells(i, 4) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:B"), 2, False)
        ws2.Cells(i, 5) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:C"), 3, False)

    End If
Next i

Spring not autowiring in unit tests with JUnit

You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml available on the test classpath.

import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {

    @Autowired
    protected SessionFactory sessionFactory;

    @Test
    public void testDBSourceIsCorrect() throws SQLException {
        String databaseProductName = sessionFactory.getCurrentSession()
                .connection()
                .getMetaData()
                .getDatabaseProductName();
        assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
    }
}

Note: This works with Spring 2.5.2 and Hibernate 3.6.5

Create an ArrayList of unique values

You could use a Set. It is a collection which doesn't accept duplicates.

How to auto adjust the div size for all mobile / tablet display formats?

I use something like this in my document.ready

var height = $(window).height();//gets height from device
var width = $(window).width(); //gets width from device

$("#container").width(width+"px");
$("#container").height(height+"px");

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

Can also be called as

@Html.Partial("_PartialView", (ModelClass)View.Data)

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

I had the same problem using distribution provisioning profile. Check that you use developer profile

Use table name in MySQL SELECT "AS"

SELECT field1, field2, 'Test' AS field3 FROM Test; // replace with simple quote '

No appenders could be found for logger(log4j)?

Maybe add the relevent project contains log4j in java build path, I add mahout_h2o into it when I met this problem in a mahout project using eclipse, it works!

How to use JavaScript variables in jQuery selectors?

$("#" + $(this).attr("name")).hide();

Solving Quadratic Equation

give input through your keyboard

a=float(input("enter the 1st number : "))
b=float(input("enter the 2nd number : "))
c=float(input("enter the 3rd number : "))

calculate the discriminant

d = (b**2) - (4*a*c)

possible solution are

sol_1 = (-b-(0.5**d))/(2*a)
sol_2 = (-b+(0.5**d))/(2*a)

print the result

print('The solution are  %0.f,%0.f'%(sol_1,sol_2))

Execute a large SQL script (with GO commands)

You can use SQL Management Objects to perform this. These are the same objects that Management Studio uses to execute queries. I believe Server.ConnectionContext.ExecuteNonQuery() will perform what you need.

Remote debugging Tomcat with Eclipse

In catalina.bat file please modify the below.

  • Step 1: CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"

  • Step 2: JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"

  • Step 3: Run Tomcat from command prompt like below: catalina.sh jpda start

  • Step 4: Then in the eclipse create a debug configuration

    1. Give any name for configuration.
    2. Give the project name.
    3. Give the connection type as Standard(Socket Attach)
    4. host as localhost
    5. port as 8000( or any port number , but that should be same in other places also).

How to get an array of unique values from an array containing duplicates in JavaScript?

This will work. Try it.

function getUnique(a) {
  var b = [a[0]], i, j, tmp;
  for (i = 1; i < a.length; i++) {
    tmp = 1;
    for (j = 0; j < b.length; j++) {
      if (a[i] == b[j]) {
        tmp = 0;
        break;
      }
    }
    if (tmp) {
      b.push(a[i]);
    }
  }
  return b;
}

How to find list of possible words from a letter matrix [Boggle Solver]

A Node.JS JavaScript solution. Computes all 100 unique words in less than a second which includes reading dictionary file (MBA 2012).

Output:
["FAM","TUX","TUB","FAE","ELI","ELM","ELB","TWA","TWA","SAW","AMI","SWA","SWA","AME","SEA","SEW","AES","AWL","AWE","SEA","AWA","MIX","MIL","AST","ASE","MAX","MAE","MAW","MEW","AWE","MES","AWL","LIE","LIM","AWA","AES","BUT","BLO","WAS","WAE","WEA","LEI","LEO","LOB","LOX","WEM","OIL","OLM","WEA","WAE","WAX","WAF","MILO","EAST","WAME","TWAS","TWAE","EMIL","WEAM","OIME","AXIL","WEST","TWAE","LIMB","WASE","WAST","BLEO","STUB","BOIL","BOLE","LIME","SAWT","LIMA","MESA","MEWL","AXLE","FAME","ASEM","MILE","AMIL","SEAX","SEAM","SEMI","SWAM","AMBO","AMLI","AXILE","AMBLE","SWAMI","AWEST","AWEST","LIMAX","LIMES","LIMBU","LIMBO","EMBOX","SEMBLE","EMBOLE","WAMBLE","FAMBLE"]

Code:

var fs = require('fs')

var Node = function(value, row, col) {
    this.value = value
    this.row = row
    this.col = col
}

var Path = function() {
    this.nodes = []
}

Path.prototype.push = function(node) {
    this.nodes.push(node)
    return this
}

Path.prototype.contains = function(node) {
    for (var i = 0, ii = this.nodes.length; i < ii; i++) {
        if (this.nodes[i] === node) {
            return true
        }
    }

    return false
}

Path.prototype.clone = function() {
    var path = new Path()
    path.nodes = this.nodes.slice(0)
    return path
}

Path.prototype.to_word = function() {
    var word = ''

    for (var i = 0, ii = this.nodes.length; i < ii; ++i) {
        word += this.nodes[i].value
    }

    return word
}

var Board = function(nodes, dict) {
    // Expects n x m array.
    this.nodes = nodes
    this.words = []
    this.row_count = nodes.length
    this.col_count = nodes[0].length
    this.dict = dict
}

Board.from_raw = function(board, dict) {
    var ROW_COUNT = board.length
      , COL_COUNT = board[0].length

    var nodes = []

    // Replace board with Nodes
    for (var i = 0, ii = ROW_COUNT; i < ii; ++i) {
        nodes.push([])
        for (var j = 0, jj = COL_COUNT; j < jj; ++j) {
            nodes[i].push(new Node(board[i][j], i, j))
        }
    }

    return new Board(nodes, dict)
}

Board.prototype.toString = function() {
    return JSON.stringify(this.nodes)
}

Board.prototype.update_potential_words = function(dict) {
    for (var i = 0, ii = this.row_count; i < ii; ++i) {
        for (var j = 0, jj = this.col_count; j < jj; ++j) {
            var node = this.nodes[i][j]
              , path = new Path()

            path.push(node)

            this.dfs_search(path)
        }
    }
}

Board.prototype.on_board = function(row, col) {
    return 0 <= row && row < this.row_count && 0 <= col && col < this.col_count
}

Board.prototype.get_unsearched_neighbours = function(path) {
    var last_node = path.nodes[path.nodes.length - 1]

    var offsets = [
        [-1, -1], [-1,  0], [-1, +1]
      , [ 0, -1],           [ 0, +1]
      , [+1, -1], [+1,  0], [+1, +1]
    ]

    var neighbours = []

    for (var i = 0, ii = offsets.length; i < ii; ++i) {
        var offset = offsets[i]
        if (this.on_board(last_node.row + offset[0], last_node.col + offset[1])) {

            var potential_node = this.nodes[last_node.row + offset[0]][last_node.col + offset[1]]
            if (!path.contains(potential_node)) {
                // Create a new path if on board and we haven't visited this node yet.
                neighbours.push(potential_node)
            }
        }
    }

    return neighbours
}

Board.prototype.dfs_search = function(path) {
    var path_word = path.to_word()

    if (this.dict.contains_exact(path_word) && path_word.length >= 3) {
        this.words.push(path_word)
    }

    var neighbours = this.get_unsearched_neighbours(path)

    for (var i = 0, ii = neighbours.length; i < ii; ++i) {
        var neighbour = neighbours[i]
        var new_path = path.clone()
        new_path.push(neighbour)

        if (this.dict.contains_prefix(new_path.to_word())) {
            this.dfs_search(new_path)
        }
    }
}

var Dict = function() {
    this.dict_array = []

    var dict_data = fs.readFileSync('./web2', 'utf8')
    var dict_array = dict_data.split('\n')

    for (var i = 0, ii = dict_array.length; i < ii; ++i) {
        dict_array[i] = dict_array[i].toUpperCase()
    }

    this.dict_array = dict_array.sort()
}

Dict.prototype.contains_prefix = function(prefix) {
    // Binary search
    return this.search_prefix(prefix, 0, this.dict_array.length)
}

Dict.prototype.contains_exact = function(exact) {
    // Binary search
    return this.search_exact(exact, 0, this.dict_array.length)
}

Dict.prototype.search_prefix = function(prefix, start, end) {
    if (start >= end) {
        // If no more place to search, return no matter what.
        return this.dict_array[start].indexOf(prefix) > -1
    }

    var middle = Math.floor((start + end)/2)

    if (this.dict_array[middle].indexOf(prefix) > -1) {
        // If we prefix exists, return true.
        return true
    } else {
        // Recurse
        if (prefix <= this.dict_array[middle]) {
            return this.search_prefix(prefix, start, middle - 1)
        } else {
            return this.search_prefix(prefix, middle + 1, end)
        }
    }
}

Dict.prototype.search_exact = function(exact, start, end) {
    if (start >= end) {
        // If no more place to search, return no matter what.
        return this.dict_array[start] === exact
    }

    var middle = Math.floor((start + end)/2)

    if (this.dict_array[middle] === exact) {
        // If we prefix exists, return true.
        return true
    } else {
        // Recurse
        if (exact <= this.dict_array[middle]) {
            return this.search_exact(exact, start, middle - 1)
        } else {
            return this.search_exact(exact, middle + 1, end)
        }
    }
}

var board = [
    ['F', 'X', 'I', 'E']
  , ['A', 'M', 'L', 'O']
  , ['E', 'W', 'B', 'X']
  , ['A', 'S', 'T', 'U']
]

var dict = new Dict()

var b = Board.from_raw(board, dict)
b.update_potential_words()
console.log(JSON.stringify(b.words.sort(function(a, b) {
    return a.length - b.length
})))

HTML form input tag name element array with JavaScript

document.form.p_id.length ... not count().

You really should give your form an id

<form id="myform">

Then refer to it using:

var theForm = document.getElementById("myform");

Then refer to the elements like:

for(var i = 0; i < theForm.p_id.length; i++){

What is Android keystore file, and what is it used for?

The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.

In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.

I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.

But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.

Making a div vertically scrollable using CSS

You can use this code instead.

<div id="" style="overflow-y:scroll; overflow-x:hidden; height:400px;">


overflow-x: The overflow-x property specifies what to do with the left/right edges of the content - if it overflows the element's content area.
overflow-y: The overflow-y property specifies what to do with the top/bottom edges of the content - if it overflows the element's content area.

Values
visible: Default value. The content is not clipped, and it may be rendered outside the content box.
hidden: The content is clipped - and no scrolling mechanism is provided.
scroll: The content is clipped and a scrolling mechanism is provided.
auto: Should cause a scrolling mechanism to be provided for overflowing boxes.
initial: Sets this property to its default value.
inherit Inherits this property from its parent element.

GROUP_CONCAT comma separator - MySQL

Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.

GROUP_CONCAT(artists.artistname SEPARATOR '----')

The way you've written it, you're concatenating artists.artistname with the '----' string using the default comma separator.

A potentially dangerous Request.Path value was detected from the client (*)

I had a similar issue in Azure Data Factory with the : character.

I resolved the problem by substituting : with %3A

as shown here.

For example, I substituted

date1=2020-01-25T00:00:00.000Z

with

date1=2020-01-25T00%3A00%3A00.000Z

Quickly create a large file on a Linux system

One approach: if you can guarantee unrelated applications won't use the files in a conflicting manner, just create a pool of files of varying sizes in a specific directory, then create links to them when needed.

For example, have a pool of files called:

  • /home/bigfiles/512M-A
  • /home/bigfiles/512M-B
  • /home/bigfiles/1024M-A
  • /home/bigfiles/1024M-B

Then, if you have an application that needs a 1G file called /home/oracle/logfile, execute a "ln /home/bigfiles/1024M-A /home/oracle/logfile".

If it's on a separate filesystem, you will have to use a symbolic link.

The A/B/etc files can be used to ensure there's no conflicting use between unrelated applications.

The link operation is about as fast as you can get.

How to fix error Base table or view not found: 1146 Table laravel relationship table?

It seems Laravel is trying to use category_posts table (because of many-to-many relationship). But you don't have this table, because you've created category_post table. Change name of the table to category_posts.

check if variable empty

you can use isset() routine .

also additionaly you can refer an range of is_type () functions like

is_string(), is_float(),is_int() etc to further specificaly test

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

October 2015 Update

This answer was posted several years ago and now the question really should be should you even consider using the X-UA-Compatible tag on your site? with the changes Microsoft has made to its browsers (more on those below).

Depending upon what Microsoft browsers you support you may not need to continue using the X-UA-Compatible tag. If you need to support IE9 or IE8, then I would recommend using the tag. If you only support the latest browsers (IE11 and/or Edge) then I would consider dropping this tag altogether. If you use Twitter Bootstrap and need to eliminate validation warnings, this tag must appear in its specified order. Additional info below:


The X-UA-Compatible meta tag allows web authors to choose what version of Internet Explorer the page should be rendered as. IE11 has made changes to these modes; see the IE11 note below. Microsoft Edge, the browser that replaced IE11, only honors the X-UA-Compatible meta tag in certain circumstances. See the Microsoft Edge note below.

According to Microsoft, when using the X-UA-Compatible tag, it should be as high as possible in your document head:

If you are using the X-UA-Compatible META tag you want to place it as close to the top of the page's HEAD as possible. Internet Explorer begins interpreting markup using the latest version. When Internet Explorer encounters the X-UA-Compatible META tag it starts over using the designated version's engine. This is a performance hit because the browser must stop and restart analyzing the content.

Here are your options:

  • "IE=edge"
  • "IE=11"
  • "IE=EmulateIE11"
  • "IE=10"
  • "IE=EmulateIE10"
  • "IE=9"
  • "IE=EmulateIE9
  • "IE=8"
  • "IE=EmulateIE8"
  • "IE=7"
  • "IE=EmulateIE7"
  • "IE=5"

To attempt to understand what each means, here are definitions provided by Microsoft:

Internet Explorer supports a number of document compatibility modes that enable different features and can affect the way content is displayed:

  • Edge mode tells Internet Explorer to display content in the highest mode available. With Internet Explorer 9, this is equivalent to IE9 mode. If a future release of Internet Explorer supported a higher compatibility mode, pages set to edge mode would appear in the highest mode supported by that version. Those same pages would still appear in IE9 mode when viewed with Internet Explorer 9. Internet Explorer supports a number of document compatibility modes that enable different features and can affect the way content is displayed:

  • IE11 mode provides the highest support available for established and emerging industry standards, including the HTML5, CSS3 and others.

  • IE10 mode provides the highest support available for established and emerging industry standards, including the HTML5, CSS3 and others.

  • IE9 mode provides the highest support available for established and emerging industry standards, including the HTML5 (Working Draft), W3C Cascading Style Sheets Level 3 Specification (Working Draft), Scalable Vector Graphics (SVG) 1.0 Specification, and others. [Editor Note: IE 9 does not support CSS3 animations].

  • IE8 mode supports many established standards, including the W3C Cascading Style Sheets Level 2.1 Specification and the W3C Selectors API; it also provides limited support for the W3C Cascading Style Sheets Level 3 Specification (Working Draft) and other emerging standards.

  • IE7 mode renders content as if it were displayed in standards mode by Internet Explorer 7, whether or not the page contains a directive.

  • Emulate IE9 mode tells Internet Explorer to use the directive to determine how to render content. Standards mode directives are displayed in IE9 mode and quirks mode directives are displayed in IE5 mode. Unlike IE9 mode, Emulate IE9 mode respects the directive.

  • Emulate IE8 mode tells Internet Explorer to use the directive to determine how to render content. Standards mode directives are displayed in IE8 mode and quirks mode directives are displayed in IE5 mode. Unlike IE8 mode, Emulate IE8 mode respects the directive.

  • Emulate IE7 mode tells Internet Explorer to use the directive to determine how to render content. Standards mode directives are displayed in Internet Explorer 7 standards mode and quirks mode directives are displayed in IE5 mode. Unlike IE7 mode, Emulate IE7 mode respects the directive. For many web sites, this is the preferred compatibility mode.

  • IE5 mode renders content as if it were displayed in quirks mode by Internet Explorer 7, which is very similar to the way content was displayed in Microsoft Internet Explorer 5.

IE10 NOTE: As of IE10, quirks mode behaves differently than it did in earlier versions of the browser. In IE9 and earlier versions, quirks mode restricted the webpage to the features supported by IE5.5. In IE10, quirks mode conforms to the differences specified in the HTML5 specification.

Personally, I always choose the http-equiv="X-UA-Compatible" content="IE=edge" meta tag, as older versions have plenty of bugs, and I do not want IE to decide to go into "Compatibility mode" and show my site as IE7 vs IE8 or 9. I always prefer the latest version of IE.

IE11

From Microsoft:

Starting with IE11, edge mode is the preferred document mode; it represents the highest support for modern standards available to the browser.

Use the HTML5 document type declaration to enable edge mode:

<!doctype html>

Edge mode was introduced in Internet Explorer 8 and has been available in each subsequent release. Note that the features supported by edge mode are limited to those supported by the specific version of the browser rendering the content.

Starting with IE11, document modes are deprecated and should no longer be used, except on a temporary basis. Make sure to update sites that rely on legacy features and document modes to reflect modern standards.

If you must target a specific document mode so that your site functions while you rework it to support modern standards and features, be aware that you're using a transitional feature, one that may not be available in future versions.

If you currently use the x-ua-compatible header to target a legacy document mode, it's possible your site won't reflect the best experience available with IE11.

Microsoft Edge (Replacement for Internet Explorer that comes bundled with Windows 10)

Information on X-UA-Compatible meta tag for the "Edge" version of IE. From Microsoft:

Introducing the “living” Edge document mode

As we announced in August 2013, we are deprecating document modes as of IE11. With our latest platform updates, the need for legacy document modes is primarily limited to Enterprise legacy web apps. With new architectural changes, these legacy document modes will be isolated from changes in the “living” Edge mode, which will help to guarantee a much higher level of compatibility for customers who depend on those modes and help us move even faster on improvements in Edge. IE will still honor document modes served by intranet sites, sites on the Compatibility View list, and when used with Enterprise Mode only.

Public Internet sites will be rendered with the new Edge mode platform (ignoring X-UA-Compatible). It is our goal that Edge is the "living" document mode from here out and no further document modes will be introduced going forward.

With the changes in Microsoft Edge to no longer support document modes in most cases, Microsoft has a tool to scan your site to check and see if it has code that is not compatible with Edge.

Chrome=1 Info for IE

There is also chrome=1 that you can use or use together with one of the above options like: <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">. chrome=1 is for Google's Chrome Frame which is defined as:

Google Chrome Frame is an open source browser plug-in. Users who have the plug-in installed have access to Google Chrome's open web technologies and speedy JavaScript engine when they open pages in the browser.

Google Chrome Frame seamlessly enhances your browsing experience in Internet Explorer. It displays Google Chrome Frame enabled sites using Google Chrome’s rendering technology, giving you access to the latest HTML5 features as well as Google Chrome’s performance and security features without in any way interrupting your usual browser usage.

When Google Chrome Frame is installed, the web just gets better without you having to think about it.

But for that plug-in to work you must use chrome=1 in the X-UA-Compatible meta tag.

More info on Chrome Frame can be found here.

Note: Google Chrome Frame only works for IE6 through IE9, and was retired on February 25, 2014. More info can be found here. Thanks to @mck for the link.

Validation:

HTML5:

The page will validate using the W3 Validator only when using <meta http-equiv="X-UA-Compatible" content="IE=Edge">. For other values it will throw the error: A meta element with an http-equiv attribute whose value is X-UA-Compatible must have a content attribute with the value IE=edge. In other words, if you have IE=edge,chrome=1 it will not validate. I ignore this error completely as modern browsers simply ignore this line of code.

If you must have completely valid code then consider doing this on the server level by setting HTTP header. As a note, Microsoft says, If both of these instructions are sent (meta and HTTP), the developer's preference (meta element) takes precedence over the web server setting (HTTP header). See olibre's answer or bitinn's answer for more details on how to set an HTTP header.

XHTML

There isn't an issue with validation when using <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> as long as the tag is properly closed (i.e. /> vs >).

Twitter Bootstrap

This tag has been strongly recommended by the Bootstrap team since at least 2014, and Bootlint, the linter authored by the twbs team continues to throw a warning when the tag is omitted. The linter distinguishes between warnings and errors, and as such the severity of omitting this tag may be considered minor.


For more information on X-UA-Compatible see Microsoft's Website Defining Document Compatibility.

For more information on what IE supports see caniuse.com.

For more information on Twitter Bootstrap requirements, see the bootlint project wiki page.

Moment.js with Vuejs

If your project is a single page application, (eg project created by vue init webpack myproject), I found this way is most intuitive and simple:

In main.js

import moment from 'moment'

Vue.prototype.moment = moment

Then in your template, simply use

<span>{{moment(date).format('YYYY-MM-DD')}}</span>

jQuery find file extension (from string)

Another way (which avoids extended switch-case statements) is to define arrays of file extensions for similar processing and use a function to check the extension result against an array (with comments):

// Define valid file extension arrays (according to your needs)
var _docExts = ["pdf", "doc", "docx", "odt"];
var _imgExts = ["jpg", "jpeg", "png", "gif", "ico"];
// Checks whether an extension is included in the array
function isExtension(ext, extnArray) {
    var result = false;
    var i;
    if (ext) {
        ext = ext.toLowerCase();
        for (i = 0; i < extnArray.length; i++) {
            if (extnArray[i].toLowerCase() === ext) {
                result = true;
                break;
            }
        }
    }
    return result;
}
// Test file name and extension
var testFileName = "example-filename.jpeg";
// Get the extension from the filename
var extn = testFileName.split('.').pop();
// boolean check if extensions are in parameter array
var isDoc = isExtension(extn, _docExts);
var isImg = isExtension(extn, _imgExts);
console.log("==> isDoc: " + isDoc + " => isImg: " + isImg);
// Process according to result: if(isDoc) { // .. etc }

How to enable GZIP compression in IIS 7.5

Sometimes no matter what you do or follow whole internet posts. Try on the MIMETYPES of applicationhost.config of the server.

https://docs.microsoft.com/en-us/iis/configuration/system.webserver/httpcompression/#configuration-sample

Get Current Session Value in JavaScript?

would be a lot easier to use Razor code in your page.

in my example, i needed to set a hidden field with a session variable.

$('#clearFormButton').click(function(){
    ResetForm();
    $('#hiddenJobId').val(@Session["jobid"]);
});

that easy. remember, you need to preface the Session with a @ sign for razor syntax.

Two statements next to curly brace in an equation

You can try the cases env in amsmath.

\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{equation}
  f(x)=\begin{cases}
    1, & \text{if $x<0$}.\\
    0, & \text{otherwise}.
  \end{cases}
\end{equation}

\end{document}

amsmath cases

IE Driver download location Link for Selenium

You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/

32 bit Windows IE

64 bit Windows IE

IE Driver is also available in the following site:

http://selenium-release.storage.googleapis.com/index.html

How to embed a SWF file in an HTML page?

What is the 'best' way? Words like 'most efficient,' 'fastest rendering,' etc. are more specific. Anyway, I am offering an alternative answer that helps me most of the time (whether or not is 'best' is irrelevant).

Alternate answer: Use an iframe.

That is, host the SWF file on the server. If you put the SWF file in the root or public_html folder then the SWF file will be located at www.YourDomain.com/YourFlashFile.swf.

Then, on your index.html or wherever, link the above location to your iframe and it will be displayed around your content wherever you put your iframe. If you can put an iframe there, you can put an SWF file there. Make the iframe dimensions the same as your SWF file. In the example below, the SWF file is 500 by 500.

Pseudo code:

<iframe src="//www.YourDomain.com/YourFlashFile.swf" width="500" height="500"></iframe>

The line of HTML code above will embed your SWF file. No other mess needed. Pros: W3C compliant, page design friendly, no speed issue, minimalist approach.
Cons: White space around your SWF file when launched in a browser.

That is an alternate answer. Whether it is the 'best' answer depends on your project.

How to generate .NET 4.0 classes from xsd?

simple enough; just run (at the vs command prompt)

xsd your.xsd /classes

(which will create your.cs). Note, however, that most of the intrinsic options here haven't changed much since 2.0

For the options, use xsd /? or see MSDN; for example /enableDataBinding can be useful.

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

Add a second });.

When properly indented, your code reads

$(function() {
    $("#mewlyDiagnosed").hover(function() {
        $("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
    }, function() {
        $("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
    });
MISSING!

You never closed the outer $(function() {.

How to return PDF to browser in MVC?

Return a FileContentResult. The last line in your controller action would be something like:

return File("Chap0101.pdf", "application/pdf");

If you are generating this PDF dynamically, it may be better to use a MemoryStream, and create the document in memory instead of saving to file. The code would be something like:

Document document = new Document();

MemoryStream stream = new MemoryStream();

try
{
    PdfWriter pdfWriter = PdfWriter.GetInstance(document, stream);
    pdfWriter.CloseStream = false;

    document.Open();
    document.Add(new Paragraph("Hello World"));
}
catch (DocumentException de)
{
    Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
    Console.Error.WriteLine(ioe.Message);
}

document.Close();

stream.Flush(); //Always catches me out
stream.Position = 0; //Not sure if this is required

return File(stream, "application/pdf", "DownloadName.pdf");

jQuery: enabling/disabling datepicker

$("#nicIssuedDate").prop('disabled', true);

This is works 100% with bootstrap Datepicker

jQuery .live() vs .on() method for adding a click event after loading dynamic html

If you want the click handler to work for an element that gets loaded dynamically, then you set the event handler on a parent object (that does not get loaded dynamically) and give it a selector that matches your dynamic object like this:

$('#parent').on("click", "#child", function() {});

The event handler will be attached to the #parent object and anytime a click event bubbles up to it that originated on #child, it will fire your click handler. This is called delegated event handling (the event handling is delegated to a parent object).

It's done this way because you can attach the event to the #parent object even when the #child object does not exist yet, but when it later exists and gets clicked on, the click event will bubble up to the #parent object, it will see that it originated on #child and there is an event handler for a click on #child and fire your event.

How To Raise Property Changed events on a Dependency Property?

I think the OP is asking the wrong question. The code below will show that it not necessary to manually raise the PropertyChanged EVENT from a dependency property to achieve the desired result. The way to do it is handle the PropertyChanged CALLBACK on the dependency property and set values for other dependency properties there. The following is a working example. In the code below, MyControl has two dependency properties - ActiveTabInt and ActiveTabString. When the user clicks the button on the host (MainWindow), ActiveTabString is modified. The PropertyChanged CALLBACK on the dependency property sets the value of ActiveTabInt. The PropertyChanged EVENT is not manually raised by MyControl.

MainWindow.xaml.cs

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        ActiveTabString = "zero";
    }

    private string _ActiveTabString;
    public string ActiveTabString
    {
        get { return _ActiveTabString; }
        set
        {
            if (_ActiveTabString != value)
            {
                _ActiveTabString = value;
                RaisePropertyChanged("ActiveTabString");
            }
        }
    }

    private int _ActiveTabInt;
    public int ActiveTabInt
    {
        get { return _ActiveTabInt; }
        set
        {
            if (_ActiveTabInt != value)
            {
                _ActiveTabInt = value;
                RaisePropertyChanged("ActiveTabInt");
            }
        }
    }

    #region INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ActiveTabString = (ActiveTabString == "zero") ? "one" : "zero";
    }

}

public class MyControl : Control
{
    public static List<string> Indexmap = new List<string>(new string[] { "zero", "one" });


    public string ActiveTabString
    {
        get { return (string)GetValue(ActiveTabStringProperty); }
        set { SetValue(ActiveTabStringProperty, value); }
    }

    public static readonly DependencyProperty ActiveTabStringProperty = DependencyProperty.Register(
        "ActiveTabString",
        typeof(string),
        typeof(MyControl), new FrameworkPropertyMetadata(
            null,
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
            ActiveTabStringChanged));


    public int ActiveTabInt
    {
        get { return (int)GetValue(ActiveTabIntProperty); }
        set { SetValue(ActiveTabIntProperty, value); }
    }
    public static readonly DependencyProperty ActiveTabIntProperty = DependencyProperty.Register(
        "ActiveTabInt",
        typeof(Int32),
        typeof(MyControl), new FrameworkPropertyMetadata(
            new Int32(),
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));


    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));

    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
    }


    private static void ActiveTabStringChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        MyControl thiscontrol = sender as MyControl;

        if (Indexmap[thiscontrol.ActiveTabInt] != thiscontrol.ActiveTabString)
            thiscontrol.ActiveTabInt = Indexmap.IndexOf(e.NewValue.ToString());

    }
}

MainWindow.xaml

    <StackPanel Orientation="Vertical">
    <Button Content="Change Tab Index" Click="Button_Click" Width="110" Height="30"></Button>
    <local:MyControl x:Name="myControl" ActiveTabInt="{Binding ActiveTabInt, Mode=TwoWay}" ActiveTabString="{Binding ActiveTabString}"></local:MyControl>
</StackPanel>

App.xaml

<Style TargetType="local:MyControl">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:MyControl">
                    <TabControl SelectedIndex="{Binding ActiveTabInt, Mode=TwoWay}">
                        <TabItem Header="Tab Zero">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                        <TabItem Header="Tab One">
                            <TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
                        </TabItem>
                    </TabControl>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

JavaScript function in href vs. onclick

First, having the url in href is best because it allows users to copy links, open in another tab, etc.

In some cases (e.g. sites with frequent HTML changes) it is not practical to bind links every time there is an update.

Typical Bind Method

Normal link:

<a href="https://www.google.com/">Google<a/>

And something like this for JS:

$("a").click(function (e) {
    e.preventDefault();
    var href = $(this).attr("href");
    window.open(href);
    return false;
});

The benefits of this method are clean separation of markup and behavior and doesn't have to repeat the function calls in every link.

No Bind Method

If you don't want to bind every time, however, you can use onclick and pass in the element and event, e.g.:

<a href="https://www.google.com/" onclick="return Handler(this, event);">Google</a>

And this for JS:

function Handler(self, e) {
    e.preventDefault();
    var href = $(self).attr("href");
    window.open(href);
    return false;
}

The benefit to this method is that you can load in new links (e.g. via AJAX) whenever you want without having to worry about binding every time.

How does Subquery in select statement work in oracle

In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.

Append a dictionary to a dictionary

You can do

orig.update(extra)

or, if you don't want orig to be modified, make a copy first:

dest = dict(orig)  # or orig.copy()
dest.update(extra)

Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,

>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}

Group by month and year in MySQL

This is how I do it:

GROUP BY  EXTRACT(YEAR_MONTH FROM t.summaryDateTime);

COUNT DISTINCT with CONDITIONS

You can try this:

select
  count(distinct tag) as tag_count,
  count(distinct (case when entryId > 0 then tag end)) as positive_tag_count
from
  your_table_name;

The first count(distinct...) is easy. The second one, looks somewhat complex, is actually the same as the first one, except that you use case...when clause. In the case...when clause, you filter only positive values. Zeros or negative values would be evaluated as null and won't be included in count.

One thing to note here is that this can be done by reading the table once. When it seems that you have to read the same table twice or more, it can actually be done by reading once, in most of the time. As a result, it will finish the task a lot faster with less I/O.

Avoiding NullPointerException in Java

Another alternative to the != null check is (if you can't get rid of it design-wise):

Optional.ofNullable(someobject).ifPresent(someobject -> someobject.doCalc());

or

Optional.ofNullable(someobject).ifPresent(SomeClass::doCalc);

With SomeClass being someobject's type.

You can't get a return value back from doCalc() though, so only useful for void methods.

How can I get the actual video URL of a YouTube live stream?

This URL return to player actual video_id

https://www.youtube.com/embed/live_stream?channel=UCkA21M22vGK9GtAvq3DvSlA

Where UCkA21M22vGK9GtAvq3DvSlA is your channel id. You can find it inside YouTube account on "My Channel" link.

Fragment Inside Fragment

You can add FrameLayout to the fragment and replace it with another fragment when it initializes.

This way , you could consider the other fragment to be inside the first fragment.

Docker and securing passwords

The issue 13490 "Secrets: write-up best practices, do's and don'ts, roadmap" just got a new update in Sept. 2020, from Sebastiaan van Stijn:

Build time secrets are now possible when using buildkit as builder; see the blog post "Build secrets and SSH forwarding in Docker 18.09", Nov. 2018, from Tõnis Tiigi.

The documentation is updated: "Build images with BuildKit"

The RUN --mount option used for secrets will graduate to the default (stable) Dockerfile syntax soon.

That last part is new (Sept. 2020)

New Docker Build secret information

The new --secret flag for docker build allows the user to pass secret information to be used in the Dockerfile for building docker images in a safe way that will not end up stored in the final image.

id is the identifier to pass into the docker build --secret.
This identifier is associated with the RUN --mount identifier to use in the Dockerfile.
Docker does not use the filename of where the secret is kept outside of the Dockerfile, since this may be sensitive information.

dst renames the secret file to a specific file in the Dockerfile RUN command to use.

For example, with a secret piece of information stored in a text file:

$ echo 'WARMACHINEROX' > mysecret.txt

And with a Dockerfile that specifies use of a BuildKit frontend docker/dockerfile:1.0-experimental, the secret can be accessed.

For example:

# syntax = docker/dockerfile:1.0-experimental
FROM alpine

# shows secret from default secret location:
RUN --mount=type=secret,id=mysecret cat /run/secrets/mysecret

# shows secret from custom secret location:
RUN --mount=type=secret,id=mysecret,dst=/foobar cat /foobar

This Dockerfile is only to demonstrate that the secret can be accessed. As you can see the secret printed in the build output. The final image built will not have the secret file:

$ docker build --no-cache --progress=plain --secret id=mysecret,src=mysecret.txt .
...
#8 [2/3] RUN --mount=type=secret,id=mysecret cat /run/secrets/mysecret
#8       digest: sha256:5d8cbaeb66183993700828632bfbde246cae8feded11aad40e524f54ce7438d6
#8         name: "[2/3] RUN --mount=type=secret,id=mysecret cat /run/secrets/mysecret"
#8      started: 2018-08-31 21:03:30.703550864 +0000 UTC
#8 1.081 WARMACHINEROX
#8    completed: 2018-08-31 21:03:32.051053831 +0000 UTC
#8     duration: 1.347502967s
#9 [3/3] RUN --mount=type=secret,id=mysecret,dst=/foobar cat /foobar
#9       digest: sha256:6c7ebda4599ec6acb40358017e51ccb4c5471dc434573b9b7188143757459efa
#9         name: "[3/3] RUN --mount=type=secret,id=mysecret,dst=/foobar cat /foobar"
#9      started: 2018-08-31 21:03:32.052880985 +0000 UTC
#9 1.216 WARMACHINEROX
#9    completed: 2018-08-31 21:03:33.523282118 +0000 UTC
#9     duration: 1.470401133s
...

Disable spell-checking on HTML textfields

Update: As suggested by a commenter (additional credit to How can I disable the spell checker on text inputs on the iPhone), use this to handle all desktop and mobile browsers.

<tag autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"/>

Original answer: Javascript cannot override user settings, so unless you use another mechanism other than textfields, this is not (or shouldn't be) possible.

How do I use the JAVA_OPTS environment variable?

Actually, you can, even though accepted answer saying that you can't.

There is a _JAVA_OPTIONS environment variable, more about it here

How to clear exisiting dropdownlist items when its content changes?

Please use the following

ddlCity.Items.Clear();

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

First, sudo pip install 'package-name' means nothing it will return

sudo: pip: command not found

You get the Permission denied, you shouldn't use pip install as root anyway. You can just install the packages into your own user like mentionned above with

pip install 'package-name' --user

and it will work as you intend. If you need it in any other user just run the same command and you'll be good to go.

How do I use extern to share variables between source files?

                 declare | define   | initialize |
                ----------------------------------

extern int a;    yes          no           no
-------------
int a = 2019;    yes          yes          yes
-------------
int a;           yes          yes          no
-------------

Declaration won't allocate memory (the variable must be defined for memory allocation) but the definition will. This is just another simple view on the extern keyword since the other answers are really great.

Show/hide forms using buttons and JavaScript

Would you want the same form with different parts, showing each part accordingly with a button?

Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters &laquo; and &raquo; just print respectively « and » which might be interesting for the previous and next button characters.

_x000D_
_x000D_
shows_form_part(1)_x000D_
_x000D_
/* this function shows form part [n] and hides the remaining form parts */_x000D_
function shows_form_part(n){_x000D_
  var i = 1, p = document.getElementById("form_part"+1);_x000D_
  while (p !== null){_x000D_
    if (i === n){_x000D_
      p.style.display = "";_x000D_
    }_x000D_
    else{_x000D_
      p.style.display = "none";_x000D_
    }_x000D_
    i++;_x000D_
    p = document.getElementById("form_part"+i);_x000D_
  }_x000D_
}_x000D_
_x000D_
/* this is called at the last step using info filled during the previous steps*/_x000D_
function calc_sum() {_x000D_
  var sum =_x000D_
    parseInt(document.getElementById("num1").value) +_x000D_
    parseInt(document.getElementById("num2").value) +_x000D_
    parseInt(document.getElementById("num3").value);_x000D_
_x000D_
  alert("The sum is: " + sum);_x000D_
}
_x000D_
<div id="form_part1">_x000D_
  Part 1<br>_x000D_
  <input type="number" value="1" id="num1"><br>_x000D_
  <button type="button" onclick="shows_form_part(2)">&raquo;</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part2">_x000D_
  Part 2<br>_x000D_
  <input type="number" value="2" id="num2"><br>_x000D_
  <button type="button" onclick="shows_form_part(1)">&laquo;</button>_x000D_
  <button type="button" onclick="shows_form_part(3)">&raquo;</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part3">_x000D_
  Part 3<br>_x000D_
  <input type="number" value="3" id="num3"><br>_x000D_
  <button type="button" onclick="shows_form_part(2)">&laquo;</button>_x000D_
  <button type="button" onclick="calc_sum()">Sum</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

tar: Error is not recoverable: exiting now

Try to get your archive using wget, I had the same issue when I was downloading archive through browser. Than I just copy archive link and in terminal use the command:

wget http://PATH_TO_ARCHIVE

Bloomberg BDH function with ISIN

I had the same problem. Here's what I figured out:

=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")

A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.

How can I express that two values are not equal to eachother?

If the class implements comparable, you could also do

int compRes = a.compareTo(b);
if(compRes < 0 || compRes > 0)
    System.out.println("not equal");
else
    System.out.println("equal);

doesn't use a !, though not particularly useful, or readable....

How to uninstall Ruby from /usr/local?

It's not a good idea to uninstall 1.8.6 if it's in /usr/bin. That is owned by the OS and is expected to be there.

If you put /usr/local/bin in your PATH before /usr/bin then things you have installed in /usr/local/bin will be found before any with the same name in /usr/bin, effectively overwriting or updating them, without actually doing so. You can still reach them by explicitly using /usr/bin in your #! interpreter invocation line at the top of your code.

@Anurag recommended using RVM, which I'll second. I use it to manage 1.8.7 and 1.9.1 in addition to the OS's 1.8.6.

curl: (6) Could not resolve host: application

In my case, it was a missing line break that added unneeded parameters due to a bad copy and paste.

I followed a guide at https://pytorch.org/docs/stable/notes/windows.html#include-optional-components which looks like this when you copy it right here without any editing:

REM Make sure you have 7z and curl installed.

REM Download MKL files

curl https://s3.amazonaws.com/ossci-windows/mkl_2020.0.166.7z -k -O 7z x -aoa mkl_2020.0.166.7z -omkl

Output:

C:\Users\Admin>curl "https://s3.amazonaws.com/ossci-windows/mkl_2020.0.166.7z" -k -O 7z x
-aoa mkl_2020.0.166.7z -omkl   
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                               Dload  Upload   Total   Spent    Left  Speed 
100  103M  100  103M  0     0  5063k      0  0:00:21  0:00:21 --:--:-- 5629k
0     0    0     0    0     0      0      0 --:--:--  0:00:01 --:--:--     0curl: (6) Could not resolve host: 7z
0     0    0     0    0     0      0      0 --:--:--  0:00:01 --:--:--     0curl: (6) Could not resolve host: x 
curl: (6) Could not resolve host: mkl_2020.0.166.7z

There is actually a line break before "7z", with "7z" as the executable (and before, in addition to adding curl to your user PATH, you need to add 7z to the user PATH as well, for example with setx PATH "%PATH%;C:\Program Files\7-Zip\"):

REM Download MKL files

curl https://s3.amazonaws.com/ossci-windows/mkl_2020.0.166.7z -k -O

7z x -aoa mkl_2020.0.166.7z -omkl

Get mouse wheel events in jQuery?

If using mentioned jquery mousewheel plugin, then what about to use the 2nd argument of event handler function - delta:

$('#my-element').on('mousewheel', function(event, delta) {
    if(delta > 0) {
    console.log('scroll up');
    } 
    else {
    console.log('scroll down');
    }
});

VBoxManage: error: Failed to create the host-only adapter

$sudo /Library/StartupItems/VirtualBox/VirtualBox restart

Worked great for me on Mac. This normally happens when I shut down my computer without running

$vagrant suspend

JavaScript blob filename without link

window.location.assign did not work for me. it downloads fine but downloads without an extension for a CSV file on Windows platform. The following worked for me.

    var blob = new Blob([csvString], { type: 'text/csv' });
    //window.location.assign(window.URL.createObjectURL(blob));
    var link = window.document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    // Construct filename dynamically and set to link.download
    link.download = link.href.split('/').pop() + '.' + extension; 
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

c# open a new form then close the current form?

                     this.Visible = false;
                        //or                         // will make LOgin Form invisivble
                        //this.Enabled = false;
                         //  or
                       // this.Hide(); 



                        Form1 form1 = new Form1();
                        form1.ShowDialog();

                        this.Dispose();

IntelliJ: Working on multiple projects

Step 1: Open "Maven Projects"

enter image description here

Step 2: Select the project you want to import:

enter image description here

Display names of all constraints for a table in Oracle SQL

Use either of the two commands below. Everything must be in uppercase. The table name must be wrapped in quotation marks:

--SEE THE CONSTRAINTS ON A TABLE
SELECT COLUMN_NAME, CONSTRAINT_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME = 'TBL_CUSTOMER';

--OR FOR LESS DETAIL
SELECT CONSTRAINT_NAME FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'TBL_CUSTOMER';

MySQL Error 1093 - Can't specify target table for update in FROM clause

The simplest way to do this is use a table alias when you are referring parent query table inside the sub query.

Example :

insert into xxx_tab (trans_id) values ((select max(trans_id)+1 from xxx_tab));

Change it to:

insert into xxx_tab (trans_id) values ((select max(P.trans_id)+1 from xxx_tab P));

How to pass boolean values to a PowerShell script from a command prompt

It appears that powershell.exe does not fully evaluate script arguments when the -File parameter is used. In particular, the $false argument is being treated as a string value, in a similar way to the example below:

PS> function f( [bool]$b ) { $b }; f -b '$false'
f : Cannot process argument transformation on parameter 'b'. Cannot convert value 
"System.String" to type "System.Boolean", parameters of this type only accept 
booleans or numbers, use $true, $false, 1 or 0 instead.
At line:1 char:36
+ function f( [bool]$b ) { $b }; f -b <<<<  '$false'
    + CategoryInfo          : InvalidData: (:) [f], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,f

Instead of using -File you could try -Command, which will evaluate the call as script:

CMD> powershell.exe -NoProfile -Command .\RunScript.ps1 -Turn 1 -Unify $false
Turn: 1
Unify: False

As David suggests, using a switch argument would also be more idiomatic, simplifying the call by removing the need to pass a boolean value explicitly:

CMD> powershell.exe -NoProfile -File .\RunScript.ps1 -Turn 1 -Unify
Turn: 1
Unify: True

Recover unsaved SQL query scripts

Go to SSMS >> Tools >> Options >> Environment >> AutoRecover

There are two different settings:

1) Save AutoRecover Information Every Minutes

This option will save the SQL Query file at certain interval. Set this option to minimum value possible to avoid loss. If you have set this value to 5, in the worst possible case, you can lose last 5 minutes of the work.

2) Keep AutoRecover Information for Days

This option will preserve the AutoRecovery information for specified days. Though, I suggest in case of accident open SQL Server Management Studio right away and recover your file. Do not procrastinate this important task for future dates.

How to check java bit version on Linux?

Go to this JVM online test and run it.

Then check the architecture displayed: x86_64 means you have the 64bit version installed, otherwise it's 32bit.

Codesign error: Provisioning profile cannot be found after deleting expired profile

To achieve Brad's solution entirely in Terminal, use these commands

  1. cd [Xcode project parent]
  2. vi [Xcode project name].xcodeproj/project.pbxproj
  3. /[offending provisioning profile] [Enter]
  4. dd - delete the entire line
  5. Press n until no more are found
  6. Ctrl+x to save and close

ClassNotFoundException: org.slf4j.LoggerFactory

You'll need to download SLF4J's jars from the official site as either a zip (v1.7.4) or tar.gz (v1.7.4)

The download contains multiple jars based on how you want to use SLF4J. If you're simply trying to resolve the requirement of some other library (GWT, I assume) and don't really care about using SLF4J correctly, then I would probably pick the slf4j-api-1.7.4.jar since the Simple jar suggested by another answer does not contain, to my knowledge, the specific class you're looking for.

Create a List that contain each Line of a File

It's a lot easier than that:

List = open("filename.txt").readlines()

This returns a list of each line in the file.

How do I check if a Key is pressed on C++

There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.

Solution for linux and other posix compliant systems:

Here, for Morgan Mattews's code provide kbhit() functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.

Solution for windows:

For windows, Microsoft offers _kbhit()

How to make a gap between two DIV within the same column

you can use $nbsp; for a single space, if you like just using single allows you single space instead of using creating own class

    <div id="bulkOptionContainer" class="col-xs-4">
        <select class="form-control" name="" id="">
            <option value="">Select Options</option>
            <option value="">Published</option>
            <option value="">Draft</option>
            <option value="">Delete</option>
        </select>
    </div>

    <div class="col-xs-4">

        <input type="submit" name="submit" class="btn btn-success " value="Apply">
         &nbsp;
        <a class="btn btn-primary" href="add_posts.php">Add post</a>

    </div>


</form>

CLICK ON IMAGE

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

Check /etc/phpmyadmin/config-db.php file

  1. Go to terminal
  2. run vi /etc/phpmyadmin/config-db.php
  3. check the information
  4. Hit Ctrl + X
  5. Try login to phpmyadmin again through the web using the information from the config file.

File being used by another process after using File.Create()

I think I know the reason for this exception. You might be running this code snippet in multiple threads.

how to open *.sdf files?

In addition to the methods described by @ctacke, you can also open SQL Server Compact Edition databases with SQL Server Management Studio. You'll need SQL Server 2008 to open SQL CE 3.5 databases.

Escape string Python for MySQL

{!a} applies ascii() and hence escapes non-ASCII characters like quotes and even emoticons. Here is an example

cursor.execute("UPDATE skcript set author='{!a}',Count='{:d}' where url='{!s}'".format(authors),leng,url))

Python3 docs

git: fatal: Could not read from remote repository

If you use Gitlab than you might need to log in and accept Gitlab new terms, before you try to pull or push.

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

curl Failed to connect to localhost port 80

In my case, the file ~/.curlrc had a wrong proxy configured.

JavaScript for handling Tab Key press

You should be able to do this with the keyup event. To be specific, event.target should point at the selected element and event.target.href will give you the href-value of that element. See mdn for more information.

The following code is jQuery, but apart from the boilerplate code, the rest is the same in pure javascript. This is a keyup handler that is bound to every link tag.

$('a').on( 'keyup', function( e ) {
    if( e.which == 9 ) {
        console.log( e.target.href );
    }
} );

jsFiddle: http://jsfiddle.net/4PqUF/

Why doesn't java.util.Set have get(int index)?

To get element in a Set, i use to following one:

public T getElement(Set<T> set, T element) {
T result = null;
if (set instanceof TreeSet<?>) {
    T floor = ((TreeSet<T>) set).floor(element);
    if (floor != null && floor.equals(element))
    result = floor;
} else {
    boolean found = false;
    for (Iterator<T> it = set.iterator(); !found && it.hasNext();) {
    if (true) {
        T current = it.next();
        if (current.equals(element)) {
        result = current;
        found = true;
        }
    }
    }
}
return result;
}

File Upload without Form

All answers here are still using the FormData API. It is like a "multipart/form-data" upload without a form. You can also upload the file directly as content inside the body of the POST request using xmlHttpRequest like this:

var xmlHttpRequest = new XMLHttpRequest();

var file = ...file handle...
var fileName = ...file name...
var target = ...target...
var mimeType = ...mime type...

xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
xmlHttpRequest.send(file);

Content-Type and Content-Disposition headers are used for explaining what we are sending (mime-type and file name).

I posted similar answer also here.

Linq select to new object

Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site

var x = from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() };

forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary

    // fordictionary 
  var x = (from t in types  group t by t.Type
     into grp    
     select new { type = grp.key, count = grp.Count() })
   .ToDictionary( t => t.type, t => t.count); 

   //for stringbuilder not sure for this 
  var x = from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() };
  StringBuilder MyStringBuilder = new StringBuilder();

  foreach (var res in x)
  {
       //: is separator between to object
       MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
  }
  Console.WriteLine(MyStringBuilder.ToString());   

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

I think it makes clear with the namespace, as we can create our own attributes and if the user specified attribute is the same as the Android one it avoid the conflict of the namespace.

TransactionRequiredException Executing an update/delete query

I received this exception when trying to run a bulk UPDATE query in a non-JTA (i.e. resource-local) entity manager in Java SE. I had simply forgotten to wrap my JPQL code in

em.getTransaction().begin();

and

em.getTransaction().commit();

Manage toolbar's navigation and back button from fragment in android

(Kotlin) In the activity hosting the fragment(s):

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
    when (item.itemId) {
        android.R.id.home -> {
            onBackPressed()
            return true
        }
    }
    return super.onOptionsItemSelected(item)
}

I have found that when I add fragments to a project, they show the action bar home button by default, to remove/disable it put this in onViewCreated() (use true to enable it if it is not showing):

val actionBar = this.requireActivity().actionBar
    actionBar?.setDisplayHomeAsUpEnabled(false)

How to clear all inputs, selects and also hidden fields in a form using jQuery?

You can use the reset() method:

$('#myform')[0].reset();

or without jQuery:

document.getElementById('myform').reset();

where myform is the id of the form containing the elements you want to be cleared.

You could also use the :input selector if the fields are not inside a form:

$(':input').val('');

What is the difference between a web API and a web service?

A web service typically offers a WSDL from which you can create client stubs automatically. Web Services are based on the SOAP protocol. ASP.NET Web API is a newer Microsoft framework which helps you to build REST based interfaces. The response can be either JSON or XML, but there is no way to generate clients automatically because Web API does not offer a service description like the WSDL from Web Services. So it depends on your requirements which one of the techniques you want to use. Perhaps even WCF fits your requirements better, just look at the MSDN documentation.

Character reading from file in Python

This is Pythons way do show you unicode encoded strings. But i think you should be able to print the string on the screen or write it into a new file without any problems.

>>> test = u"I don\u2018t like this"
>>> test
u'I don\u2018t like this'
>>> print test
I don‘t like this

How do I import a namespace in Razor View Page?

In ASP.NET MVC 3 Preview1 you can import a namespace on all your razor views with this code in Global.asax.cs

Microsoft.WebPages.Compilation.CodeGeneratorSettings.AddGlobalImport("Namespace.Namespace");

I hope in RTM this gets done through Web.config section.

How to normalize an array in NumPy to a unit vector?

If you have multidimensional data and want each axis normalized to its max or its sum:

def normalize(_d, to_sum=True, copy=True):
    # d is a (n x dimension) np array
    d = _d if not copy else np.copy(_d)
    d -= np.min(d, axis=0)
    d /= (np.sum(d, axis=0) if to_sum else np.ptp(d, axis=0))
    return d

Uses numpys peak to peak function.

a = np.random.random((5, 3))

b = normalize(a, copy=False)
b.sum(axis=0) # array([1., 1., 1.]), the rows sum to 1

c = normalize(a, to_sum=False, copy=False)
c.max(axis=0) # array([1., 1., 1.]), the max of each row is 1

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

How to get HTTP Response Code using Selenium WebDriver

It is not possible to get HTTP Response code by using Selenium WebDriver directly. The code can be got by using Java code and that can be used in Selenium WebDriver.

To get HTTP Response code by java:

public static int getResponseCode(String urlString) throws MalformedURLException, IOException{
    URL url = new URL(urlString);
    HttpURLConnection huc = (HttpURLConnection)url.openConnection();
    huc.setRequestMethod("GET");
    huc.connect();
    return huc.getResponseCode();
}

Now you can write your Selenium WebDriver code as below:

private static int statusCode;
public static void main(String... args) throws IOException{
    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("https://www.google.com/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    List<WebElement> links = driver.findElements(By.tagName("a"));
    for(int i = 0; i < links.size(); i++){
        if(!(links.get(i).getAttribute("href") == null) && !(links.get(i).getAttribute("href").equals(""))){
            if(links.get(i).getAttribute("href").contains("http")){
                statusCode= getResponseCode(links.get(i).getAttribute("href").trim());
                if(statusCode == 403){
                    System.out.println("HTTP 403 Forbidden # " + i + " " + links.get(i).getAttribute("href"));
                }
            }
        }   
    }   
}

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

It is permission issue in my case the task scheduler has a user which doesn't have permission on the server in which the database is present.

Consistency of hashCode() on a Java string

I found something about JDK 1.0 and 1.1 and >= 1.2:

In JDK 1.0.x and 1.1.x the hashCode function for long Strings worked by sampling every nth character. This pretty well guaranteed you would have many Strings hashing to the same value, thus slowing down Hashtable lookup. In JDK 1.2 the function has been improved to multiply the result so far by 31 then add the next character in sequence. This is a little slower, but is much better at avoiding collisions. Source: http://mindprod.com/jgloss/hashcode.html

Something different, because you seem to need a number: How about using CRC32 or MD5 instead of hashcode and you are good to go - no discussions and no worries at all...

Deleting specific rows from DataTable

Or just convert a DataTable Row collection to a list:

foreach(DataRow dr in dtPerson.Rows.ToList())
{
    if(dr["name"].ToString()=="Joe")
    dr.Delete();
}

How to make a Python script run like a service or daemon in Linux

cron is clearly a great choice for many purposes. However it doesn't create a service or daemon as you requested in the OP. cron just runs jobs periodically (meaning the job starts and stops), and no more often than once / minute. There are issues with cron -- for example, if a prior instance of your script is still running the next time the cron schedule comes around and launches a new instance, is that OK? cron doesn't handle dependencies; it just tries to start a job when the schedule says to.

If you find a situation where you truly need a daemon (a process that never stops running), take a look at supervisord. It provides a simple way to wrapper a normal, non-daemonized script or program and make it operate like a daemon. This is a much better way than creating a native Python daemon.

What are the most common naming conventions in C?

Here's an (apparently) uncommon one, which I've found useful: module name in CamelCase, then an underscore, then function or file-scope name in CamelCase. So for example:

Bluetooth_Init()
CommsHub_Update()
Serial_TxBuffer[]

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

You can use white-space: nowrap; to define this behaviour:

// HTML:

_x000D_
_x000D_
.nowrap {_x000D_
  white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
      <span class="nowrap">How do I wrap this line of text</span>_x000D_
      <span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
    </p>
_x000D_
_x000D_
_x000D_

// CSS:
.nowrap {
  white-space: nowrap ;
}

Check file uploaded is in csv format

the mime type might not be text/csv some systems can read/save them different. (for example sometimes IE sends .csv files as application/vnd.ms-excel) so you best bet would be to build an array of allowed values and test against that, then find all possible values to test against.

$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(in_array($_FILES['file']['type'],$mimes)){
  // do something
} else {
  die("Sorry, mime type not allowed");
}

if you wished you could add a further check if mime is returned as text/plain you could run a preg_match to make sure it has enough commas in it to be a csv.

StringStream in C#

You have a number of options:

One is to not use streams, but use the TextWriter

   void Print(TextWriter writer) 
   {
   }

   void Main() 
  {
    var textWriter = new StringWriter();
    Print(writer);
    string myString = textWriter.ToString();
   }

It's likely that TextWriter is the appropriate level of abstraction for your print function. Streams are aimed at writing binary data, while TextWriter works at a higher abstraction level, specifically geared towards outputting strings.

If your motivation is that you also want your Print function to write to files, you can get a text writer from a filestream as well.

void Print(TextWriter writer) 
{
}

void PrintToFile(string filePath) 
{
     using(var textWriter = new StreamWriter(filePath))
     {
         Print(writer);
     }
}

If you REALLY want a stream you can look at MemoryStream.

What is the difference between match_parent and fill_parent?

Functionally no difference, Google just changed the name from fill_parent to match_parent, from API level 8 (Android 2.2). FILL_PARENT is still available for compatibility reason.

LayoutParams.FILL_PARENT and LayoutParams.MATCH_PARENT both have value -1. Not sure what tempted google to change from Fill Parent to Match Parent :)

Since most of the phones are >= Android 2.2 .. you should use Match Parent for future compatibility... not sure when they will discontinue the older Fill Parent constant!

how to set auto increment column with sql developer

You can make auto increment in SQL Modeler. In column properties window Click : General then Tick the box of Auto Increment. After that the auto increment window will be enabled for you.

How to upload (FTP) files to server in a bash script?

if you want to use it inside a 'for' to copy the last generated files for a every-day bacakup...

j=0  
var="`find /backup/path/ -name 'something*' -type f -mtime -1`"  
#we have in $var some files with last day change date

for i in $var  
  do  
  j=$(( $j + 1 ))  
  dirname="`dirname $i`"  
  filename="`basename $i`"  
  /usr/bin/ftp -in >> /tmp/ftp.good 2>> /tmp/ftp.bad << EOF  
    open 123.456.789.012  
    user user_name passwd  
    bin  
    lcd $dirname  
    put $filename  
    quit  
  EOF      #end of ftp  
done       #end of for iteration

What's the strangest corner case you've seen in C# or .NET?

The scoping in c# is truly bizarre at times. Lets me give you one example:

if (true)
{
   OleDbCommand command = SQLServer.CreateCommand();
}

OleDbCommand command = SQLServer.CreateCommand();

This fails to compile, because command is redeclared? There are some interested guesswork as to why it works that way in this thread on stackoverflow and in my blog.

How to parse XML to R data frame

Use xpath more directly for both performance and clarity.

time_path <- "//start-valid-time"
temp_path <- "//temperature[@type='hourly']/value"

df <- data.frame(
    latitude=data[["number(//point/@latitude)"]],
    longitude=data[["number(//point/@longitude)"]],
    start_valid_time=sapply(data[time_path], xmlValue),
    hourly_temperature=as.integer(sapply(data[temp_path], as, "integer"))

leading to

> head(df, 2)
  latitude longitude          start_valid_time hourly_temperature
1    29.81    -82.42 2014-02-14T18:00:00-05:00                 60
2    29.81    -82.42 2014-02-14T19:00:00-05:00                 55

Virtual network interface in Mac OS X

The loopback adapter is always up.

ifconfig lo0 alias 172.16.123.1 will add an alias IP 172.16.123.1 to the loopback adapter

ifconfig lo0 -alias 172.16.123.1 will remove it

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Yes, use the commercial but inexpensive SSMS Tools Pack addin which has a nifty "Generate Insert statements from resultsets, tables or database" feature

Laravel Eloquent get results grouped by days

You could also solve this problem in following way:

$totalView =  View::select(DB::raw('Date(read_at) as date'), DB::raw('count(*) as Views'))
        ->groupBy(DB::raw('Date(read_at)'))
        ->orderBy(DB::raw('Date(read_at)'))
        ->get();

How does ifstream's eof() work?

-1 is get's way of saying you've reached the end of file. Compare it using the std::char_traits<char>::eof() (or std::istream::traits_type::eof()) - avoid -1, it's a magic number. (Although the other one is a bit verbose - you can always just call istream::eof)

The EOF flag is only set once a read tries to read past the end of the file. If I have a 3 byte file, and I only read 3 bytes, EOF is false, because I've not tried to read past the end of the file yet. While this seems confusing for files, which typically know their size, EOF is not known until a read is attempted on some devices, such as pipes and network sockets.

The second example works as inf >> foo will always return inf, with the side effect of attempt to read something and store it in foo. inf, in an if or while, will evaluate to true if the file is "good": no errors, no EOF. Thus, when a read fails, inf evaulates to false, and your loop properly aborts. However, take this common error:

while(!inf.eof())  // EOF is false here
{
    inf >> x;      // read fails, EOF becomes true, x is not set
    // use x       // we use x, despite our read failing.
}

However, this:

while(inf >> x)  // Attempt read into x, return false if it fails
{
    // will only be entered if read succeeded.
}

Which is what we want.

EL access a map value by Integer key

Just another helpful hint in addition to the above comment would be when you have a string value contained in some variable such as a request parameter. In this case, passing this in will also result in JSTL keying the value of say "1" as a sting and as such no match being found in a Map hashmap.

One way to get around this is to do something like this.

<c:set var="longKey" value="${param.selectedIndex + 0}"/>

This will now be treated as a Long object and then has a chance to match an object when it is contained withing the map Map or whatever.

Then, continue as usual with something like

${map[longKey]}

DateTime.Compare how to check if a date is less than 30 days old?

Try this instead

if ( (expiryDate - DateTime.Now ).TotalDays < 30 ) { 
  matchFound = true;
}

Embed a PowerPoint presentation into HTML

besides, if you save ppt as .pps format using microsoft powerpoint, you can use the following code:

<iframe src="file.pps" width="800px" heigt="600px"></iframe>

Another common way to do it is to convert ppt/doc to pdf,

then use swftool(http://www.swftools.org) to convert it to swf

finally, take FlexPaper(http://flexpaper.devaldi.com) as document viewer.

Array as session variable

session_start();          //php part
$_SESSION['student']=array();
$student_name=$_POST['student_name']; //student_name form field name
$student_city=$_POST['city_id'];   //city_id form field name
array_push($_SESSION['student'],$student_name,$student_city);   
//print_r($_SESSION['student']);


<table class="table">     //html part
    <tr>
      <th>Name</th>
      <th>City</th>
    </tr>

    <tr>
     <?php for($i = 0 ; $i < count($_SESSION['student']) ; $i++) {
     echo '<td>'.$_SESSION['student'][$i].'</td>';
     }  ?>
    </tr>
</table>

How to delete a file or folder?

shutil.rmtree is the asynchronous function, so if you want to check when it complete, you can use while...loop

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')

How do I send an HTML email?

I found this way not sure it works for all the CSS primitives

By setting the header property "Content-Type" to "text/html"

mimeMessage.setHeader("Content-Type", "text/html");

now I can do stuff like

mimeMessage.setHeader("Content-Type", "text/html");

mimeMessage.setText ("`<html><body><h1 style =\"color:blue;\">My first Header<h1></body></html>`")

Regards

How to concat a string to xsl:value-of select="...?

You can use the rather sensibly named xpath function called concat here

<a>
   <xsl:attribute name="href">
      <xsl:value-of select="concat('myText:', /*/properties/property[@name='report']/@value)" />
   </xsl:attribute>
</a>  

Of course, it doesn't have to be text here, it can be another xpath expression to select an element or attribute. And you can have any number of arguments in the concat expression.

Do note, you can make use of Attribute Value Templates (represented by the curly braces) here to simplify your expression

<a href="{concat('myText:', /*/properties/property[@name='report']/@value)}"></a>

Help with packages in java - import does not work

Just add classpath entry ( I mean your parent directory location) under System Variables and User Variables menu ... Follow : Right Click My Computer>Properties>Advanced>Environment Variables

dispatch_after - GCD in Swift?

In Swift 5, use in the below:

 DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: closure) 

// time gap, specify unit is second
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
            Singleton.shared().printDate()
        }
// default time gap is second, you can reduce it
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
          // just do it!
    }

What is a None value?

The book you refer to is clearly trying to greatly simplify the meaning of None. Python variables don't have an initial, empty state – Python variables are bound (only) when they're defined. You can't create a Python variable without giving it a value.

>>> print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> def test(x):
...   print(x)
... 
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 1 argument (0 given)
>>> def test():
...   print(x)
... 
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in test
NameError: global name 'x' is not defined

but sometimes you want to make a function mean different things depending on whether a variable is defined or not. You can create an argument with a default value of None:

>>> def test(x=None):
...   if x is None:
...     print('no x here')
...   else:
...     print(x)
... 
>>> test()
no x here
>>> test('x!')
x!

The fact that this value is the special None value is not terribly important in this case. I could've used any default value:

>>> def test(x=-1):
...   if x == -1:
...     print('no x here')
...   else:
...     print(x)
... 
>>> test()
no x here
>>> test('x!')
x!

…but having None around gives us two benefits:

  1. We don't have to pick a special value like -1 whose meaning is unclear, and
  2. Our function may actually need to handle -1 as a normal input.
>>> test(-1)
no x here

oops!

So the book is a little misleading mostly in its use of the word reset – assigning None to a name is a signal to a programmer that that value isn't being used or that the function should behave in some default way, but to reset a value to its original, undefined state you must use the del keyword:

>>> x = 3
>>> x
3
>>> del x
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

Converting Integers to Roman Numerals - Java

Here's the results of MY homework. It doesn't ensure the input is in the right range and I probably should be using StringBuilder (time I looked it up!) and isn't one single method. But if anyone is reading this far I'd appreciate both positive and negative feedback on it!

import java.util.Scanner;
    /**
     *Main() allows user input and tests 1-3999
     *toRoman() breaks the number down into digits and passes them to romanLogic()
     *romanLogic() converts each digit into a the numerals that represent it.
     */
    public class RomanNumerals
    {
        public static void main(String args[]){
            Scanner in = new Scanner(System.in);
            System.out.print("give us an integer < 4000: ");        
            System.out.println("the roman numeral version is: " + toRoman(in.nextInt()));
            for (int i = 1; i<=3999; i++){
                System.out.println(i +" === "+ toRoman(i));
            }
        }
        public static String toRoman(int i){
            String output = "";
            int digits = i%10;
            int tens = (i%100)/10;
            int hundreds = (i%1000)/100;
            int thousands = (i%10000)/1000;
            return (romanLogic(thousands, "M","","")+
                    romanLogic(hundreds,"C","D","M")+
                    romanLogic(tens,"X","L","C")+
                    romanLogic(digits,"I","V","X"));
        }
        public static String romanLogic(int i, String ones, String fives, String tens){
            String result = "";
            if (i == 0){
                return result;
            } else {
                if ((i>=4)&&(i<=8)){                
                    result += fives;
                }
                if (i==9){
                    result += tens;
                }
                if(i%5 < 4){
                    while(i%5 > 0){
                        result += ones;
                        i--;
                    }
                }
                if(i%5 == 4){
                    result = ones + result;
                }
            }
            return result;
        }    
    }

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

Use directions service of Google Maps API v3. It's basically the same as directions API, but nicely packed in Google Maps API which also provides convenient way to easily render the route on the map.

Information and examples about rendering the directions route on the map can be found in rendering directions section of Google Maps API v3 documentation.

PHP sessions default timeout

http://php.net/session.gc-maxlifetime

session.gc_maxlifetime = 1440
(1440 seconds = 24 minutes)

adding a datatable in a dataset

Just give any name to the DataTable Like:

DataTable dt = new DataTable();
dt = SecondDataTable.Copy();    
dt .TableName = "New Name";
DataSet.Tables.Add(dt );

Finding all the subsets of a set

An elegant recursive solution that corresponds to the best answer explanation above. The core vector operation is only 4 lines. credit to "Guide to Competitive Programming" book from Laaksonen, Antti.

// #include <iostream>
#include <vector>
using namespace std;

vector<int> subset;
void search(int k, int n) {
    if (k == n+1) {
    // process subset - put any of your own application logic
    // for (auto i : subset) cout<< i << " ";
    // cout << endl;
    }
    else {
        // include k in the subset
        subset.push_back(k);
        search(k+1, n);
        subset.pop_back();
        // don't include k in the subset
        search(k+1,n);
    }
}

int main() {
    // find all subset between [1,3]
    search(1, 3);
}

Adding +1 to a variable inside a function

You could also pass points to the function: Small example:

def test(points):
    addpoint = raw_input ("type ""add"" to add a point")
    if addpoint == "add":
        points = points + 1
    else:
        print "asd"
    return points;
if __name__ == '__main__':
    points = 0
    for i in range(10):
        points = test(points)
        print points

wget: unable to resolve host address `http'

I figured out what went wrong. In the proxy configuration of my box, an extra http:// got prefixed to "proxy server with http".

Example..

http://http://proxy.mycollege.com

and that has created problems. Corrected that, and it works perfectly.

Thanks @WhiteCoffee and @ChrisBint for your suggestions!

Django Multiple Choice Field / Checkbox Select Multiple

The profile choices need to be setup as a ManyToManyField for this to work correctly.

So... your model should be like this:

class Choices(models.Model):
  description = models.CharField(max_length=300)

class Profile(models.Model):
  user = models.ForeignKey(User, blank=True, unique=True, verbose_name='user')
  choices = models.ManyToManyField(Choices)

Then, sync the database and load up Choices with the various options you want available.

Now, the ModelForm will build itself...

class ProfileForm(forms.ModelForm):
  Meta:
    model = Profile
    exclude = ['user']

And finally, the view:

if request.method=='POST':
  form = ProfileForm(request.POST)
  if form.is_valid():
    profile = form.save(commit=False)
    profile.user = request.user
    profile.save()
else:
  form = ProfileForm()

return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))

It should be mentioned that you could setup a profile in a couple different ways, including inheritance. That said, this should work for you as well.

Good luck.

Using Python 3 in virtualenv

Python now comes with its own implementation of virtual environment, by the name of "venv". I would suggest using that, instead of virtualenv.

Quoting from venv - docs,

Deprecated since version 3.6: pyvenv was the recommended tool for creating virtual environments for Python 3.3 and 3.4, and is deprecated in Python 3.6.

Changed in version 3.5: The use of venv is now recommended for creating virtual environments.

For windows, to initiate venv on some project, open cmd:

python -m venv "c:\path\to\myenv"

(Would suggest using double quote around directory path if it contains any spaces. Ex: "C:/My Dox/Spaced Directory/Something")

Once venv is set up, you will see some new folders inside your project directory. One of them would be "Scripts".

To activate or invoke venv you need:

C:\> <venv>\Scripts\activate.bat

You can deactivate a virtual environment by typing “deactivate” in your shell. With this, you are now ready to install your project specific libraries, which will reside under the folder "Lib".

================================ Edit 1 ==================================== The scenario which will be discussed below is not what originally asked, just adding this in case someone use vscode with python extension

In case, you use vs code with its python extension, you might face an issue with its pylint which points to the global installation. In this case, pylint won't be able to see the modules that are installed in your virtual environment and hence will show errors while importing.

Here is a simple method to get past this.

cd Workspace\Scripts
.\Activate.ps1
code .

We are basically activating the environment first and then invoking vs-code so that pylint starts within the environment and can see all local packages.

Display date in dd/mm/yyyy format in vb.net

Try this.

 var dateAsString = DateTime.Now.ToString("dd/MM/yyyy");
// dateAsString = "09/07/2013"

and also check this link for more formatting data and time

AngularJS : Clear $watch

Some time your $watch is calling dynamically and it will create its instances so you have to call deregistration function before your $watch function

if(myWatchFun)
  myWatchFun(); // it will destroy your previous $watch if any exist
myWatchFun = $scope.$watch("abc", function () {});

Install an apk file from command prompt?

You can build on the command line with ant. See this guide.

Then, you can install it by using adb on the command line.

adb install -r MyApp.apk

The -r flag is to replace the existing application.

How do you create different variable names while in a loop?

I think the challenge here is not to call upon global()

I would personally define a list for your (dynamic) variables to be held and then append to it within a for loop. Then use a separate for loop to view each entry or even execute other operations.

Here is an example - I have a number of network switches (say between 2 and 8) at various BRanches. Now I need to ensure I have a way to determining how many switches are available (or alive - ping test) at any given branch and then perform some operations on them.

Here is my code:

import requests
import sys

def switch_name(branchNum):
    # s is an empty list to start with
    s = []
    #this FOR loop is purely for creating and storing the dynamic variable names in s
    for x in range(1,8,+1):
        s.append("BR" + str(branchNum) + "SW0" + str(x))

    #this FOR loop is used to read each of the switch in list s and perform operations on
    for i in s:
        print(i,"\n")
        # other operations can be executed here too for each switch (i) - like SSH in using paramiko and changing switch interface VLAN etc.


def main():  

    # for example's sake - hard coding the site code
    branchNum= "123"
    switch_name(branchNum)


if __name__ == '__main__':
    main()

Output is:

BR123SW01

BR123SW02

BR123SW03

BR123SW04

BR123SW05

BR123SW06

BR123SW07

How to get the second column from command output?

Use -F [field separator] to split the lines on "s:

awk -F '"' '{print $2}' your_input_file

or for input from pipe

<some_command> | awk -F '"' '{print $2}'

output:

A B
C
D

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

Datatable plugin solves the purpose best and allows us to export the HTML table data into Excel , PDF , TEXT. easily configurable.

Please find the complete example in below datatable reference link :

https://datatables.net/extensions/buttons/examples/html5/simple.html

(screenshot from datatable reference site) enter image description here

How to configure welcome file list in web.xml

Its based on from which file you are trying to access those files.

If it is in the same folder where your working project file is, then you can use just the file name. no need of path.

If it is in the another folder which is under the same parent folder of your working project file then you can use location like in the following /javascript/sample.js

In your example if you are trying to access your js file from your html file you can use the following location

../javascript/sample.js

the prefix../ will go to the parent folder of the file(Folder upward journey)

Install MySQL on Ubuntu without a password prompt

Use:

sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server

sudo mysql -h127.0.0.1 -P3306 -uroot -e"UPDATE mysql.user SET password = PASSWORD('yourpassword') WHERE user = 'root'"

How to test code dependent on environment variables using JUnit?

I think the cleanest way to do this is with Mockito.spy(). It's a bit more lightweight than creating a separate class to mock and pass around.

Move your environment variable fetching to another method:

@VisibleForTesting
String getEnvironmentVariable(String envVar) {
    return System.getenv(envVar);
}

Now in your unit test do this:

@Test
public void test() {
    ClassToTest classToTest = new ClassToTest();
    ClassToTest classToTestSpy = Mockito.spy(classToTest);
    Mockito.when(classToTestSpy.getEnvironmentVariable("key")).thenReturn("value");
    // Now test the method that uses getEnvironmentVariable
    assertEquals("changedvalue", classToTestSpy.methodToTest());
}

Looping through all rows in a table column, Excel-VBA

If this is in fact a ListObject table (Insert Table from the ribbon) then you can use the table's .DataBodyRange object to get the number of rows and columns. This ignores the header row.

Sub TableTest()

Dim tbl As ListObject
Dim tRows As Long
Dim tCols As Long

Set tbl = ActiveSheet.ListObjects("Table1")  '## modify to your table name.

With tbl.DataBodyRange
    tRows = .Rows.Count
    tCols = .Columns.Count
End With

MsgBox tbl.Name & " contains " & tRows & " rows and " & tCols & " columns.", vbInformation

End Sub

If you need to use the header row, instead of using tbl.DataBodyRange just use tbl.Range.

Highlight all occurrence of a selected word?

For example this plugIns:

Just search for under cursor in vimawesome.com

The key, as clagccs mentioned, is that the highlight does NOT conflict with your search: https://vim.fandom.com/wiki/Auto_highlight_current_word_when_idle

Screen-shot of how it does NOT conflict with search: enter image description here Notes:

  • vim-illuminate highlights by default, in my screen-shot I switched to underline
  • vim-illuminate highlights/underlines word under cursor by default, in my screen-shot I unset it
  • my colorschemes are very grey-ish. Check yours to customize it too.

What's the difference between ASCII and Unicode?

ASCII defines 128 characters, as Unicode contains a repertoire of more than 120,000 characters.

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

You may be an administrator on the workstation, but that means nothing to SQL Server. Your login has to be a member of the sysadmin role in order to perform the actions in question. By default, the local administrators group is no longer added to the sysadmin role in SQL 2008 R2. You'll need to login with something else (sa for example) in order to grant yourself the permissions.

Android: how to hide ActionBar on certain activities

Check for padding attribute if the issue still exists after changing theme.

Padding Issue creating a white space on top of fragment window / app window

Padding Issue creating a white space on top of fragment window / app window

Once you remove the padding - top value automatically the white space is removed.

How do I put all required JAR files in a library folder inside the final JAR file with Maven?

The executable packer maven plugin can be used for exactly that purpose: creating standalone java applications containing all dependencies as JAR files in a specific folder.

Just add the following to your pom.xml inside the <build><plugins> section (be sure to replace the value of mainClass accordingly):

<plugin>
    <groupId>de.ntcomputer</groupId>
    <artifactId>executable-packer-maven-plugin</artifactId>
    <version>1.0.1</version>
    <configuration>
        <mainClass>com.example.MyMainClass</mainClass>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>pack-executable-jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>

The built JAR file is located at target/<YourProjectAndVersion>-pkg.jar after you run mvn package. All of its compile-time and runtime dependencies will be included in the lib/ folder inside the JAR file.

Disclaimer: I am the author of the plugin.

How to find files recursively by file type and copy them to a directory while in ssh?

Something like this should work.

ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'

C++ Best way to get integer division and remainder

Sample code testing div() and combined division & mod. I compiled these with gcc -O3, I had to add the call to doNothing to stop the compiler from optimising everything out (output would be 0 for the division + mod solution).

Take it with a grain of salt:

#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>

extern doNothing(int,int); // Empty function in another compilation unit

int main() {
    int i;
    struct timeval timeval;
    struct timeval timeval2;
    div_t result;
    gettimeofday(&timeval,NULL);
    for (i = 0; i < 1000; ++i) {
        result = div(i,3);
        doNothing(result.quot,result.rem);
    }
    gettimeofday(&timeval2,NULL);
    printf("%d",timeval2.tv_usec - timeval.tv_usec);
}

Outputs: 150

#include <stdio.h>
#include <sys/time.h>
#include <stdlib.h>

extern doNothing(int,int); // Empty function in another compilation unit

int main() {
    int i;
    struct timeval timeval;
    struct timeval timeval2;
    int dividend;
    int rem;
    gettimeofday(&timeval,NULL);
    for (i = 0; i < 1000; ++i) {
        dividend = i / 3;
        rem = i % 3;
        doNothing(dividend,rem);
    }
    gettimeofday(&timeval2,NULL);
    printf("%d",timeval2.tv_usec - timeval.tv_usec);
}

Outputs: 25

Passive Link in Angular 2 - <a href=""> equivalent

Here is a simple way

  <div (click)="$event.preventDefault()">
            <a href="#"></a>
   </div>

capture the bubbling event and shoot it down

Toggle Class in React

You have to use the component's State to update component parameters such as Class Name if you want React to render your DOM correctly and efficiently.

UPDATE: I updated the example to toggle the Sidemenu on a button click. This is not necessary, but you can see how it would work. You might need to use "this.state" vs. "this.props" as I have shown. I'm used to working with Redux components.

constructor(props){
    super(props);
}

getInitialState(){
  return {"showHideSidenav":"hidden"};
}

render() {
    return (
        <div className="header">
            <i className="border hide-on-small-and-down"></i>
            <div className="container">
                <a ref="btn" onClick={this.toggleSidenav.bind(this)} href="#" className="btn-menu show-on-small"><i></i></a>
                <Menu className="menu hide-on-small-and-down"/>
                <Sidenav className={this.props.showHideSidenav}/>
            </div>
        </div>
    )
}

toggleSidenav() {
    var css = (this.props.showHideSidenav === "hidden") ? "show" : "hidden";
    this.setState({"showHideSidenav":css});
}

Now, when you toggle the state, the component will update and change the class name of the sidenav component. You can use CSS to show/hide the sidenav using the class names.

.hidden {
   display:none;
}
.show{
   display:block;
}

Why is there no ForEach extension method on IEnumerable?

Partially it's because the language designers disagree with it from a philosophical perspective.

  • Not having (and testing...) a feature is less work than having a feature.
  • It's not really shorter (there's some passing function cases where it is, but that wouldn't be the primary use).
  • It's purpose is to have side effects, which isn't what linq is about.
  • Why have another way to do the same thing as a feature we've already got? (foreach keyword)

https://blogs.msdn.microsoft.com/ericlippert/2009/05/18/foreach-vs-foreach/

What data is stored in Ephemeral Storage of Amazon EC2 instance?

To be clear and answer @Dean's question: EBS-type root storage doesn't seem to be ephemeral. Data is persistent across reboots and actually it doesn't make any sense to use ebs-backed root volume which is 'ephemeral'. This wouldn't be different from image-based root volume.

Can I add background color only for padding?

This would be a proper CSS solution which works for IE8/9 as well (IE8 with html5shiv ofcourse): codepen

nav {
  margin:0px auto;
  height:50px;
  background-color:gray;
  padding:10px;
  border:2px solid red;
  position: relative;
  color: white;
  z-index: 1;
}

nav:after {
  content: '';
  background: black;
  display: block;
  position: absolute;
  margin: 10px;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: -1;
}

Detect if the device is iPhone X

Another possibility, which works on iOS 11 and iOS 12 because the iPhone X is the only one with a notch at the top and an inset of 44. That is what I am really detecting here:

Objective-C:

    BOOL iPhoneX = NO;
    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
        if (mainWindow.safeAreaInsets.top > 24.0) {
            iPhoneX = YES;
        }
    }

Swift 4:

/// Has safe area
///
/// with notch: 44.0 on iPhone X, XS, XS Max, XR.
///
/// without notch: 20.0 on iPhone 8 on iOS 12+.
///
static var hasSafeArea: Bool {
    guard #available(iOS 11.0, *), let topPadding = UIApplication.shared.keyWindow?.safeAreaInsets.top, topPadding > 24 else {
        return false
    }
    return true
}

And of course, you might need to check the left and right safe area insets if you are in landscape orientation.

Edit: _window is the UIWindow of the AppDelegate, where this check is done in application didFinishLaunchingWithOptions.

Answer updated for iOS 12 to check if top > 24 rather than top > 0.

Edit: In the simulator you can go to Hardware, Toggle In-call Status Bar. Doing that shows me that the status bar height does not change on iPhone X on iOS 11 or iPhone XS iOS 12 when engaged in a call. All that changes is the time icon, which gets a green background, in both cases. Here's a snap:

enter image description here

How to send a POST request in Go?

You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.

req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))

Can an Android App connect directly to an online mysql database

Yes you can do that.

Materials you need:

  1. WebServer
  2. A Database Stored in the webserver
  3. And a little bit android knowledge :)
  4. Webservices (json ,Xml...etc) whatever you are comfortable with

1. First set the internet permissions in your manifest file

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

2. Make a class to make an HTTPRequest from the server (i am using json parisng to get the values)

for eg:

    public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

3. In your MainActivity Make an object of the class JsonFunctions and pass the url as an argument from where you want to get the data

eg:

JSONObject jsonobject;

jsonobject = JSONfunctions.getJSONfromURL("http://YOUR_DATABASE_URL");

4. And then finally read the jsontags and store the values in an arraylist and later show it in listview if you want

and if you have any problem you can follow this blog he gives excellent android tutorials AndroidHive

Since the above answer i wrote was long back and now HttpClient, HttpPost,HttpEntity have been removed in Api 23. You can use the below code in the build.gradle(app-level) to still continue using org.apache.httpin your project.

android {
    useLibrary 'org.apache.http.legacy'
    signingConfigs {}
    buildTypes {}
}

or You can use HttpURLConnection like below to get your response from server

public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
    URL u = new URL(url);
    c = (HttpURLConnection) u.openConnection();
    c.setRequestMethod("GET");
    c.setRequestProperty("Content-length", "0");
    c.setUseCaches(false);
    c.setAllowUserInteraction(false);
    c.setConnectTimeout(timeout);
    c.setReadTimeout(timeout);
    c.connect();
    int status = c.getResponseCode();

    switch (status) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line+"\n");
            }
            br.close();
            return sb.toString();
    }

} catch (MalformedURLException ex) {
    Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
    Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
   if (c != null) {
      try {
          c.disconnect();
      } catch (Exception ex) {
         Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
      }
   }
}
return null;

}

or You can use 3rd party Library like Volley, Retrofit to call the webservice api and get the response and later parse it with using FasterXML-jackson, google-gson.

What does `ValueError: cannot reindex from a duplicate axis` mean?

Indices with duplicate values often arise if you create a DataFrame by concatenating other DataFrames. IF you don't care about preserving the values of your index, and you want them to be unique values, when you concatenate the the data, set ignore_index=True.

Alternatively, to overwrite your current index with a new one, instead of using df.reindex(), set:

df.index = new_index

How to link html pages in same or different folders?

I would caution you: if you are using absolute paths, then your application cannot be installed in a "subdirectory" of the server!

eg, http://yourserver.com/yourapp may work, but http://myserver.com/apps/yourapp will not!

sql ORDER BY multiple values in specific order?

You can order by a selected column or other expressions.

Here an example, how to order by the result of a case-statement:

  SELECT col1
       , col2
    FROM tbl_Bill
   WHERE col1 = 0
ORDER BY -- order by case-statement
    CASE WHEN tbl_Bill.IsGen = 0 THEN 0
         WHEN tbl_Bill.IsGen = 1 THEN 1
         ELSE 2 END

The result will be a List starting with "IsGen = 0" rows, followed by "IsGen = 1" rows and all other rows a the end.

You could add more order-parameters at the end:

  SELECT col1
       , col2
    FROM tbl_Bill
   WHERE col1 = 0
ORDER BY -- order by case-statement
    CASE WHEN tbl_Bill.IsGen = 0 THEN 0
         WHEN tbl_Bill.IsGen = 1 THEN 1
         ELSE 2 END,
         col1,
         col2

Convert DateTime to a specified Format

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");

MySQL set current date in a DATETIME field on insert

DELIMITER ;;
CREATE TRIGGER `my_table_bi` BEFORE INSERT ON `my_table` FOR EACH ROW
BEGIN
    SET NEW.created_date = NOW();
END;;
DELIMITER ;

Which characters make a URL invalid?

Not really an answer to your question but validating url's is really a serious p.i.t.a You're probably just better off validating the domainname and leave query part of the url be. That is my experience. You could also resort to pinging the url and seeing if it results in a valid response but that might be too much for such a simple task.

Regular expressions to detect url's are abundant, google it :)

Trying to get property of non-object - Laravel 5

If you working with or loops (for, foreach, etc.) or relationships (one to many, many to many, etc.), this may mean that one of the queries is returning a null variable or a null relationship member.

For example: In a table, you may want to list users with their roles.

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ $user->role->name }}</td>
    </tr>
    @endforeach
</table>

In the above case, you may receive this error if there is even one User who does not have a Role. You should replace {{ $user->role->name }} with {{ !empty($user->role) ? $user->role->name:'' }}, like this:

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ !empty($user->role) ? $user->role->name:'' }}</td>
    </tr>
    @endforeach
</table>

Edit: You can use Laravel's the optional method to avoid errors (more information). For example:

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ optional($user->role)->name }}</td>
    </tr>
    @endforeach
</table>

If you are using PHP 8, you can use the null safe operator:

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user?->name }}</td>
        <td>{{ $user?->role?->name }}</td>
    </tr>
    @endforeach
</table>

Excel - match data from one range to another and get the value from the cell to the right of the matched data

Thanks a bundle, guys. You are great.

I used Chuff's answer and modified it a little to do what I wanted.

I have 2 worksheets in the same workbook.

On 1st worksheet I have a list of SMS in 3 columns: phone number, date & time, message

Then I inserted a new blank column next to the phone number

On worksheet 2 I have two columns: phone number, name of person

Used the formula to check the cell on the left, and match against the range in worksheet 2, pick the name corresponding to the number and input it into the blank cell in worksheet 1.

Then just copy the formula down the whole column until last sms It worked beautifully.

=VLOOKUP(A3,Sheet2!$A$1:$B$31,2,0)

Throw keyword in function's signature

When throw specifications were added to the language it was with the best intentions, but practice has borne out a more practical approach.

With C++, my general rule of thumb is to only use throw specifications to indicate that a method can't throw. This is a strong guarantee. Otherwise, assume it could throw anything.

How do I create a simple 'Hello World' module in Magento?

I will rather recommend Mage2Gen, this will help you generate the boilerplate and you can just focus on the core business logic. it just helps speed up the things.

How do I add 1 day to an NSDate?

Swift 5.0 :

var dayComponent    = DateComponents()
dayComponent.day    = 1 // For removing one day (yesterday): -1
let theCalendar     = Calendar.current
let nextDate        = theCalendar.date(byAdding: dayComponent, to: Date())
print("nextDate : \(nextDate)")

Objective C :

NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;

NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *nextDate = [theCalendar dateByAddingComponents:dayComponent toDate:[NSDate date] options:0];

NSLog(@"nextDate: %@ ...", nextDate);

This should be self-explanatory.

jQuery move to anchor location on page load

Description

You can do this using jQuery's .scrollTop() and .offset() method

Check out my sample and this jsFiddle Demonstration

Sample

$(function() {
    $(document).scrollTop( $("#header").offset().top );  
});

More Information

What is the size of column of int(11) in mysql in bytes?

According to here, int(11) will take 4 bytes of space that is 32 bits of space with 2^(31) = 2147483648 max value and -2147483648min value. One bit is for sign.

How to roundup a number to the closest ten?

the second argument in ROUNDUP, eg =ROUNDUP(12345.6789,3) refers to the negative of the base-10 column with that power of 10, that you want rounded up. eg 1000 = 10^3, so to round up to the next highest 1000, use ,-3)

=ROUNDUP(12345.6789,-4) = 20,000
=ROUNDUP(12345.6789,-3) = 13,000
=ROUNDUP(12345.6789,-2) = 12,400
=ROUNDUP(12345.6789,-1) = 12,350
=ROUNDUP(12345.6789,0) = 12,346
=ROUNDUP(12345.6789,1) = 12,345.7
=ROUNDUP(12345.6789,2) = 12,345.68
=ROUNDUP(12345.6789,3) = 12,345.679

So, to answer your question: if your value is in A1, use =ROUNDUP(A1,-1)

How to predict input image using trained model in Keras?

keras predict_classes (docs) outputs A numpy array of class predictions. Which in your model case, the index of neuron of highest activation from your last(softmax) layer. [[0]] means that your model predicted that your test data is class 0. (usually you will be passing multiple image, and the result will look like [[0], [1], [1], [0]] )

You must convert your actual label (e.g. 'cancer', 'not cancer') into binary encoding (0 for 'cancer', 1 for 'not cancer') for binary classification. Then you will interpret your sequence output of [[0]] as having class label 'cancer'

ImportError: No module named 'pygame'

Since no answer stated this:

Make sure that, if you are using a virtual environment, you have activated it before trying to run the program.

If you don't really know if you are using a virtual environment or not, check with the other contributors of the project. Or maybe try to find a file with the name activate like this: find . -name activate.

Using sed, how do you print the first 'N' characters of a line?

colrm x

For example, if you need the first 100 characters:

cat file |colrm 101 

It's been around for years and is in most linux's and bsd's (freebsd for sure), usually by default. I can't remember ever having to type apt-get install colrm.

CSS: fixed position on x-axis but not y?

If you want to fix it on the right, for example, use justify-content: flex-end.

More: http://www.w3schools.com/cssref/css3_pr_justify-content.asp

How to emit an event from parent to child?

Using RxJs, you can declare a Subject in your parent component and pass it as Observable to child component, child component just need to subscribe to this Observable.

Parent-Component

eventsSubject: Subject<void> = new Subject<void>();

emitEventToChild() {
  this.eventsSubject.next();
}

Parent-HTML

<child [events]="eventsSubject.asObservable()"> </child>    

Child-Component

private eventsSubscription: Subscription;

@Input() events: Observable<void>;

ngOnInit(){
  this.eventsSubscription = this.events.subscribe(() => doSomething());
}

ngOnDestroy() {
  this.eventsSubscription.unsubscribe();
}

Twitter bootstrap scrollable modal

/* Important part */
.modal-dialog{
    overflow-y: initial !important
}
.modal-body{
    max-height: calc(100vh - 200px);
    overflow-y: auto;
}

This works for Bootstrap 3 without JS code and is responsive.

Source

How do I apply a perspective transform to a UIView?

You can get accurate Carousel effect using iCarousel SDK.

You can get an instant Cover Flow effect on iOS by using the marvelous and free iCarousel library. You can download it from https://github.com/nicklockwood/iCarousel and drop it into your Xcode project fairly easily by adding a bridging header (it's written in Objective-C).

If you haven't added Objective-C code to a Swift project before, follow these steps:

  • Download iCarousel and unzip it
  • Go into the folder you unzipped, open its iCarousel subfolder, then select iCarousel.h and iCarousel.m and drag them into your project navigation – that's the left pane in Xcode. Just below Info.plist is fine.
  • Check "Copy items if needed" then click Finish.
  • Xcode will prompt you with the message "Would you like to configure an Objective-C bridging header?" Click "Create Bridging Header" You should see a new file in your project, named YourProjectName-Bridging-Header.h.
  • Add this line to the file: #import "iCarousel.h"
  • Once you've added iCarousel to your project you can start using it.
  • Make sure you conform to both the iCarouselDelegate and iCarouselDataSource protocols.

Swift 3 Sample Code:

    override func viewDidLoad() {
      super.viewDidLoad()
      let carousel = iCarousel(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
      carousel.dataSource = self
      carousel.type = .coverFlow
      view.addSubview(carousel) 
    }

   func numberOfItems(in carousel: iCarousel) -> Int {
        return 10
    }

    func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
        let imageView: UIImageView

        if view != nil {
            imageView = view as! UIImageView
        } else {
            imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 128))
        }

        imageView.image = UIImage(named: "example")

        return imageView
    }

Is there a "between" function in C#?

As @Hellfrost pointed out, it is literally nonsense to compare a number to two different numbers in "one operation", and I know of no C# operator that encapsulates this.

between = (0 < 5 && 5 < 10);

Is about the most-compact form I can think of.

You could make a somewhat "fluent"-looking method using extension (though, while amusing, I think it's overkill):

public static bool Between(this int x, int a, int b)
{
    return (a < x) && (x < b);
}

Use:

int x = 5;
bool b = x.Between(0,10);

How to print VARCHAR(MAX) using Print Statement?

create procedure dbo.PrintMax @text nvarchar(max)
as
begin
    declare @i int, @newline nchar(2), @print varchar(max); 
    set @newline = nchar(13) + nchar(10);
    select @i = charindex(@newline, @text);
    while (@i > 0)
    begin
        select @print = substring(@text,0,@i);
        while (len(@print) > 8000)
        begin
            print substring(@print,0,8000);
            select @print = substring(@print,8000,len(@print));
        end
        print @print;
        select @text = substring(@text,@i+2,len(@text));
        select @i = charindex(@newline, @text);
    end
    print @text;
end

How to use icons and symbols from "Font Awesome" on Native Android Application

Font Awesome seems to be working fine for me in my android app. I did the following:

  1. Copied fontawesome-webfont.ttf into my assests folder
  2. Found the character entities for icons I wanted, using this page: http://fortawesome.github.io/Font-Awesome/cheatsheet/
  3. Created an entry in strings.xml for each icon. Eg for a heart:

    <string name="icon_heart">&#xf004;</string>
    
  4. Referenced said entry in the view of my xml layout:

     <Button
         android:id="@+id/like"
         style="?android:attr/buttonStyleSmall"
         ...
         android:text="@string/icon_heart" />
    
  5. Loaded the font in my onCreate method and set it for the appropriate Views:

    Typeface font = Typeface.createFromAsset( getAssets(), "fontawesome-webfont.ttf" );
    ...
    Button button = (Button)findViewById( R.id.like );
    button.setTypeface(font);
    

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

The following should work and not require any permissions in the manifest (basically override shouldOverrideUrlLoading and handle links separately from tel, mailto, etc.):

    mWebView = (WebView) findViewById(R.id.web_view);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    mWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if( url.startsWith("http:") || url.startsWith("https:") ) {
                return false;
            }

            // Otherwise allow the OS to handle things like tel, mailto, etc.
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity( intent );
            return true;
        }
    });
    mWebView.loadUrl(url);

Also, note that in the above snippet I am enabling JavaScript, which you will also most likely want, but if for some reason you don't, just remove those 2 lines.

How to get the caller class in Java

Since I currently have the same problem here is what I do:

  1. I prefer com.sun.Reflection instead of stackTrace since a stack trace is only producing the name not the class (including the classloader) itself.

  2. The method is deprecated but still around in Java 8 SDK.

// Method descriptor #124 (I)Ljava/lang/Class; (deprecated) // Signature: (I)Ljava/lang/Class<*>; @java.lang.Deprecated public static native java.lang.Class getCallerClass(int arg0);

  1. The method without int argument is not deprecated

// Method descriptor #122 ()Ljava/lang/Class; // Signature: ()Ljava/lang/Class<*>; @sun.reflect.CallerSensitive public static native java.lang.Class getCallerClass();

Since I have to be platform independent bla bla including Security Restrictions, I just create a flexible method:

  1. Check if com.sun.Reflection is available (security exceptions disable this mechanism)

  2. If 1 is yes then get the method with int or no int argument.

  3. If 2 is yes call it.

If 3. was never reached, I use the stack trace to return the name. I use a special result object that contains either the class or the string and this object tells exactly what it is and why.

[Summary] I use stacktrace for backup and to bypass eclipse compiler warnings I use reflections. Works very good. Keeps the code clean, works like a charm and also states the problems involved correctly.

I use this for quite a long time and today I searched a related question so

MySQL query to get column names?

I have done this in the past.

SELECT column_name
FROM information_schema.columns
WHERE table_name='insert table name here';