Programs & Examples On #Xsom

XML Schema Object Model (XSOM)

Remove category & tag base from WordPress url - without a plugin

I don´t know how to do it using code, but for those who don't mind using a plugin. This is a great one that works for me:

https://es.wordpress.org/plugins/permalink-manager/

Linux command (like cat) to read a specified quantity of characters

Here's a simple script that wraps up using the dd approach mentioned here:

extract_chars.sh

#!/usr/bin/env bash

function show_help()
{
  IT="
extracts characters X to Y from stdin or FILE
usage: X Y {FILE}

e.g. 

2 10 /tmp/it     => extract chars 2-10 from /tmp/it
EOF
  "
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

FROM=$1
TO=$2
COUNT=`expr $TO - $FROM + 1`

if [ -z "$3" ]
then
  dd skip=$FROM count=$COUNT bs=1 2>/dev/null
else
  dd skip=$FROM count=$COUNT bs=1 if=$3 2>/dev/null 
fi

Angular bootstrap datepicker date format does not format ng-model value

All proposed solutions didn't work for me but the closest one was from @Rishii.

I'm using AngularJS 1.4.4 and UI Bootstrap 0.13.3.

.directive('jsr310Compatible', ['dateFilter', 'dateParser', function(dateFilter, dateParser) {
  return {
    restrict: 'EAC',
    require: 'ngModel',
    priority: 1,
    link: function(scope, element, attrs, ngModel) {
      var dateFormat = 'yyyy-MM-dd';

      ngModel.$parsers.push(function(viewValue) {
        return dateFilter(viewValue, dateFormat);
      });

      ngModel.$validators.date = function (modelValue, viewValue) {
        var value = modelValue || viewValue;

        if (!attrs.ngRequired && !value) {
          return true;
        }

        if (angular.isNumber(value)) {
          value = new Date(value);
        }

        if (!value) {
          return true;
        }
        else if (angular.isDate(value) && !isNaN(value)) {
          return true;
        }
        else if (angular.isString(value)) {
          var date = dateParser.parse(value, dateFormat);
          return !isNaN(date);
        }
        else {
          return false;
        }
      };
    }
  };
}])

jQuery document.createElement equivalent?

Here's your example in the "one" line.

this.$OuterDiv = $('<div></div>')
    .hide()
    .append($('<table></table>')
        .attr({ cellSpacing : 0 })
        .addClass("text")
    )
;

Update: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about $("<div>") vs $("<div></div>") vs $(document.createElement('div')) as a way of creating new elements, and which is "best".

I put together a small benchmark, and here are roughly the results of repeating the above options 100,000 times:

jQuery 1.4, 1.5, 1.6

               Chrome 11  Firefox 4   IE9
<div>            440ms      640ms    460ms
<div></div>      420ms      650ms    480ms
createElement    100ms      180ms    300ms

jQuery 1.3

                Chrome 11
<div>             770ms
<div></div>      3800ms
createElement     100ms

jQuery 1.2

                Chrome 11
<div>            3500ms
<div></div>      3500ms
createElement     100ms

I think it's no big surprise, but document.createElement is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds per thousand elements.


Update 2

Updated for jQuery 1.7.2 and put the benchmark on JSBen.ch which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!

http://jsben.ch/#/ARUtz

MySQL date format DD/MM/YYYY select query?

Use:

SELECT DATE_FORMAT(NAME_COLUMN, "%d/%l/%Y") AS 'NAME'
SELECT DATE_FORMAT(NAME_COLUMN, "%d/%l/%Y %H:%i:%s") AS 'NAME'

Reference: https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

If someone else have got a similar error message, you probably built the app with optimisations(production) flag on and that's why the error message is not that communicative. Another possibility that you have got the error under development (from i386 I know you were using simulator). If that is the case, change the build environment to development and try to reproduce the situation to get a more specific error message.

Showing the same file in both columns of a Sublime Text window

Its Shift + Alt + 2 to split into 2 screens. More options are found under the menu item View -> Layout.
Once the screen is split, you can open files using the shortcuts:
1. Ctrl + P (From existing directories within sublime) or
2. Ctrl + O(Browse directory)

Enum "Inheritance"

This is not possible (as @JaredPar already mentioned). Trying to put logic to work around this is a bad practice. In case you have a base class that have an enum, you should list of all possible enum-values there, and the implementation of class should work with the values that it knows.

E.g. Supposed you have a base class BaseCatalog, and it has an enum ProductFormats (Digital, Physical). Then you can have a MusicCatalog or BookCatalog that could contains both Digital and Physical products, But if the class is ClothingCatalog, it should only contains Physical products.

Linux bash script to extract IP address

  /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'

For each row in an R dataframe

Well, since you asked for R equivalent to other languages, I tried to do this. Seems to work though I haven't really looked at which technique is more efficient in R.

> myDf <- head(iris)
> myDf
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
> nRowsDf <- nrow(myDf)
> for(i in 1:nRowsDf){
+ print(myDf[i,4])
+ }
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.4

For the categorical columns though, it would fetch you a Data Frame which you could typecast using as.character() if needed.

Printing all properties in a Javascript Object

Your syntax is incorrect. The var keyword in your for loop must be followed by a variable name, in this case its propName

var propValue;
for(var propName in nyc) {
    propValue = nyc[propName]

    console.log(propName,propValue);
}

I suggest you have a look here for some basics:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Java: How to convert a File object to a String object in java?

You can copy all contents of myhtml to String as follows:

Scanner myScanner = null;
try
{
    myScanner = new Scanner(myhtml);
    String contents = myScanner.useDelimiter("\\Z").next(); 
}
finally
{
    if(myScanner != null)
    {
        myScanner.close(); 
    }
}

Ofcourse, you can add a catch block to handle exceptions properly.

Increase bootstrap dropdown menu width

Usually we have the need to control the width of the dropdown menu; specially that's essential when the dropdown menu holds a form, e.g. login form --- then the dropdown menu and its items should be wide enough for ease of inputing username/email and password.

Besides, when the screen is smaller than 768px or when the window (containing the dropdown menu) is zoomed down to smaller than 768px, Bootstrap 3 responsively scales the dropdown menu to the whole width of the screen/window. We need to keep this reponsive action.

Hence, the following css class could do that:

@media (min-width: 768px) {
    .dropdown-menu {
        width: 300px !important;  /* change the number to whatever that you need */
    }
}

(I had used it in my web app.)

Writing image to local server

I have an easier solution using fs.readFileSync(./my_local_image_path.jpg)

This is for reading images from Azure Cognative Services's Vision API

const subscriptionKey = 'your_azure_subscrition_key';
const uriBase = // **MUST change your location (mine is 'eastus')**
    'https://eastus.api.cognitive.microsoft.com/vision/v2.0/analyze';

// Request parameters.
const params = {
    'visualFeatures': 'Categories,Description,Adult,Faces',
    'maxCandidates': '2',
    'details': 'Celebrities,Landmarks',
    'language': 'en'
};

const options = {
    uri: uriBase,
    qs: params,
    body: fs.readFileSync(./my_local_image_path.jpg),
    headers: {
        'Content-Type': 'application/octet-stream',
        'Ocp-Apim-Subscription-Key' : subscriptionKey
    }
};

request.post(options, (error, response, body) => {
if (error) {
    console.log('Error: ', error);
    return;
}
let jsonString = JSON.stringify(JSON.parse(body), null, '  ');
body = JSON.parse(body);
if (body.code) // err
{
    console.log("AZURE: " + body.message)
}

console.log('Response\n' + jsonString);

How to change the button color when it is active using bootstrap?

CSS has many pseudo selector like, :active, :hover, :focus, so you can use.

Html

<div class="col-sm-12" id="my_styles">
     <button type="submit" class="btn btn-warning" id="1">Button1</button>
     <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css

.btn{
    background: #ccc;
} .btn:focus{
    background: red;
}

JsFiddle

How to convert date into this 'yyyy-MM-dd' format in angular 2

_x000D_
_x000D_
const formatDate=(dateObj)=>{
const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
const months = ["January","February","March","April","May","June","July","August","September","October","November","December"];

const dateOrdinal=(dom)=> {
    if (dom == 31 || dom == 21 || dom == 1) return dom + "st";
    else if (dom == 22 || dom == 2) return dom + "nd";
    else if (dom == 23 || dom == 3) return dom + "rd";
    else return dom + "th";
};
return dateOrdinal(dateObj.getDate())+', '+days[dateObj.getDay()]+' '+ months[dateObj.getMonth()]+', '+dateObj.getFullYear();
}
const ddate = new Date();
const result=formatDate(ddate)
document.getElementById("demo").innerHTML = result
_x000D_
<!DOCTYPE html>
<html>
<body>
<h2>Example:20th, Wednesday September, 2020 <h2>
<p id="demo"></p>
</body>
</html>
_x000D_
_x000D_
_x000D_

nodejs vs node on ubuntu 12.04

It's optional to remove the existing node and nodejs, but have to do alternatively install the latest 7.x nodejs.

curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
sudo apt-get install -y nodejs

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"Group")

I had the same problem.. It helped me, I'm specify the same field names of my classes as the tag names in the xml file (the file comes from an external system).

For example:

My xml file:

<Response>
  <ESList>
     <Item>
        <ID>1</ID>
        <Name>Some name 1</Name>
        <Code>Some code</Code>
        <Url>Some Url</Url>
        <RegionList>
           <Item>
              <ID>2</ID>
              <Name>Some name 2</Name>
           </Item>
        </RegionList>
     </Item>
  </ESList>
</Response>

My Response class:

@XmlRootElement(name="Response")
@XmlAccessorType(XmlAccessType.FIELD)
public class Response {
    @XmlElement
    private ESList[] ESList = new ESList[1]; // as the tag name in the xml file..

    // getter and setter here
}

My ESList class:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="ESList")
public class ESList {
    @XmlElement
    private Item[] Item = new Item[1]; // as the tag name in the xml file..

    // getters and setters here
}

My Item class:

@XmlRootElement(name="Item")
@XmlAccessorType(XmlAccessType.FIELD)
public class Item {
    @XmlElement
    private String ID; // as the tag name in the xml file..
    @XmlElement
    private String Name; // and so on...
    @XmlElement
    private String Code;
    @XmlElement
    private String Url;
    @XmlElement
    private RegionList[] RegionList = new RegionList[1];

    // getters and setters here
}

My RegionList class:

@XmlRootElement(name="RegionList")
@XmlAccessorType(XmlAccessType.FIELD)
public class RegionList {
    Item[] Item = new Item[1];

    // getters and setters here
}

My DemoUnmarshalling class:

public class DemoUnmarshalling {
    public static void main(String[] args) {
        try {
            File file = new File("...");

            JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            jaxbUnmarshaller.setEventHandler(
                new ValidationEventHandler() {
                    public boolean handleEvent(ValidationEvent event ) {
                        throw new RuntimeException(event.getMessage(),
                            event.getLinkedException());
                    }
                }
            );

            Response response = (Response) jaxbUnmarshaller.unmarshal(file);

            ESList[] esList = response.getESList();
            Item[] item = esList[0].getItem();
            RegionList[] regionLists = item[0].getRegionList();
            Item[] regionListItem = regionLists[0].getItem();

            System.out.println(item[0].getID());
            System.out.println(item[0].getName());
            System.out.println(item[0].getCode());
            System.out.println(item[0].getUrl());
            System.out.println(regionListItem[0].getID());
            System.out.println(regionListItem[0].getName());

        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

It gives:

1
Some name 1
Some code
Some Url
2
Some name 2

error C4996: 'scanf': This function or variable may be unsafe in c programming

You can add "_CRT_SECURE_NO_WARNINGS" in Preprocessor Definitions.

Right-click your project->Properties->Configuration Properties->C/C++ ->Preprocessor->Preprocessor Definitions.

enter image description here

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

Simply try removing the ".xib" from the nib name in "initWithNibName:". According to the documentation, the ".xib" is assumed and shouldn't be used.

SVN Commit specific files

try this script..

#!/bin/bash
NULL="_"
for f in `svn st|grep -v ^\?|sed s/.\ *//`; 
     do LIST="${LIST} $f $NULL on"; 
done
dialog --checklist "Select files to commit" 30 60 30 $LIST 2>/tmp/svnlist.txt
svn ci `cat /tmp/svnlist.txt|sed 's/"//g'`

How to get SQL from Hibernate Criteria API (*not* for logging)

For those using NHibernate, this is a port of [ram]'s code

public static string GenerateSQL(ICriteria criteria)
    {
        NHibernate.Impl.CriteriaImpl criteriaImpl = (NHibernate.Impl.CriteriaImpl)criteria;
        NHibernate.Engine.ISessionImplementor session = criteriaImpl.Session;
        NHibernate.Engine.ISessionFactoryImplementor factory = session.Factory;

        NHibernate.Loader.Criteria.CriteriaQueryTranslator translator = 
            new NHibernate.Loader.Criteria.CriteriaQueryTranslator(
                factory, 
                criteriaImpl, 
                criteriaImpl.EntityOrClassName, 
                NHibernate.Loader.Criteria.CriteriaQueryTranslator.RootSqlAlias);

        String[] implementors = factory.GetImplementors(criteriaImpl.EntityOrClassName);

        NHibernate.Loader.Criteria.CriteriaJoinWalker walker = new NHibernate.Loader.Criteria.CriteriaJoinWalker(
            (NHibernate.Persister.Entity.IOuterJoinLoadable)factory.GetEntityPersister(implementors[0]),
                                translator,
                                factory,
                                criteriaImpl,
                                criteriaImpl.EntityOrClassName,
                                session.EnabledFilters);

        return walker.SqlString.ToString();
    }

Checking Value of Radio Button Group via JavaScript?

_x000D_
_x000D_
function myFunction() {_x000D_
document.getElementById("text").value='male'_x000D_
 document.getElementById("myCheck_2").checked = false;_x000D_
  var checkBox = document.getElementById("myCheck");_x000D_
  var text = document.getElementById("text");_x000D_
  if (checkBox.checked == true){_x000D_
    text.style.display = "block";_x000D_
  } else {_x000D_
     text.style.display = "none";_x000D_
  }_x000D_
}_x000D_
function myFunction_2() {_x000D_
document.getElementById("text").value='female'_x000D_
 document.getElementById("myCheck").checked = false;_x000D_
  var checkBox = document.getElementById("myCheck_2");_x000D_
  var text = document.getElementById("text");_x000D_
  if (checkBox.checked == true){_x000D_
    text.style.display = "block";_x000D_
  } else {_x000D_
     text.style.display = "none";_x000D_
  }_x000D_
}
_x000D_
Male: <input type="checkbox" id="myCheck"  onclick="myFunction()">_x000D_
Female: <input type="checkbox" id="myCheck_2"  onclick="myFunction_2()">_x000D_
_x000D_
<input type="text" id="text" placeholder="Name">
_x000D_
_x000D_
_x000D_

How to remove space from string?

A funny way to remove all spaces from a variable is to use printf:

$ myvar='a cool variable    with   lots of   spaces in it'
$ printf -v myvar '%s' $myvar
$ echo "$myvar"
acoolvariablewithlotsofspacesinit

It turns out it's slightly more efficient than myvar="${myvar// /}", but not safe regarding globs (*) that can appear in the string. So don't use it in production code.

If you really really want to use this method and are really worried about the globbing thing (and you really should), you can use set -f (which disables globbing altogether):

$ ls
file1  file2
$ myvar='  a cool variable with spaces  and  oh! no! there is  a  glob  *  in it'
$ echo "$myvar"
  a cool variable with spaces  and  oh! no! there is  a  glob  *  in it
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglobfile1file2init
$ # See the trouble? Let's fix it with set -f:
$ set -f
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglob*init
$ # Since we like globbing, we unset the f option:
$ set +f

I posted this answer just because it's funny, not to use it in practice.

asynchronous vs non-blocking

Blocking: control returns to invoking precess after processing of primitive(sync or async) completes

Non blocking: control returns to process immediately after invocation

Generate a heatmap in MatPlotLib using a scatter data set

In Matplotlib lexicon, i think you want a hexbin plot.

If you're not familiar with this type of plot, it's just a bivariate histogram in which the xy-plane is tessellated by a regular grid of hexagons.

So from a histogram, you can just count the number of points falling in each hexagon, discretiize the plotting region as a set of windows, assign each point to one of these windows; finally, map the windows onto a color array, and you've got a hexbin diagram.

Though less commonly used than e.g., circles, or squares, that hexagons are a better choice for the geometry of the binning container is intuitive:

  • hexagons have nearest-neighbor symmetry (e.g., square bins don't, e.g., the distance from a point on a square's border to a point inside that square is not everywhere equal) and

  • hexagon is the highest n-polygon that gives regular plane tessellation (i.e., you can safely re-model your kitchen floor with hexagonal-shaped tiles because you won't have any void space between the tiles when you are finished--not true for all other higher-n, n >= 7, polygons).

(Matplotlib uses the term hexbin plot; so do (AFAIK) all of the plotting libraries for R; still i don't know if this is the generally accepted term for plots of this type, though i suspect it's likely given that hexbin is short for hexagonal binning, which is describes the essential step in preparing the data for display.)


from matplotlib import pyplot as PLT
from matplotlib import cm as CM
from matplotlib import mlab as ML
import numpy as NP

n = 1e5
x = y = NP.linspace(-5, 5, 100)
X, Y = NP.meshgrid(x, y)
Z1 = ML.bivariate_normal(X, Y, 2, 2, 0, 0)
Z2 = ML.bivariate_normal(X, Y, 4, 1, 1, 1)
ZD = Z2 - Z1
x = X.ravel()
y = Y.ravel()
z = ZD.ravel()
gridsize=30
PLT.subplot(111)

# if 'bins=None', then color of each hexagon corresponds directly to its count
# 'C' is optional--it maps values to x-y coordinates; if 'C' is None (default) then 
# the result is a pure 2D histogram 

PLT.hexbin(x, y, C=z, gridsize=gridsize, cmap=CM.jet, bins=None)
PLT.axis([x.min(), x.max(), y.min(), y.max()])

cb = PLT.colorbar()
cb.set_label('mean value')
PLT.show()   

enter image description here

Multiple models in a view

Do I need to make another view which holds these 2 views?

Answer:No

Isn't there another way such as (without the BigViewModel):

Yes, you can use Tuple (brings magic in view having multiple model).

Code:

 @model Tuple<LoginViewModel, RegisterViewModel>


    @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
    {
     @Html.TextBoxFor(tuple=> tuple.Item.Name)
     @Html.TextBoxFor(tuple=> tuple.Item.Email)
     @Html.PasswordFor(tuple=> tuple.Item.Password)
    }


    @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
     {
      @Html.TextBoxFor(tuple=> tuple.Item1.Email)
      @Html.PasswordFor(tuple=> tuple.Item1.Password)
     }

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

It seems you are connecting to the wrong database. R u sure "jdbc:postgresql://localhost/testDB" will connect you to the actual datasource ?

Generally they are of the form "jdbc://hostname/databasename". Look into Postgresql log file.

Which port we can use to run IIS other than 80?

Port 8080 might have been used by another process in your computer.

Do netstat in command prompt to find out which server/process is using it.

Have a look at this page (http://en.wikipedia.org/wiki/Port_number) it gives you full explanation on how to use port number

Removing carriage return and new-line from the end of a string in c#

If you are using multiple platforms you are safer using this method.

value.TrimEnd(System.Environment.NewLine.ToCharArray());

It will account for different newline and carriage-return characters.

Open web in new tab Selenium + Python

  • OS: Win 10,
  • Python 3.8.1
    • selenium==3.141.0
from selenium import webdriver
import time

driver = webdriver.Firefox(executable_path=r'TO\Your\Path\geckodriver.exe')
driver.get('https://www.google.com/')

# Open a new window
driver.execute_script("window.open('');")
# Switch to the new window
driver.switch_to.window(driver.window_handles[1])
driver.get("http://stackoverflow.com")
time.sleep(3)

# Open a new window
driver.execute_script("window.open('');")
# Switch to the new window
driver.switch_to.window(driver.window_handles[2])
driver.get("https://www.reddit.com/")
time.sleep(3)
# close the active tab
driver.close()
time.sleep(3)

# Switch back to the first tab
driver.switch_to.window(driver.window_handles[0])
driver.get("https://bing.com")
time.sleep(3)

# Close the only tab, will also close the browser.
driver.close()

Reference: Need Help Opening A New Tab in Selenium

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

Laravel 5 – Remove Public from URL

add .htaccess file to you root folder and paste the following code and replace yourdomainname with your own domain name

RewriteEngine on RewriteCond %{HTTP_HOST} ^(www.)?yourdomainname$ RewriteCond %{REQUEST_URI} !^/public/

RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ /public/$1

RewriteCond %{HTTP_HOST} ^(www.)?yourdomainname$ RewriteRule ^(/)?$ /public/index.php [L]

How to escape apostrophe (') in MySql?

There are three ways I am aware of. The first not being the prettiest and the second being the common way in most programming languages:

  1. Use another single quote: 'I mustn''t sin!'
  2. Use the escape character \ before the single quote': 'I mustn\'t sin!'
  3. Use double quotes to enclose string instead of single quotes: "I mustn't sin!"

Calculating width from percent to pixel then minus by pixel in LESS CSS

You can escape the calc arguments in order to prevent them from being evaluated on compilation.

Using your example, you would simply surround the arguments, like this:

calc(~'100% - 10px')

Demo : http://jsfiddle.net/c5aq20b6/


I find that I use this in one of the following three ways:

Basic Escaping

Everything inside the calc arguments is defined as a string, and is totally static until it's evaluated by the client:

LESS Input

div {
    > span {
        width: calc(~'100% - 10px');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Interpolation of Variables

You can insert a LESS variable into the string:

LESS Input

div {
    > span {
        @pad: 10px;
        width: calc(~'100% - @{pad}');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Mixing Escaped and Compiled Values

You may want to escape a percentage value, but go ahead and evaluate something on compilation:

LESS Input

@btnWidth: 40px;
div {
    > span {
        @pad: 10px;
        width: calc(~'(100% - @{pad})' - (@btnWidth * 2));
    }
}

CSS Output

div > span {
  width: calc((100% - 10px) - 80px);
}

Source: http://lesscss.org/functions/#string-functions-escape.

How to compile c# in Microsoft's new Visual Studio Code?

Install the extension "Code Runner". Check if you can compile your program with csc (ex.: csc hello.cs). The command csc is shipped with Mono. Then add this to your VS Code user settings:

"code-runner.executorMap": {
        "csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
        // "csharp": "echo '# calling dotnet run\n' && dotnet run"
    }

Open your C# file and use the execution key of Code Runner.

Edit: also added dotnet run, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console, dotnet restore).

How to name Dockerfiles

Dockerfile is good if you only have one docker file (per-directory). You can use whatever standard you want if you need multiple docker files in the same directory - if you have a good reason. In a recent project there were AWS docker files and local dev environment files because the environments differed enough:

Dockerfile Dockerfile.aws

Ajax post request in laravel 5 return error 500 (Internal Server Error)

Short and Simple Solution

e.preventDefault();
var value = $('#id').val();
var id = $('#some_id').val();
url="{{url('office/service/requirement/rule_delete/')}}" +"/"+ id;
console.log(url);
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
$.ajax({
/* the route pointing to the post function */
    url: url,
    type: 'DELETE',
/* send the csrf-token and the input to the controller */
    data: {message:value},
    dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
    success: function (data) { 
    console.log(data)
    //$('.writeinfo').append(data.msg);
    //$('#ruleRow'+id).remove();
    }
});
return false;

How to parse a JSON string into JsonNode in Jackson?

import com.github.fge.jackson.JsonLoader;
JsonLoader.fromString("{\"k1\":\"v1\"}")
== JsonNode = {"k1":"v1"}

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

No.

If the user is sophisticated or determined enough to:

  1. Open the Excel VBA editor
  2. Use the object browser to see the list of all sheets, including VERYHIDDEN ones
  3. Change the property of the sheet to VISIBLE or just HIDDEN

then they are probably sophisticated or determined enough to:

  1. Search the internet for "remove Excel 2007 project password"
  2. Apply the instructions they find.

So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.

Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release)

You have to import 'CommonModule' in the module where you are using these in-built directives like ngFor,ngIf etc.

import { CommonModule } from "@angular/common";


@NgModule({
  imports: [
    CommonModule
  ]
})

export class ProductModule { }

Single Page Application: advantages and disadvantages

Try not to consider using a SPA without first defining how you will address security and API stability on the server side. Then you will see some of the true advantages to using a SPA. Specifically, if you use a RESTful server that implements OAUTH 2.0 for security, you will achieve two fundamental separation of concerns that can lower your development and maintenance costs.

  1. This will move the session (and it's security) onto the SPA and relieve your server from all of that overhead.
  2. Your API's become both stable and easily extensible.

Hinted to earlier, but not made explicit; If your goal is to deploy Android & Apple applications, writing a JavaScript SPA that is wrapped by a native call to host the screen in a browser (Android or Apple) eliminates the need to maintain both an Apple code base and an Android code base.

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Find and replace strings in vim on multiple lines

As a side note, instead of having to type in the line numbers, just highlight the lines where you want to find/replace in one of the visual modes:

  • VISUAL mode (V)
  • VISUAL BLOCK mode (Ctrl+V)
  • VISUAL LINE mode (Shift+V, works best in your case)

Once you selected the lines to replace, type your command:

:s/<search_string>/<replace_string>/g

You'll note that the range '<,'> will be inserted automatically for you:

:'<,'>s/<search_string>/<replace_string>/g

Here '< simply means first highlighted line, and '> means last highlighted line.

Note that the behaviour might be unexpected when in NORMAL mode: '< and '> point to the start and end of the last highlight done in one of the VISUAL modes. Instead, in NORMAL mode, the special line number . can be used, which simply means current line. Hence, you can find/replace only on the current line like this:

:.s/<search_string>/<replace_string>/g

Another thing to note is that inserting a second : between the range and the find/replace command does no harm, in other words, these commands will still work:

:'<,'>:s/<search_string>/<replace_string>/g
:.:s/<search_string>/<replace_string>/g

Best way to find if an item is in a JavaScript array?

A robust way to check if an object is an array in javascript is detailed here:

Here are two functions from the xa.js framework which I attach to a utils = {} ‘container’. These should help you properly detect arrays.

var utils = {};

/**
 * utils.isArray
 *
 * Best guess if object is an array.
 */
utils.isArray = function(obj) {
     // do an instanceof check first
     if (obj instanceof Array) {
         return true;
     }
     // then check for obvious falses
     if (typeof obj !== 'object') {
         return false;
     }
     if (utils.type(obj) === 'array') {
         return true;
     }
     return false;
 };

/**
 * utils.type
 *
 * Attempt to ascertain actual object type.
 */
utils.type = function(obj) {
    if (obj === null || typeof obj === 'undefined') {
        return String (obj);
    }
    return Object.prototype.toString.call(obj)
        .replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
};

If you then want to check if an object is in an array, I would also include this code:

/**
 * Adding hasOwnProperty method if needed.
 */
if (typeof Object.prototype.hasOwnProperty !== 'function') {
    Object.prototype.hasOwnProperty = function (prop) {
        var type = utils.type(this);
        type = type.charAt(0).toUpperCase() + type.substr(1);
        return this[prop] !== undefined
            && this[prop] !== window[type].prototype[prop];
    };
}

And finally this in_array function:

function in_array (needle, haystack, strict) {
    var key;

    if (strict) {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

How do I make a branch point at a specific commit?

git reset --hard 1258f0d0aae

But be careful, if the descendant commits between 1258f0d0aae and HEAD are not referenced in other branches it'll be tedious (but not impossible) to recover them, so you'd better to create a "backup" branch at current HEAD, checkout master, and reset to the commit you want.

Also, be sure that you don't have uncommitted changes before a reset --hard, they will be truly lost (no way to recover).

Filter dataframe rows if value in column is in a set list of values

You can also achieve similar results by using 'query' and @:

eg:

df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'f']})
df = pd.DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]})
list_of_values = [3,6]
result= df.query("A in @list_of_values")
result
   A  B
1  6  2
2  3  3

Regular expression to limit number of characters to 10

You can use curly braces to control the number of occurrences. For example, this means 0 to 10:

/^[a-z]{0,10}$/

The options are:

  • {3} Exactly 3 occurrences;
  • {6,} At least 6 occurrences;
  • {2,5} 2 to 5 occurrences.

See the regular expression reference.

Your expression had a + after the closing curly brace, hence the error.

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

When a there are 2 columns for primary keys they make up a composite primary key therefore you have to make sure that in the table that is being referenced there are also 2 columns of the same data type.

What's the difference between "app.render" and "res.render" in express.js?

along with these two variants, there is also jade.renderFile which generates html that need not be passed to the client.

usage-

var jade = require('jade');

exports.getJson = getJson;

function getJson(req, res) {
    var html = jade.renderFile('views/test.jade', {some:'json'});
    res.send({message: 'i sent json'});
}

getJson() is available as a route in app.js.

Can I dynamically add HTML within a div tag from C# on load event?

Remember using

myDiv.InnerHtml = "something";

will replace all HTML elements in myDIV. you need to append text to avoid that.In that this may help

myDiv.InnerHtml = "something" + myDiv.InnerText;

any html control in myDiv but not ASP html controls(as they are not rendered yet).

How to move files from one git repo to another (not a clone), preserving history

In my case, I didn't need to preserve the repo I was migrating from or preserve any previous history. I had a patch of the same branch, from a different remote

#Source directory
git remote rm origin
#Target directory
git remote add branch-name-from-old-repo ../source_directory

In those two steps, I was able to get the other repo's branch to appear in the same repo.

Finally, I set this branch (that I imported from the other repo) to follow the target repo's mainline (so I could diff them accurately)

git br --set-upstream-to=origin/mainline

Now it behaved as-if it was just another branch I had pushed against that same repo.

curl_init() function not working

I got it working in ubuntu 16.04 by following steps.My php version was 7.0

sudo apt-get install php7.0-curl

sudo service apache2 restart

i got it from this link check here for more details

Real world use of JMS/message queues?

JMS (ActiveMQ is a JMS broker implementation) can be used as a mechanism to allow asynchronous request processing. You may wish to do this because the request take a long time to complete or because several parties may be interested in the actual request. Another reason for using it is to allow multiple clients (potentially written in different languages) to access information via JMS. ActiveMQ is a good example here because you can use the STOMP protocol to allow access from a C#/Java/Ruby client.

A real world example is that of a web application that is used to place an order for a particular customer. As part of placing that order (and storing it in a database) you may wish to carry a number of additional tasks:

  • Store the order in some sort of third party back-end system (such as SAP)
  • Send an email to the customer to inform them their order has been placed

To do this your application code would publish a message onto a JMS queue which includes an order id. One part of your application listening to the queue may respond to the event by taking the orderId, looking the order up in the database and then place that order with another third party system. Another part of your application may be responsible for taking the orderId and sending a confirmation email to the customer.

Android how to use Environment.getExternalStorageDirectory()

Environment.getExternalStorageDirectory().getAbsolutePath()

Gives you the full path the SDCard. You can then do normal File I/O operations using standard Java.

Here's a simple example for writing a file:

String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";

// Not sure if the / is on the path or not
File f = new File(baseDir + File.separator + fileName);
f.write(...);
f.flush();
f.close();

Edit:

Oops - you wanted an example for reading ...

String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";

// Not sure if the / is on the path or not
File f = new File(baseDir + File.Separator + fileName);
FileInputStream fiStream = new FileInputStream(f);

byte[] bytes;

// You might not get the whole file, lookup File I/O examples for Java
fiStream.read(bytes); 
fiStream.close();

Regular expression [Any number]

var mask = /^\d+$/;
if ( myString.exec(mask) ){
   /* That's a number */
}

How to program a delay in Swift 3

Try the following function implemented in Swift 3.0 and above

func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { 
        completion()
    }
}

Usage

delayWithSeconds(1) {
   //Do something
}

Error running android: Gradle project sync failed. Please fix your project and try again

This could be due to Android Studio version conflict of v3 and v4 especially when you import a project in android stdio v4 which was previously built in v3.

Here are the few things you need to do:

  • remove the .gradle and .idea folders from the main Application folder.
  • import the project in the android studio.
  • after the sync finished, it will ask you to update the android studio supported version.
  • click update.
  • done.

how to use free cloud database with android app?

As Wingman said, Google App Engine is a great solution for your scenario.

You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android

And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4

Heap space out of memory

There is no way to dynamically increase the heap programatically since the heap is allocated when the Java Virtual Machine is started.

However, you can use this command

java -Xmx1024M YourClass

to set the memory to 1024

or, you can set a min max

java -Xms256m -Xmx1024m YourClassNameHere

Custom events in jQuery?

I had a similar question, but was actually looking for a different answer; I'm looking to create a custom event. For example instead of always saying this:

$('#myInput').keydown(function(ev) {
    if (ev.which == 13) {
        ev.preventDefault();
        // Do some stuff that handles the enter key
    }
});

I want to abbreviate it to this:

$('#myInput').enterKey(function() {
    // Do some stuff that handles the enter key
});

trigger and bind don't tell the whole story - this is a JQuery plugin. http://docs.jquery.com/Plugins/Authoring

The "enterKey" function gets attached as a property to jQuery.fn - this is the code required:

(function($){
    $('body').on('keydown', 'input', function(ev) {
        if (ev.which == 13) {
            var enterEv = $.extend({}, ev, { type: 'enterKey' });
            return $(ev.target).trigger(enterEv);
        }
    });

    $.fn.enterKey = function(selector, data, fn) {
        return this.on('enterKey', selector, data, fn);
    };
})(jQuery);

http://jsfiddle.net/b9chris/CkvuJ/4/

A nicety of the above is you can handle keyboard input gracefully on link listeners like:

$('a.button').on('click enterKey', function(ev) {
    ev.preventDefault();
    ...
});

Edits: Updated to properly pass the right this context to the handler, and to return any return value back from the handler to jQuery (for example in case you were looking to cancel the event and bubbling). Updated to pass a proper jQuery event object to handlers, including key code and ability to cancel event.

Old jsfiddle: http://jsfiddle.net/b9chris/VwEb9/24/

How to send password using sftp batch file

You need to use the command pscp and forcing it to pass through sftp protocol. pscp is automatically installed when you install PuttY, a software to connect to a linux server through ssh.

When you have your pscp command here is the command line:

pscp -sftp -pw <yourPassword> "<pathToYourFile(s)>" <username>@<serverIP>:<PathInTheServerFromTheHomeDirectory>

These parameters (-sftp and -pw) are only available with pscp and not scp. You can also add -r if you want to upload everything in a folder in a recursive way.

Spring MVC: Complex object as GET @RequestParam

While answers that refer to @ModelAttribute, @RequestParam, @PathParam and the likes are valid, there is a small gotcha I ran into. The resulting method parameter is a proxy that Spring wraps around your DTO. So, if you attempt to use it in a context that requires your own custom type, you may get some unexpected results.

The following will not work:

@GetMapping(produces = APPLICATION_JSON_VALUE)
public ResponseEntity<CustomDto> request(@ModelAttribute CustomDto dto) {
    return ResponseEntity.ok(dto);
}

In my case, attempting to use it in Jackson binding resulted in a com.fasterxml.jackson.databind.exc.InvalidDefinitionException.

You will need to create a new object from the dto.

SQL Column definition : default value and not null redundant?

DEFAULT is the value that will be inserted in the absence of an explicit value in an insert / update statement. Lets assume, your DDL did not have the NOT NULL constraint:

ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT 'MyDefault'

Then you could issue these statements

-- 1. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B) VALUES (NULL, NULL);

-- 2. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, DEFAULT);

-- 3. This will insert 'MyDefault' into tbl.col
INSERT INTO tbl (A, B, col) DEFAULT VALUES;

-- 4. This will insert NULL into tbl.col
INSERT INTO tbl (A, B, col) VALUES (NULL, NULL, NULL);

Alternatively, you can also use DEFAULT in UPDATE statements, according to the SQL-1992 standard:

-- 5. This will update 'MyDefault' into tbl.col
UPDATE tbl SET col = DEFAULT;

-- 6. This will update NULL into tbl.col
UPDATE tbl SET col = NULL;

Note, not all databases support all of these SQL standard syntaxes. Adding the NOT NULL constraint will cause an error with statements 4, 6, while 1-3, 5 are still valid statements. So to answer your question: No, they're not redundant.

Print string to text file

If you are using Python3.

then you can use Print Function :

your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data,  file=open('D:\log.txt', 'w'))

For python2

this is the example of Python Print String To Text File

def my_func():
    """
    this function return some value
    :return:
    """
    return 25.256


def write_file(data):
    """
    this function write data to file
    :param data:
    :return:
    """
    file_name = r'D:\log.txt'
    with open(file_name, 'w') as x_file:
        x_file.write('{} TotalAmount'.format(data))


def run():
    data = my_func()
    write_file(data)


run()

How to create global variables accessible in all views using Express / Node.JS?

You can do this by adding them to the locals object in a general middleware.

app.use(function (req, res, next) {
   res.locals = {
     siteTitle: "My Website's Title",
     pageTitle: "The Home Page",
     author: "Cory Gross",
     description: "My app's description",
   };
   next();
});

Locals is also a function which will extend the locals object rather than overwriting it. So the following works as well

res.locals({
  siteTitle: "My Website's Title",
  pageTitle: "The Home Page",
  author: "Cory Gross",
  description: "My app's description",
});

Full example

var app = express();

var middleware = {

    render: function (view) {
        return function (req, res, next) {
            res.render(view);
        }
    },

    globalLocals: function (req, res, next) {
        res.locals({ 
            siteTitle: "My Website's Title",
            pageTitle: "The Root Splash Page",
            author: "Cory Gross",
            description: "My app's description",
        });
        next();
    },

    index: function (req, res, next) {
        res.locals({
            indexSpecificData: someData
        });
        next();
    }

};


app.use(middleware.globalLocals);
app.get('/', middleware.index, middleware.render('home'));
app.get('/products', middleware.products, middleware.render('products'));

I also added a generic render middleware. This way you don't have to add res.render to each route which means you have better code reuse. Once you go down the reusable middleware route you'll notice you will have lots of building blocks which will speed up development tremendously.

How can I run code on a background thread on Android?

Remember Running Background, Running continuously are two different tasks.

For long-term background processes, Threads aren't optimal with Android. However, here's the code and do it at your own risk...

Remember Service or Thread will run in the background but our task needs to make trigger (call again and again) to get updates, i.e. once the task is completed we need to recall the function for next update.

Timer (periodic trigger), Alarm (Timebase trigger), Broadcast (Event base Trigger), recursion will awake our functions.

public static boolean isRecursionEnable = true;

void runInBackground() {
    if (!isRecursionEnable)
        // Handle not to start multiple parallel threads
        return;

    // isRecursionEnable = false; when u want to stop
    // on exception on thread make it true again  
    new Thread(new Runnable() {
        @Override
        public void run() {
            // DO your work here
            // get the data
            if (activity_is_not_in_background) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // update UI
                        runInBackground();
                    }
                });
            } else {
                runInBackground();
            }
        }
    }).start();
}

Using Service: If you launch a Service it will start, It will execute the task, and it will terminate itself. after the task execution. terminated might also be caused by exception, or user killed it manually from settings. START_STICKY (Sticky Service) is the option given by android that service will restart itself if service terminated.

Remember the question difference between multiprocessing and multithreading? Service is a background process (Just like activity without UI), The same way how you launch thread in the activity to avoid load on the main thread (Activity thread), the same way you need to launch threads(or async tasks) on service to avoid load on service.

In a single statement, if you want a run a background continues task, you need to launch a StickyService and run the thread in the service on event base

How to color System.out.println output?

Escape sequences must be interpreted by SOMETHING to be converted to color. The standard CMD.EXE used by java when started from the command line, doesn't support this so therefore Java does not.

parse html string with jquery

I'm not a 100% sure, but won't

$(data)

produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.

EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)

$("img", data).attr ("src")

if you want to access the src-attribute. If your data is just text, it would probably work to do

$("img", $(data)).attr ("src")

Encoding an image file with base64

I'm not sure I understand your question. I assume you are doing something along the lines of:

import base64

with open("yourfile.ext", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read())

You have to open the file first of course, and read its contents - you cannot simply pass the path to the encode function.

Edit: Ok, here is an update after you have edited your original question.

First of all, remember to use raw strings (prefix the string with 'r') when using path delimiters on Windows, to prevent accidentally hitting an escape character. Second, PIL's Image.open either accepts a filename, or a file-like (that is, the object has to provide read, seek and tell methods).

That being said, you can use cStringIO to create such an object from a memory buffer:

import cStringIO
import PIL.Image

# assume data contains your decoded image
file_like = cStringIO.StringIO(data)

img = PIL.Image.open(file_like)
img.show()

Converting a string to a date in JavaScript

You can also do: mydate.toLocaleDateString();

Detect the Enter key in a text input field

event.key === "Enter"

More recent and much cleaner: use event.key. No more arbitrary number codes!

NOTE: The old properties (.keyCode and .which) are Deprecated.

const node = document.getElementsByClassName("input")[0];
node.addEventListener("keyup", function(event) {
    if (event.key === "Enter") {
        // Do work
    }
});

Modern style, with lambda and destructuring

node.addEventListener('keyup', ({key}) => {
    if (key === "Enter") return false
})

If you must use jQuery:

$(document).keyup(function(event) {
    if ($(".input1").is(":focus") && event.key == "Enter") {
        // Do work
    }
});

Mozilla Docs

Supported Browsers

hadoop copy a local file system folder to HDFS

In Short

hdfs dfs -put <localsrc> <dest>

In detail with example:

Checking source and target before placing files into HDFS

[cloudera@quickstart ~]$ ll files/
total 132
-rwxrwxr-x 1 cloudera cloudera  5387 Nov 14 06:33 cloudera-manager
-rwxrwxr-x 1 cloudera cloudera  9964 Nov 14 06:33 cm_api.py
-rw-rw-r-- 1 cloudera cloudera   664 Nov 14 06:33 derby.log
-rw-rw-r-- 1 cloudera cloudera 53655 Nov 14 06:33 enterprise-deployment.json
-rw-rw-r-- 1 cloudera cloudera 50515 Nov 14 06:33 express-deployment.json

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 1 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging

Copy files HDFS using -put or -copyFromLocal command

[cloudera@quickstart ~]$ hdfs dfs -put files/ files

Verify the result in HDFS

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 2 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 06:34 files

[cloudera@quickstart ~]$ hdfs dfs -ls files
Found 5 items
-rw-r--r--   1 cloudera cloudera       5387 2017-11-14 06:34 files/cloudera-manager
-rw-r--r--   1 cloudera cloudera       9964 2017-11-14 06:34 files/cm_api.py
-rw-r--r--   1 cloudera cloudera        664 2017-11-14 06:34 files/derby.log
-rw-r--r--   1 cloudera cloudera      53655 2017-11-14 06:34 files/enterprise-deployment.json
-rw-r--r--   1 cloudera cloudera      50515 2017-11-14 06:34 files/express-deployment.json

How can I check that JButton is pressed? If the isEnable() is not work?

The method you are trying to use checks if the button is active:

btnAdd.isEnabled()

When enabled, any component associated with this object is active and able to fire this object's actionPerformed method.

This method does not check if the button is pressed.

If i understand your question correctly, you want to disable your "Add" button after the user clicks "Check out".

Try disabling your button at start: btnAdd.setEnabled(false) or after the user presses "Check out"

How to remove duplicate white spaces in string using Java?

Though it is too late, I have found a better solution (that works for me) that will replace all consecutive same type white spaces with one white space of its type. That is:

   Hello!\n\n\nMy    World  

will be

 Hello!\nMy World 

Notice there are still leading and trailing white spaces. So my complete solution is:

str = str.trim().replaceAll("(\\s)+", "$1"));

Here, trim() replaces all leading and trailing white space strings with "". (\\s) is for capturing \\s (that is white spaces such as ' ', '\n', '\t') in group #1. + sign is for matching 1 or more preceding token. So (\\s)+ can be consecutive characters (1 or more) among any single white space characters (' ', '\n' or '\t'). $1 is for replacing the matching strings with the group #1 string (which only contains 1 white space character) of the matching type (that is the single white space character which has matched). The above solution will change like this:

   Hello!\n\n\nMy    World  

will be

Hello!\nMy World

I have not found my above solution here so I have posted it.

Group by with union mysql select query

select sum(qty), name
from (
    select count(m.owner_id) as qty, o.name
    from transport t,owner o,motorbike m
    where t.type='motobike' and o.owner_id=m.owner_id
        and t.type_id=m.motorbike_id
    group by m.owner_id

    union all

    select count(c.owner_id) as qty, o.name,
    from transport t,owner o,car c
    where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
    group by c.owner_id
) t
group by name

C/C++ switch case with string

Typically, you would use a hash table and function object, both available in Boost, TR1 and C++0x.

void func1() {
}
std::unordered_map<std::string, std::function<void()>> hash_map;
hash_map["Value1"] = &func1;
// .... etc
hash_map[mystring]();

This is a little more overhead at runtime but a bajillion times more maintainable. Hash tables offer O(1) insertion, lookup, and etc, which makes them the same complexity as the assembly-style jump-table.

java Compare two dates

java.util.Date class has before and after method to compare dates.

Date date1 = new Date();
Date date2 = new Date();

if(date1.before(date2)){
    //Do Something
}

if(date1.after(date2)){
    //Do Something else
}

how to get the child node in div using javascript

If you give your table a unique id, its easier:

<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
    onmouseup="checkMultipleSelection(this,event);">
       <table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table" 
              cellpadding="0" cellspacing="0" border="0" width="100%">
           <tr>
              <td style="width:50px; text-align:left;">09:15 AM</td>
              <td style="width:50px; text-align:left;">Item001</td>
              <td style="width:50px; text-align:left;">10</td>
              <td style="width:50px; text-align:left;">Address1</td>
              <td style="width:50px; text-align:left;">46545465</td>
              <td style="width:50px; text-align:left;">ref1</td>
           </tr>
       </table>
</div>


var multiselect = 
    document.getElementById(
               'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
            ).rows[0].cells,
    timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];

//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

A duplicate in the database should be a 409 CONFLICT.

I recommend using 422 UNPROCESSABLE ENTITY for validation errors.

I give a longer explanation of 4xx codes here: http://parker0phil.com/2014/10/16/REST_http_4xx_status_codes_syntax_and_sematics/

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

There is a way to do this without installing putty on your Mac. You can easily convert your existing PPK file to a PEM file using PuTTYgen on Windows.

Launch PuTTYgen and then load the existing private key file using the Load button. From the "Conversions" menu select "Export OpenSSH key" and save the private key file with the .pem file extension.

Copy the PEM file to your Mac and set it to be read-only by your user:

chmod 400 <private-key-filename>.pem

Then you should be able to use ssh to connect to your remote server

ssh -i <private-key-filename>.pem username@hostname

C free(): invalid pointer

From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.

Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.

What is the best way to delete a component with CLI

Since it is not yet supported using angular CLI

so here is the possible way, before that please observe what happens when you create a component/service using CLI (ex. ng g c demoComponent).

  1. It creates a separate folder named demoComponent (ng g c demoComponent).
  2. It generate HTML,CSS,ts and a spec file dedicated to demoComponent.
  3. Also, It adds dependency inside app.module.ts file to add that component to your project.

so do it in reverse order

  1. Remove Dependency from app.module.ts
  2. Delete that component folder.

when removing the dependency you have to do two things.

  1. Remove the import line reference from app.module.ts file.
  2. Remove the component declaration from @NgModule declaration array in app.module.ts.

Double Iteration in List Comprehension

Order of iterators may seem counter-intuitive.

Take for example: [str(x) for i in range(3) for x in foo(i)]

Let's decompose it:

def foo(i):
    return i, i + 0.5

[str(x)
    for i in range(3)
        for x in foo(i)
]

# is same as
for i in range(3):
    for x in foo(i):
        yield str(x)

Sublime Text 2: How do I change the color that the row number is highlighted?

On windows 7, find

C:\Users\Simion\AppData\Roaming\Sublime Text 2\Packages\Color Scheme - Default

Find your color scheme file, open it, and find lineHighlight.
Ex:

<key>lineHighlight</key>
<string>#ccc</string>

replace #ccc with your preferred background color.

How to position absolute inside a div?

The problem is described (among other) in this article.

#box is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".

Page flow means that the positioning of an element effects other elements in the flow.

In other words, as #box now sees the dom, .a and .b are no longer "inside" #box.

To fix this, you would want to make everything relative, or everything absolute.

One way would be:

.a {
   position:relative;
   margin-top:10px;
   margin-left:10px;
   background-color:red;
   width:210px;
   padding: 5px;
}

Append a Lists Contents to another List C#

With Linq

var newList = GlobalStrings.Append(localStrings)

Import/Index a JSON file into Elasticsearch

You are using

$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests

If 'requests' is a json file then you have to change this to

$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests.json

Now before this, if your json file is not indexed, you have to insert an index line before each line inside the json file. You can do this with JQ. Refer below link: http://kevinmarsh.com/2014/10/23/using-jq-to-import-json-into-elasticsearch.html

Go to elasticsearch tutorials (example the shakespeare tutorial) and download the json file sample used and have a look at it. In front of each json object (each individual line) there is an index line. This is what you are looking for after using the jq command. This format is mandatory to use the bulk API, plain json files wont work.

How do I find the distance between two points?

Let's not forget math.hypot:

dist = math.hypot(x2-x1, y2-y1)

Here's hypot as part of a snippet to compute the length of a path defined by a list of (x, y) tuples:

from math import hypot

pts = [
    (10,10),
    (10,11),
    (20,11),
    (20,10),
    (10,10),
    ]

# Py2 syntax - no longer allowed in Py3
# ptdiff = lambda (p1,p2): (p1[0]-p2[0], p1[1]-p2[1])
ptdiff = lambda p1, p2: (p1[0]-p2[0], p1[1]-p2[1])

diffs = (ptdiff(p1, p2) for p1, p2 in zip (pts, pts[1:]))
path = sum(hypot(*d) for d in  diffs)
print(path)

Assign pandas dataframe column dtypes

Since 0.17, you have to use the explicit conversions:

pd.to_datetime, pd.to_timedelta and pd.to_numeric

(As mentioned below, no more "magic", convert_objects has been deprecated in 0.17)

df = pd.DataFrame({'x': {0: 'a', 1: 'b'}, 'y': {0: '1', 1: '2'}, 'z': {0: '2018-05-01', 1: '2018-05-02'}})

df.dtypes

x    object
y    object
z    object
dtype: object

df

   x  y           z
0  a  1  2018-05-01
1  b  2  2018-05-02

You can apply these to each column you want to convert:

df["y"] = pd.to_numeric(df["y"])
df["z"] = pd.to_datetime(df["z"])    
df

   x  y          z
0  a  1 2018-05-01
1  b  2 2018-05-02

df.dtypes

x            object
y             int64
z    datetime64[ns]
dtype: object

and confirm the dtype is updated.


OLD/DEPRECATED ANSWER for pandas 0.12 - 0.16: You can use convert_objects to infer better dtypes:

In [21]: df
Out[21]: 
   x  y
0  a  1
1  b  2

In [22]: df.dtypes
Out[22]: 
x    object
y    object
dtype: object

In [23]: df.convert_objects(convert_numeric=True)
Out[23]: 
   x  y
0  a  1
1  b  2

In [24]: df.convert_objects(convert_numeric=True).dtypes
Out[24]: 
x    object
y     int64
dtype: object

Magic! (Sad to see it deprecated.)

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

How do I "commit" changes in a git submodule?

Before you can commit and push, you need to init a working repository tree for a submodule. I am using tortoise and do following things:

First check if there exist .git file (not a directory)

  • if there is such file it contains path to supermodule git directory
  • delete this file
  • do git init
  • do git add remote path the one used for submodule
  • follow instructions below

If there was .git file, there surly was .git directory which tracks local tree. You still need to a branch (you can create one) or switch to master (which sometimes does not work). Best to do is - git fetch - git pull. Do not omit fetch.

Now your commits and pulls will be synchronized with your origin/master

Declaring static constants in ES6 classes?

I did this.

class Circle
{
    constuctor(radius)
    {
        this.radius = radius;
    }
    static get PI()
    {
        return 3.14159;
    }
}

The value of PI is protected from being changed since it is a value being returned from a function. You can access it via Circle.PI. Any attempt to assign to it is simply dropped on the floor in a manner similar to an attempt to assign to a string character via [].

python - checking odd/even numbers and changing outputs on number size

Simple but yet fast:

>>> def is_odd(a):
...     return bool(a - ((a>>1)<<1))
...
>>> print(is_odd(13))
True
>>> print(is_odd(12))
False
>>>

Or even simpler:

>>> def is_odd(a):
...   return bool(a & 1)

How to run or debug php on Visual Studio Code (VSCode)

The best solution for me was to add a key binding to run PHP code directly in the terminal

To do so you just need to download terminal-command-keys from VS code extensions marketplace:

enter image description here

Then got to File>Preferences>Keyboard Shortcuts and click on the following icon at the upper right corner:

enter image description here

It will open up the keybindings.json file

Add the following settings

[
    {
        "key": "ctrl+s",
        "command":"terminalCommandKeys.run",
        "when": "editorLangId == php",
        "args": {
            "cmd":"php ${file}",
            "newTerminal":true,
            "saveAllfiles": true,
            "showTerminal": true,
        }
    }
]

key is the shortcut to run your PHP file (I use ctrl+s) you can change it as you wish

when to run different commands for different file types (I set it for PHP files only) vscode's "when" clauses

See the full settings documentation from here

That's it, I hope it helps.

Nuget connection attempt failed "Unable to load the service index for source"

Make sure docker is running in your local machine. build command will work but its required running docker to get network data.

I think it will help.

How do you exit from a void function in C++?

Use a return statement!

return;

or

if (condition) return;

You don't need to (and can't) specify any values, if your method returns void.

Selecting with complex criteria from pandas.DataFrame

Another solution is to use the query method:

import pandas as pd

from random import randint
df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)],
                   'B': [randint(1, 9) * 10 for x in xrange(10)],
                   'C': [randint(1, 9) * 100 for x in xrange(10)]})
print df

   A   B    C
0  7  20  300
1  7  80  700
2  4  90  100
3  4  30  900
4  7  80  200
5  7  60  800
6  3  80  900
7  9  40  100
8  6  40  100
9  3  10  600

print df.query('B > 50 and C != 900')

   A   B    C
1  7  80  700
2  4  90  100
4  7  80  200
5  7  60  800

Now if you want to change the returned values in column A you can save their index:

my_query_index = df.query('B > 50 & C != 900').index

....and use .iloc to change them i.e:

df.iloc[my_query_index, 0] = 5000

print df

      A   B    C
0     7  20  300
1  5000  80  700
2  5000  90  100
3     4  30  900
4  5000  80  200
5  5000  60  800
6     3  80  900
7     9  40  100
8     6  40  100
9     3  10  600

How to remove specific element from an array using python

If you want to delete the index of array:

Use array_name.pop(index_no.)

ex:-

>>> arr = [1,2,3,4]
>>> arr.pop(2)
>>>arr
[1,2,4]

If you want to delete a particular string/element from the array then

>>> arr1 = ['python3.6' , 'python2' ,'python3']
>>> arr1.remove('python2')
>>> arr1
['python3.6','python3']

What to gitignore from the .idea folder?

Github uses the following .gitignore for their programs

https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore

# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn.  Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

Could not load file or assembly '***.dll' or one of its dependencies

1) Copy DLLs from "Externals\ffmpeg\bin" to your project's output directory (where executable stays); 2) Make sure your project is built for x86 target (runs in 32-bit mode).

Follow this thread for more

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

You must to have installed php_openssl.dll, if you use wampserver it's pretty easy, search and apply the extension for PHP.

In the example change this:

    //Set the hostname of the mail server
    $mail->Host = 'smtp.gmail.com';

    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission 465 ssl
    $mail->Port = 465;

    //Set the encryption system to use - ssl (deprecated) or tls
    $mail->SMTPSecure = 'ssl';

and then you recived an email from gmail talking about to enable the option to Less Safe Access Applications here https://www.google.com/settings/security/lesssecureapps

I recommend you change the password and encrypt it constantly

Saving response from Requests to file

As Peter already pointed out:

In [1]: import requests

In [2]: r = requests.get('https://api.github.com/events')

In [3]: type(r)
Out[3]: requests.models.Response

In [4]: type(r.content)
Out[4]: str

You may also want to check r.text.

Also: https://2.python-requests.org/en/latest/user/quickstart/

How to Execute a Python File in Notepad ++?

I would like to avoid using full python directory path in the Notepad++ macro. I tried other solutions given in this page, they failed.

The one working on my PC is:

In Notepad++, press F5.

Copy/paste this:

cmd /k cd /d $(CURRENT_DIRECTORY) && py -3 -i $(FULL_CURRENT_PATH)

Enter.

How to get mouse position in jQuery without mouse-events?

I came across this, tot it would be nice to share...

What do you guys think?

$(document).ready(function() {
  window.mousemove = function(e) {
    p = $(e).position();  //remember $(e) - could be any html tag also.. 
    left = e.left;        //retrieving the left position of the div... 
    top = e.top;          //get the top position of the div... 
  }
});

and boom, there we have it..

What is the point of the diamond operator (<>) in Java 7?

This line causes the [unchecked] warning:

List<String> list = new LinkedList();

So, the question transforms: why [unchecked] warning is not suppressed automatically only for the case when new collection is created?

I think, it would be much more difficult task then adding <> feature.

UPD: I also think that there would be a mess if it were legally to use raw types 'just for a few things'.

$("#form1").validate is not a function

Probably the browser first downloaded the validade script and then jQuery. If the validade script be downloaded before loading jQuery you'll get an error. You can see this using a tool like firebug.

Try this:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
    function LoadValidade() {
        var a = false;
        try {
            var teste = $('*');
            if(teste == null)
                throw 1;
        } catch (e) { 
            a = true; 
        }

        if (a){ 
            setTimeout(LoadValidade, 300);
            return;
        }

        var validadeScript = document.createElement("script");
        validadeScript.src = "../common/jquery.validate.js";
        $('head')[0].appendChild(validadeScript);
    } 
    setTimeout(LoadValidade, 300);
</script>

Should I use alias or alias_method?

The rubocop gem contributors propose in their Ruby Style Guide:

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

class Westerner
  def first_name
   @names.first
  end

 alias given_name first_name
end

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

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

class Sting < Westerner
  include Mononymous
end

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Permissions error when connecting to EC2 via SSH on Mac OSx

If the issue is consistent and happened about 10-15 times in a row even after changing file permissions to 400 or 600, then it is most certainly something is wrong on the ec2 instance, so to make sure:

  1. Check the logs when you try to ssh to the instance by adding -v at the end and see either it gives out anything specific.

  2. Make sure you use the correct name for ssh, like Ubuntu. Perhaps that depends on Linux distribution and users you added and either you've given permission for "root user" ssh.

Then if nothing helps, follow the documentation here https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html#TroubleshootingInstancesConnectingMindTerm to fix that. It helped in my case, and it happened because of messed up directories/files permissions.

Convert date formats in bash

It's enough to do:

data=`date`
datatime=`date -d "${data}" '+%Y%m%d'`
echo $datatime
20190206

If you want to add also the time you can use in that way

data=`date`
datatime=`date -d "${data}" '+%Y%m%d %T'`

echo $data
Wed Feb 6 03:57:15 EST 2019

echo $datatime
20190206 03:57:15

How can I make the computer beep in C#?

Try this

Console.WriteLine("\a")

Save file/open file dialog box, using Swing & Netbeans GUI editor

saving in any format is very much possible. Check following- http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

2ndly , What exactly you are expecting the save dialog to work , it works like that, Opening a doc file is very much possible- http://srikanthtechnologies.com/blog/openworddoc.html

Auto-Submit Form using JavaScript

This solution worked for me:

<body onload="setTimeout(function() { document.myform.submit() }, 5000)">
   <form action=TripRecorder name="myform">
      <textarea id="result1"  name="res1" value="str1" cols="20" rows="1" ></textarea> <br> <br/>
      <textarea id="result2" name="res2" value="str2" cols="20" rows="1" ></textarea>
   </form>
</body>

Getting data-* attribute for onclick event for an html element

User $() to get jQuery object from your link and data() to get your values

<a id="option1" 
   data-id="10" 
   data-option="21" 
   href="#" 
   onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
       Click to do something
</a>

If statement in aspx page

To use C# (C# Script was initialized at 2015) on ASPX page you can make use the following syntax.

Start Tag:- <% End tag:- %> Please make sure that all the C# code must reside inside this <%%> .

Syntax Example:-

  • <%@ Import Namespace="System.Web.UI.WebControls" %> (For importing Namespace) Reference to some basic namespaces for working with ASPX page.

    <%@ Import Namespace="System.Web.UI.WebControls" %> <%@ Import Namespace="System.Diagnostics" %> <%@ Import Namespace="System" %> <%@ Import Namespace="System.Web" %> <%@ Import Namespace="System.Web.UI" %> <%@ Import Namespace="System.IO" %>

C# Code:-

`<%
if (Session["New"] != null)
{
    Page.Title = ActionController.GetName(Session["New"].ToString());
}
%>`

Features of C# Script:

  • No need of compilation. Run time execution is occurred like Java Script.

Before using C# script make sure the following things:-

  • You are on WebForm. Not on WebForm with master page.
  • If you are in WebForm with master page make sure that you have written your C# script at Master page file.
  • C# script can be inserted anywhere in the aspx page but after the page meta declaration like

    <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Profile.master.cs" Inherits="OOSDDemo.Profile" %>

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication3.WebForm1" %> (For WebForm)

Can Powershell Run Commands in Parallel?

You can execute parallel jobs in Powershell 2 using Background Jobs. Check out Start-Job and the other job cmdlets.

# Loop through the server list
Get-Content "ServerList.txt" | %{

  # Define what each job does
  $ScriptBlock = {
    param($pipelinePassIn) 
    Test-Path "\\$pipelinePassIn\c`$\Something"
    Start-Sleep 60
  }

  # Execute the jobs in parallel
  Start-Job $ScriptBlock -ArgumentList $_
}

Get-Job

# Wait for it all to complete
While (Get-Job -State "Running")
{
  Start-Sleep 10
}

# Getting the information back from the jobs
Get-Job | Receive-Job

What is an unhandled promise rejection?

Promises can be "handled" after they are rejected. That is, one can call a promise's reject callback before providing a catch handler. This behavior is a little bothersome to me because one can write...

var promise = new Promise(function(resolve) {
kjjdjf(); // this function does not exist });

... and in this case, the Promise is rejected silently. If one forgets to add a catch handler, code will continue to silently run without errors. This could lead to lingering and hard-to-find bugs.

In the case of Node.js, there is talk of handling these unhandled Promise rejections and reporting the problems. This brings me to ES7 async/await. Consider this example:

async function getReadyForBed() {
  let teethPromise = brushTeeth();
  let tempPromise = getRoomTemperature();

  // Change clothes based on room temperature
  let temp = await tempPromise;
  // Assume `changeClothes` also returns a Promise
  if(temp > 20) {
    await changeClothes("warm");
  } else {
    await changeClothes("cold");
  }

  await teethPromise;
}

In the example above, suppose teethPromise was rejected (Error: out of toothpaste!) before getRoomTemperature was fulfilled. In this case, there would be an unhandled Promise rejection until await teethPromise.

My point is this... if we consider unhandled Promise rejections to be a problem, Promises that are later handled by an await might get inadvertently reported as bugs. Then again, if we consider unhandled Promise rejections to not be problematic, legitimate bugs might not get reported.

Thoughts on this?

This is related to the discussion found in the Node.js project here:

Default Unhandled Rejection Detection Behavior

if you write the code this way:

function getReadyForBed() {
  let teethPromise = brushTeeth();
  let tempPromise = getRoomTemperature();

  // Change clothes based on room temperature
  return Promise.resolve(tempPromise)
    .then(temp => {
      // Assume `changeClothes` also returns a Promise
      if (temp > 20) {
        return Promise.resolve(changeClothes("warm"));
      } else {
        return Promise.resolve(changeClothes("cold"));
      }
    })
    .then(teethPromise)
    .then(Promise.resolve()); // since the async function returns nothing, ensure it's a resolved promise for `undefined`, unless it's previously rejected
}

When getReadyForBed is invoked, it will synchronously create the final (not returned) promise - which will have the same "unhandled rejection" error as any other promise (could be nothing, of course, depending on the engine). (I find it very odd your function doesn't return anything, which means your async function produces a promise for undefined.

If I make a Promise right now without a catch, and add one later, most "unhandled rejection error" implementations will actually retract the warning when i do later handle it. In other words, async/await doesn't alter the "unhandled rejection" discussion in any way that I can see.

to avoid this pitfall please write the code this way:

async function getReadyForBed() {
  let teethPromise = brushTeeth();
  let tempPromise = getRoomTemperature();

  // Change clothes based on room temperature
  var clothesPromise = tempPromise.then(function(temp) {
    // Assume `changeClothes` also returns a Promise
    if(temp > 20) {
      return changeClothes("warm");
    } else {
      return changeClothes("cold");
    }
  });
  /* Note that clothesPromise resolves to the result of `changeClothes`
     due to Promise "chaining" magic. */

  // Combine promises and await them both
  await Promise.all(teethPromise, clothesPromise);
}

Note that this should prevent any unhandled promise rejection.

Why am I getting this redefinition of class error?

You're defining the same class twice is why.

If your intent is to implement the methods in the CPP file then do so something like this:

gameObject::gameObject()
{
    x = 0;
    y = 0;
}
gameObject::~gameObject()
{
    //
}
int gameObject::add()
{
        return x+y;
}

PostgreSQL Error: Relation already exists

In my case, I had a sequence with the same name.

PHP Try and Catch for SQL Insert

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.

javascript date to string

I like Daniel Cerecedo's answer using toJSON() and regex. An even simpler form would be:

var now = new Date();
var regex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).*$/;
var token_array = regex.exec(now.toJSON());
// [ "2017-10-31T02:24:45.868Z", "2017", "10", "31", "02", "24", "45" ]
var myFormat = token_array.slice(1).join('');
// "20171031022445"

What is the difference between map and flatMap and a good use case for each?

The difference can be seen from below sample pyspark code:

rdd = sc.parallelize([2, 3, 4])
rdd.flatMap(lambda x: range(1, x)).collect()
Output:
[1, 1, 2, 1, 2, 3]


rdd.map(lambda x: range(1, x)).collect()
Output:
[[1], [1, 2], [1, 2, 3]]

Why does GitHub recommend HTTPS over SSH?

Maybe because it's harder to steal a password from your brain then to steal a key file from your computer (at least to my knowledge, maybe some substances exist already or methods but this is an infinite discussion)? And if you password protect the key, then you are using a password again and the same problems arise (but some might argue that you have to do more work, because you need to get the key and then crack the password).

How to get URL of current page in PHP

You can use $_SERVER['HTTP_REFERER'] this will give you whole URL for example:

suppose you want to get url of site name www.example.com then $_SERVER['HTTP_REFERER'] will give you https://www.example.com

SQL recursive query on self referencing table (Oracle)

Using the new nested query syntax

with q(name, id, parent_id, parent_name) as (
    select 
      t1.name, t1.id, 
      null as parent_id, null as parent_name 
    from t1
    where t1.id = 1
  union all
    select 
      t1.name, t1.id, 
      q.id as parent_id, q.name as parent_name 
    from t1, q
    where t1.parent_id = q.id
)
select * from q

Request Permission for Camera and Library in iOS 10 - Info.plist

To ask permission for the photo app you need to add this code (Swift 3):

PHPhotoLibrary.requestAuthorization({ 
       (newStatus) in 
         if newStatus ==  PHAuthorizationStatus.authorized { 
          /* do stuff here */ 
    } 
})

Matplotlib: "Unknown projection '3d'" error

Try this:

import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.mplot3d import axes3d

fig=plt.figure(figsize=(16,12.5))
ax=fig.add_subplot(2,2,1,projection="3d")

a=ax.scatter(Dataframe['bedrooms'],Dataframe['bathrooms'],Dataframe['floors'])
plt.plot(a)

Laravel 5 not finding css files

I used:

"{{asset('css/custom.css')}}"
"{{asset('css/app.css') }}"

First one is my own file the second one came with laravel. I'm using version 5.

http://spanibox.com/css/app.css works but http://spanibox.com/css/custom.css does not. I find this very weird.

Abstraction vs Encapsulation in Java

In simple words: You do abstraction when deciding what to implement. You do encapsulation when hiding something that you have implemented.

Installing a plain plugin jar in Eclipse 3.5

Since the advent of p2, you should be using the dropins directory instead.

To be completely clear create "plugins" under "/dropins" and make sure to restart eclipse with the "-clean" option.

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

Cause for the error according to the Java [8] Platform, Standard Edition Troubleshooting Guide: (emphasis and line breaks added)

[...] "GC overhead limit exceeded" indicates that the garbage collector is running all the time and Java program is making very slow progress.

After a garbage collection, if the Java process is spending more than approximately 98% of its time doing garbage collection and if it is recovering less than 2% of the heap and has been doing so far the last 5 (compile time constant) consecutive garbage collections, then a java.lang.OutOfMemoryError is thrown. [...]

  1. Increase the heap size if current heap is not enough.
  2. If you still get this error after increasing heap memory, use memory profiling tools like MAT ( Memory analyzer tool), Visual VM etc and fix memory leaks.
  3. Upgrade JDK version to latest version ( 1.8.x) or at least 1.7.x and use G1GC algorithm. . The throughput goal for the G1 GC is 90 percent application time and 10 percent garbage collection time
  4. Apart from setting heap memory with -Xms1g -Xmx2g , try

    -XX:+UseG1GC -XX:G1HeapRegionSize=n -XX:MaxGCPauseMillis=m  
    -XX:ParallelGCThreads=n -XX:ConcGCThreads=n
    

Have a look at some more related questions regarding G1GC

Extract first and last row of a dataframe in pandas

You can also use head and tail:

In [29]: pd.concat([df.head(1), df.tail(1)])
Out[29]:
   a  b
0  1  a
3  4  d

Difference between timestamps with/without time zone in PostgreSQL

I try to explain it more understandably than the referred PostgreSQL documentation.

Neither TIMESTAMP variants store a time zone (or an offset), despite what the names suggest. The difference is in the interpretation of the stored data (and in the intended application), not in the storage format itself:

  • TIMESTAMP WITHOUT TIME ZONE stores local date-time (aka. wall calendar date and wall clock time). Its time zone is unspecified as far as PostgreSQL can tell (though your application may knows what it is). Hence, PostgreSQL does no time zone related conversion on input or output. If the value was entered into the database as '2011-07-01 06:30:30', then no mater in what time zone you display it later, it will still say year 2011, month 07, day 01, 06 hours, 30 minutes, and 30 seconds (in some format). Also, any offset or time zone you specify in the input is ignored by PostgreSQL, so '2011-07-01 06:30:30+00' and '2011-07-01 06:30:30+05' are the same as just '2011-07-01 06:30:30'. For Java developers: it's analogous to java.time.LocalDateTime.

  • TIMESTAMP WITH TIME ZONE stores a point on the UTC time line. How it looks (how many hours, minutes, etc.) depends on your time zone, but it always refers to the same "physical" instant (like the moment of an actual physical event). The input is internally converted to UTC, and that's how it's stored. For that, the offset of the input must be known, so when the input contains no explicit offset or time zone (like '2011-07-01 06:30:30') it's assumed to be in the current time zone of the PostgreSQL session, otherwise the explicitly specified offset or time zone is used (as in '2011-07-01 06:30:30+05'). The output is displayed converted to the current time zone of the PostgreSQL session. For Java developers: It's analogous to java.time.Instant (with lower resolution though), but with JDBC and JPA 2.2 you are supposed to map it to java.time.OffsetDateTime (or to java.util.Date or java.sql.Timestamp of course).

Some say that both TIMESTAMP variations store UTC date-time. Kind of, but it's confusing to put it that way in my opinion. TIMESTAMP WITHOUT TIME ZONE is stored like a TIMESTAMP WITH TIME ZONE, which rendered with UTC time zone happens to give the same year, month, day, hours, minutes, seconds, and microseconds as they are in the local date-time. But it's not meant to represent the point on the time line that the UTC interpretation says, it's just the way the local date-time fields are encoded. (It's some cluster of dots on the time line, as the real time zone is not UTC; we don't know what it is.)

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

__func__ is an implicitly declared identifier that expands to a character array variable containing the function name when it is used inside of a function. It was added to C in C99. From C99 §6.4.2.2/1:

The identifier __func__ is implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration

static const char __func__[] = "function-name";

appeared, where function-name is the name of the lexically-enclosing function. This name is the unadorned name of the function.

Note that it is not a macro and it has no special meaning during preprocessing.

__func__ was added to C++ in C++11, where it is specified as containing "an implementation-de?ned string" (C++11 §8.4.1[dcl.fct.def.general]/8), which is not quite as useful as the specification in C. (The original proposal to add __func__ to C++ was N1642).

__FUNCTION__ is a pre-standard extension that some C compilers support (including gcc and Visual C++); in general, you should use __func__ where it is supported and only use __FUNCTION__ if you are using a compiler that does not support it (for example, Visual C++, which does not support C99 and does not yet support all of C++0x, does not provide __func__).

__PRETTY_FUNCTION__ is a gcc extension that is mostly the same as __FUNCTION__, except that for C++ functions it contains the "pretty" name of the function including the signature of the function. Visual C++ has a similar (but not quite identical) extension, __FUNCSIG__.

For the nonstandard macros, you will want to consult your compiler's documentation. The Visual C++ extensions are included in the MSDN documentation of the C++ compiler's "Predefined Macros". The gcc documentation extensions are described in the gcc documentation page "Function Names as Strings."

How to change the data type of a column without dropping the column with query?

ALTER TABLE YourTableNameHere ALTER COLUMN YourColumnNameHere VARCHAR(20)

jQuery prevent change for select

None of the other answers worked for me, here is what eventually did.

I had to track the previous selected value of the select element and store it in the data-* attribute. Then I had to use the val() method for the select box that JQuery provides. Also, I had to make sure I was using the value attribute in my options when I populated the select box.

<body>
    <select id="sel">
        <option value="Apple">Apple</option>        <!-- Must use the value attribute on the options in order for this to work. -->
        <option value="Bannana">Bannana</option>
        <option value="Cherry">Cherry</option>
    </select>
</body>

<script src="https://code.jquery.com/jquery-3.5.1.js" type="text/javascript" language="javascript"></script>

<script>
    $(document).ready()
    {
        //
        // Register the necessary events.
        $("#sel").on("click", sel_TrackLastChange);
        $("#sel").on("keydown", sel_TrackLastChange);
        $("#sel").on("change", sel_Change);
        
        $("#sel").data("lastSelected", $("#sel").val());
    }
    
    //
    // Track the previously selected value when the user either clicks on or uses the keyboard to change
    // the option in the select box.  Store it in the select box's data-* attribute.
    function sel_TrackLastChange()
    {
        $("#sel").data("lastSelected", $("#sel").val());
    }
    
    //
    // When the option changes on the select box, ask the user if they want to change it.
    function sel_Change()
    {
        if(!confirm("Are you sure?"))
        {
            //
            // If the user does not want to change the selection then use JQuery's .val() method to change
            // the selection back to what it was  previously.
            $("#sel").val($("#sel").data("lastSelected"));
        }
    }
</script>

I hope this can help someone else who has the same problem as I did.

What's the difference between MyISAM and InnoDB?

MYISAM:

  1. MYISAM supports Table-level Locking
  2. MyISAM designed for need of speed
  3. MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS
  4. MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)
  5. MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.
  6. MYISAM supports fulltext search
  7. You can use MyISAM, if the table is more static with lots of select and less update and delete.

INNODB:

  1. InnoDB supports Row-level Locking
  2. InnoDB designed for maximum performance when processing high volume of data
  3. InnoDB support foreign keys hence we call MySQL with InnoDB is RDBMS
  4. InnoDB stores its tables and indexes in a tablespace
  5. InnoDB supports transaction. You can commit and rollback with InnoDB

Android draw a Horizontal line between views

You can put this view between your views to imitate the line

<View
  android:layout_width="fill_parent"
  android:layout_height="2dp"
  android:background="#c0c0c0"/>

including parameters in OPENQUERY

declare @p_Id varchar(10)
SET @p_Id = '40381'

EXECUTE ('BEGIN update TableName
                set     ColumnName1 = null,
                        ColumnName2 = null,
                        ColumnName3 = null,
                        ColumnName4 = null
                 where   PERSONID = '+ @p_Id +'; END;') AT [linked_Server_Name]

Sending command line arguments to npm script

I know there is an approved answer already, but I kinda like this JSON approach.

npm start '{"PROJECT_NAME_STR":"my amazing stuff", "CRAZY_ARR":[0,7,"hungry"], "MAGICAL_NUMBER_INT": 42, "THING_BOO":true}';

Usually I have like 1 var I need, such as a project name, so I find this quick n' simple.

Also I often have something like this in my package.json

"scripts": {
    "start": "NODE_ENV=development node local.js"
}

And being greedy I want "all of it", NODE_ENV and the CMD line arg stuff.

You simply access these things like so in your file (in my case local.js)

console.log(process.env.NODE_ENV, starter_obj.CRAZY_ARR, starter_obj.PROJECT_NAME_STR, starter_obj.MAGICAL_NUMBER_INT, starter_obj.THING_BOO);

You just need to have this bit above it (I'm running v10.16.0 btw)

var starter_obj = JSON.parse(JSON.parse(process.env.npm_config_argv).remain[0]);

Anyhoo, question already answered. Thought I'd share, as I use this method a lot.

How to obtain the chat_id of a private Telegram channel?

You Can Too Do This:

Step 1)Convert Your Private Channel To Public Channel

Step 2)Set The ChannelName For This Channel

Step 3)then you Can change this Channel to Private

Step 4)Now Sending Your Message Using @ChannelName That you Set In Step 3

note:For Step 1 You Can Change One of Your Public Channel To Private For a short time.

How add spaces between Slick carousel item

    /* the slides */
  .slick-slide {
    margin: 0 27px;
  }
  /* the parent */
  .slick-list {
    margin: 0 -27px;
  }

This problem reported as issue (#582) on plugin's github, btw this solution mentioned there too, (https://github.com/kenwheeler/slick/issues/582)

mysqli_fetch_array while loop columns

I think this would be a more simpler way of outputting your results.

Sorry for using my own data should be easy to replace .

$query = "SELECT * FROM category ";

$result = mysqli_query($connection, $query);


    while($row = mysqli_fetch_assoc($result))
    {
        $cat_id = $row['cat_id'];
        $cat_title = $row['cat_title'];

        echo $cat_id . " " . $cat_title  ."<br>";
    }

This would output :

  • -ID Title
  • -1 Gary
  • -2 John
  • -3 Michaels

How to disable right-click context-menu in JavaScript

Capture the onContextMenu event, and return false in the event handler.

You can also capture the click event and check which mouse button fired the event with event.button, in some browsers anyway.

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

I had the same error with Oracle.DataAccess but deploying to Azure Web Sites (azurewebsites.net). For me I had to edit a setting in VS.NET 2019 before publishing to Azure. I ticked the checkbox "Use the 64 bit version of IIS Express for Web sites and projects" which is found under Tools > Options > Projects and Solutions > Web Projects.

How to count the occurrence of certain item in an ndarray?

Numpy has a module for this. Just a small hack. Put your input array as bins.

numpy.histogram(y, bins=y)

The output are 2 arrays. One with the values itself, other with the corresponding frequencies.

Adding a directory to PATH in Ubuntu

you can set it in .bashrc

PATH=$PATH:/opt/ActiveTcl-8.5/bin;export PATH;

SQL Developer with JDK (64 bit) cannot find JVM

I know that people may frown on a youtube example but this worked for me and I was getting the same issue https://www.youtube.com/watch?v=ex1dyu0Px8U

It will direct you to add the correct Environmental Variables for the JDK.

System Properties>Advanced>Environment Variables>Path> \sqldeveloper\jdk\bin AND \sqldeveloper\jdk\bin\server

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

Looks like PostgreSQL supports a schema object called a rule.

http://www.postgresql.org/docs/current/static/rules-update.html

You could create a rule ON INSERT for a given table, making it do NOTHING if a row exists with the given primary key value, or else making it do an UPDATE instead of the INSERT if a row exists with the given primary key value.

I haven't tried this myself, so I can't speak from experience or offer an example.

Creating virtual directories in IIS express

A new option is Jexus Manager for IIS Express,

https://blog.lextudio.com/2014/10/jexus-manager-for-iis-express/

It is just the management tool you know how to use.

Regular expression to match standard 10 digit phone number

Here's a fairly compact one I created.

Search: \+?1?\s*\(?-*\.*(\d{3})\)?\.*-*\s*(\d{3})\.*-*\s*(\d{4})$

Replace: +1 \($1\) $2-$3

Tested against the following use cases.

18001234567
1 800 123 4567
1-800-123-4567
+18001234567
+1 800 123 4567
+1 (800) 123 4567
1(800)1234567
+1800 1234567
1.8001234567
1.800.123.4567
1--800--123--4567
+1 (800) 123-4567

How can I stop Chrome from going into debug mode?

For anyone that's searching why their chrome debugger is automatically jumping to sources tab on every page load, event though all of the breakpoints/pauses/etc have been disabled.

For me it was the "breakOnLoad": true line in VS Code launch.json config.

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

You can put this inside your jquery code or it can stand alone:

window.onload = prep;

function prep(){
document.getElementById('somediv').onclick = function(){
document.getElementById('inputField').value ='';
  }
}

builtins.TypeError: must be str, not bytes

Convert binary file to base64 & vice versa. Prove in python 3.5.2

import base64

read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()

b64 = base64.b64encode(data)

print (b64)

# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)

# Test in python 3.5.2

Build query string for System.Net.HttpClient get

Since I have to reuse this few time, I came up with this class that simply help to abstract how the query string is composed.

public class UriBuilderExt
{
    private NameValueCollection collection;
    private UriBuilder builder;

    public UriBuilderExt(string uri)
    {
        builder = new UriBuilder(uri);
        collection = System.Web.HttpUtility.ParseQueryString(string.Empty);
    }

    public void AddParameter(string key, string value) {
        collection.Add(key, value);
    }

    public Uri Uri{
        get
        {
            builder.Query = collection.ToString();
            return builder.Uri;
        }
    }

}

The use will be simplify to something like this:

var builder = new UriBuilderExt("http://example.com/");
builder.AddParameter("foo", "bar<>&-baz");
builder.AddParameter("bar", "second");
var uri = builder.Uri;

that will return the uri: http://example.com/?foo=bar%3c%3e%26-baz&bar=second

How To Execute SSH Commands Via PHP

I've had a hard time with ssh2 in php mostly because the output stream sometimes works and sometimes it doesn't. I'm just gonna paste my lib here which works for me very well. If there are small inconsistencies in code it's because I have it plugged in a framework but you should be fine porting it:

<?php

class Components_Ssh {

    private $host;

    private $user;

    private $pass;

    private $port;

    private $conn = false;

    private $error;

    private $stream;

    private $stream_timeout = 100;

    private $log;

    private $lastLog;

    public function __construct ( $host, $user, $pass, $port, $serverLog ) {
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->port = $port;
        $this->sLog = $serverLog;

        if ( $this->connect ()->authenticate () ) {
            return true;
        }
    }

    public function isConnected () {
        return ( boolean ) $this->conn;
    }

    public function __get ( $name ) {
        return $this->$name;
    }

    public function connect () {
        $this->logAction ( "Connecting to {$this->host}" );
        if ( $this->conn = ssh2_connect ( $this->host, $this->port ) ) {
            return $this;
        }
        $this->logAction ( "Connection to {$this->host} failed" );
        throw new Exception ( "Unable to connect to {$this->host}" );
    }

    public function authenticate () {
        $this->logAction ( "Authenticating to {$this->host}" );
        if ( ssh2_auth_password ( $this->conn, $this->user, $this->pass ) ) {
            return $this;
        }
        $this->logAction ( "Authentication to {$this->host} failed" );
        throw new Exception ( "Unable to authenticate to {$this->host}" );
    }

    public function sendFile ( $localFile, $remoteFile, $permision = 0644 ) {
        if ( ! is_file ( $localFile ) ) throw new Exception ( "Local file {$localFile} does not exist" );
        $this->logAction ( "Sending file $localFile as $remoteFile" );

        $sftp = ssh2_sftp ( $this->conn );
        $sftpStream = @fopen ( 'ssh2.sftp://' . $sftp . $remoteFile, 'w' );
        if ( ! $sftpStream ) {
            //  if 1 method failes try the other one
            if ( ! @ssh2_scp_send ( $this->conn, $localFile, $remoteFile, $permision ) ) {
                throw new Exception ( "Could not open remote file: $remoteFile" );
            }
            else {
                return true;
            }
        }

        $data_to_send = @file_get_contents ( $localFile );

        if ( @fwrite ( $sftpStream, $data_to_send ) === false ) {
            throw new Exception ( "Could not send data from file: $localFile." );
        }

        fclose ( $sftpStream );

        $this->logAction ( "Sending file $localFile as $remoteFile succeeded" );
        return true;
    }

    public function getFile ( $remoteFile, $localFile ) {
        $this->logAction ( "Receiving file $remoteFile as $localFile" );
        if ( ssh2_scp_recv ( $this->conn, $remoteFile, $localFile ) ) {
            return true;
        }
        $this->logAction ( "Receiving file $remoteFile as $localFile failed" );
        throw new Exception ( "Unable to get file to {$remoteFile}" );
    }

    public function cmd ( $cmd, $returnOutput = false ) {
        $this->logAction ( "Executing command $cmd" );
        $this->stream = ssh2_exec ( $this->conn, $cmd );

        if ( FALSE === $this->stream ) {
            $this->logAction ( "Unable to execute command $cmd" );
            throw new Exception ( "Unable to execute command '$cmd'" );
        }
        $this->logAction ( "$cmd was executed" );

        stream_set_blocking ( $this->stream, true );
        stream_set_timeout ( $this->stream, $this->stream_timeout );
        $this->lastLog = stream_get_contents ( $this->stream );

        $this->logAction ( "$cmd output: {$this->lastLog}" );
        fclose ( $this->stream );
        $this->log .= $this->lastLog . "\n";
        return ( $returnOutput ) ? $this->lastLog : $this;
    }

    public function shellCmd ( $cmds = array () ) {
        $this->logAction ( "Openning ssh2 shell" );
        $this->shellStream = ssh2_shell ( $this->conn );

        sleep ( 1 );
        $out = '';
        while ( $line = fgets ( $this->shellStream ) ) {
            $out .= $line;
        }

        $this->logAction ( "ssh2 shell output: $out" );

        foreach ( $cmds as $cmd ) {
            $out = '';
            $this->logAction ( "Writing ssh2 shell command: $cmd" );
            fwrite ( $this->shellStream, "$cmd" . PHP_EOL );
            sleep ( 1 );
            while ( $line = fgets ( $this->shellStream ) ) {
                $out .= $line;
                sleep ( 1 );
            }
            $this->logAction ( "ssh2 shell command $cmd output: $out" );
        }

        $this->logAction ( "Closing shell stream" );
        fclose ( $this->shellStream );
    }

    public function getLastOutput () {
        return $this->lastLog;
    }

    public function getOutput () {
        return $this->log;
    }

    public function disconnect () {
        $this->logAction ( "Disconnecting from {$this->host}" );
        // if disconnect function is available call it..
        if ( function_exists ( 'ssh2_disconnect' ) ) {
            ssh2_disconnect ( $this->conn );
        }
        else { // if no disconnect func is available, close conn, unset var
            @fclose ( $this->conn );
            $this->conn = false;
        }
        // return null always
        return NULL;
    }

    public function fileExists ( $path ) {
        $output = $this->cmd ( "[ -f $path ] && echo 1 || echo 0", true );
        return ( bool ) trim ( $output );
    }
}

Changing the default icon in a Windows Forms application

Select your project properties from Project Tab Then Application->Resource->Icon And Manifest->change the default icon

This works in Visual studio 2019 finely Note:Only files with .ico format can be added as icon

How do I get the information from a meta tag with JavaScript?

function getMetaContentByName(name,content){
   var content = (content==null)?'content':content;
   return document.querySelector("meta[name='"+name+"']").getAttribute(content);
}

Used in this way:

getMetaContentByName("video");

The example on this page:

getMetaContentByName("twitter:domain");

How can I convert String to Int?

You also may use an extension method, so it will be more readable (although everybody is already used to the regular Parse functions).

public static class StringExtensions
{
    /// <summary>
    /// Converts a string to int.
    /// </summary>
    /// <param name="value">The string to convert.</param>
    /// <returns>The converted integer.</returns>
    public static int ParseToInt32(this string value)
    {
        return int.Parse(value);
    }

    /// <summary>
    /// Checks whether the value is integer.
    /// </summary>
    /// <param name="value">The string to check.</param>
    /// <param name="result">The out int parameter.</param>
    /// <returns>true if the value is an integer; otherwise, false.</returns>
    public static bool TryParseToInt32(this string value, out int result)
    {
        return int.TryParse(value, out result);
    }
}

And then you can call it that way:

  1. If you are sure that your string is an integer, like "50".

    int num = TextBoxD1.Text.ParseToInt32();
    
  2. If you are not sure and want to prevent crashes.

    int num;
    if (TextBoxD1.Text.TryParseToInt32(out num))
    {
        //The parse was successful, the num has the parsed value.
    }
    

To make it more dynamic, so you can parse it also to double, float, etc., you can make a generic extension.

Windows command prompt log to a file

In cmd when you use > or >> the output will be only written on the file. Is it possible to see the output in the cmd windows and also save it in a file. Something similar if you use teraterm, when you can start saving all the log in a file meanwhile you use the console and view it (only for ssh, telnet and serial).

ValueError: unsupported format character while forming strings

For anyone checking this using python 3:

If you want to print the following output "100% correct":

python 3.8: print("100% correct")
python 3.7 and less: print("100%% correct")


A neat programming workaround for compatibility across diff versions of python is shown below:

Note: If you have to use this, you're probably experiencing many other errors... I'd encourage you to upgrade / downgrade python in relevant machines so that they are all compatible.

DevOps is a notable exception to the above -- implementing the following code would indeed be appropriate for specific DevOps / Debugging scenarios.

import sys

if version_info.major==3:
    if version_info.minor>=8:
        my_string = "100% correct"
    else:
        my_string = "100%% correct"

# Finally
print(my_string)

How to iterate over a column vector in Matlab?

If you just want to apply a function to each element and put the results in an output array, you can use arrayfun.

As others have pointed out, for most operations, it's best to avoid loops in MATLAB and vectorise your code instead.

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

Explicitly mention the ubuntu version in the docker file which you are trying to RUN,

FROM ubuntu:14.04

Dont use like FROM ubuntu:Latest. This resolved my above "Cannot Start Container: stat /bin/sh: no such file or directory" issue

When to use the JavaScript MIME type application/javascript instead of text/javascript?

application because .js-Files aren't something a user wants to read but something that should get executed.

How to vertically center <div> inside the parent element with CSS?

I'm pretty late to the party, but I came up with this myself and it's one of my favorite quick hacks for vertical alignment. It's crazy simple, and easy to understand what's going on.

You use the :before css attribute to insert a div into the beginning of the parent div, give it display:inline-block and vertical-align:middle and then give those same properties to the child div. Since vertical-align is for alignment along a line, those inline divs will be considered a line.

Make the :before div height:100%, and the child div will automatically follow and align in the middle of a very tall "line."

.parent:before, .child {
    display:inline-block;
    vertical-align:middle;
}
.parent:before {
    content:""; // so that it shows up
    height:100%; // so it takes up the full height
}

Here's a fiddle to demonstrate what I'm talking about. The child div can be any height, and you never have to modify its margins/paddings.
And here's a more explanatory fiddle.

If you're not fond of :before, you can always manually put in a div.

<div class="parent">
    <div class="before"></div>
    <div class="child">
        content
    </div>
</div>

And then just reassign .parent:before to .parent .before

Text file with 0D 0D 0A line breaks

This typically stems from a bug in revision control system, or similar. This was a product from CVS, if a file was checked in from Windows to Unix server, and then checked out again...

In other words, it is just broken...

Good examples of python-memcache (memcached) being used in Python?

A good rule of thumb: use the built-in help system in Python. Example below...

jdoe@server:~$ python
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memcache
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'memcache']
>>> help(memcache)

------------------------------------------
NAME
    memcache - client module for memcached (memory cache daemon)

FILE
    /usr/lib/python2.7/dist-packages/memcache.py

MODULE DOCS
    http://docs.python.org/library/memcache

DESCRIPTION
    Overview
    ========

    See U{the MemCached homepage<http://www.danga.com/memcached>} for more about memcached.

    Usage summary
    =============
...
------------------------------------------

What are the differences between a superkey and a candidate key?

Superkey :A set of attributes or combination of attributes which uniquely identify the tuple in a given relation . Superkey have two properties uniqueness and reducible set

Candidate key: Minimal set of superkey which have following two properties: uniqueness and irreducible set or attribute

IN vs OR in the SQL WHERE Clause

The best way to find out is looking at the Execution Plan.


I tried it with Oracle, and it was exactly the same.

CREATE TABLE performance_test AS ( SELECT * FROM dba_objects );

SELECT * FROM performance_test
WHERE object_name IN ('DBMS_STANDARD', 'DBMS_REGISTRY', 'DBMS_LOB' );

Even though the query uses IN, the Execution Plan says that it uses OR:

--------------------------------------------------------------------------------------    
| Id  | Operation         | Name             | Rows  | Bytes | Cost (%CPU)| Time     |    
--------------------------------------------------------------------------------------    
|   0 | SELECT STATEMENT  |                  |     8 |  1416 |   163   (2)| 00:00:02 |    
|*  1 |  TABLE ACCESS FULL| PERFORMANCE_TEST |     8 |  1416 |   163   (2)| 00:00:02 |    
--------------------------------------------------------------------------------------    

Predicate Information (identified by operation id):                                       
---------------------------------------------------                                       

   1 - filter("OBJECT_NAME"='DBMS_LOB' OR "OBJECT_NAME"='DBMS_REGISTRY' OR                
              "OBJECT_NAME"='DBMS_STANDARD')                                              

On duplicate key ignore?

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

I got a similar problem with sql server , I have tried every thing but does not connect to database engine & it shows error:26.

  • First check if the database engine is running or not. by going into configuration manager. start > sql server >sql server configuration manager. On the right pane you should see the sql server (mss .. ) should be running state with a green indication.
  • IF the database engine is not running, simply uninstall sql server / format your system if possible and then download sql server 2012 and management studio. from
    https://www.microsoft.com/en-ca/download/details.aspx?id=29062

  • Install server first, make sure to add server on installation phase
    by clicking add server and then install management studio.

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

multipart/form-data

Note. Please consult RFC2388 for additional information about file uploads, including backwards compatibility issues, the relationship between "multipart/form-data" and other content types, performance issues, etc.

Please consult the appendix for information about security issues for forms.

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

The content type "multipart/form-data" follows the rules of all multipart MIME data streams as outlined in RFC2045. The definition of "multipart/form-data" is available at the [IANA] registry.

A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.

As with all multipart MIME types, each part has an optional "Content-Type" header that defaults to "text/plain". User agents should supply the "Content-Type" header, accompanied by a "charset" parameter.

application/x-www-form-urlencoded

This is the default content type. Forms submitted with this content type must be encoded as follows:

Control names and values are escaped. Space characters are replaced by +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A'). The control names/values are listed in the order they appear in the document. The name is separated from the value by=' and name/value pairs are separated from each other by `&'.

application/x-www-form-urlencoded the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

Execute action when back bar button of UINavigationController is pressed

I accomplished this by calling/overriding viewWillDisappear and then accessing the stack of the navigationController like this:

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    let stack = self.navigationController?.viewControllers.count

    if stack >= 2 {
        // for whatever reason, the last item on the stack is the TaskBuilderViewController (not self), so we only use -1 to access it
        if let lastitem = self.navigationController?.viewControllers[stack! - 1] as? theViewControllerYoureTryingToAccess {
            // hand over the data via public property or call a public method of theViewControllerYoureTryingToAccess, like
            lastitem.emptyArray()
            lastitem.value = 5
        }
    }
}

How to load GIF image in Swift?

Load GIF image Swift :

## Reference.

#1 : Copy the swift file from This Link :

#2 : Load GIF image Using Name

    let jeremyGif = UIImage.gifImageWithName("funny")
    let imageView = UIImageView(image: jeremyGif)
    imageView.frame = CGRect(x: 20.0, y: 50.0, width: self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView)

#3 : Load GIF image Using Data

    let imageData = try? Data(contentsOf: Bundle.main.url(forResource: "play", withExtension: "gif")!)
    let advTimeGif = UIImage.gifImageWithData(imageData!)
    let imageView2 = UIImageView(image: advTimeGif)
    imageView2.frame = CGRect(x: 20.0, y: 220.0, width: 
    self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView2)

#4 : Load GIF image Using URL

    let gifURL : String = "http://www.gifbin.com/bin/4802swswsw04.gif"
    let imageURL = UIImage.gifImageWithURL(gifURL)
    let imageView3 = UIImageView(image: imageURL)
    imageView3.frame = CGRect(x: 20.0, y: 390.0, width: self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView3)

Download Demo Code

OUTPUT :

iPhone 8 / iOS 11 / xCode 9

enter image description here

HTML Input Box - Disable

The syntax to disable an HTML input is as follows:

<input type="text" id="input_id" DISABLED />

How to enable assembly bind failure logging (Fusion) in .NET

For those who are a bit lazy, I recommend running this as a bat file for when ever you want to enable it:

reg add "HKLM\Software\Microsoft\Fusion" /v EnableLog /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v ForceLog /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogFailures /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogResourceBinds /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogPath /t REG_SZ /d C:\FusionLog\

if not exist "C:\FusionLog\" mkdir C:\FusionLog

SQL JOIN vs IN performance?

Generally speaking, IN and JOIN are different queries that can yield different results.

SELECT  a.*
FROM    a
JOIN    b
ON      a.col = b.col

is not the same as

SELECT  a.*
FROM    a
WHERE   col IN
        (
        SELECT  col
        FROM    b
        )

, unless b.col is unique.

However, this is the synonym for the first query:

SELECT  a.*
FROM    a
JOIN    (
        SELECT  DISTINCT col
        FROM    b
        )
ON      b.col = a.col

If the joining column is UNIQUE and marked as such, both these queries yield the same plan in SQL Server.

If it's not, then IN is faster than JOIN on DISTINCT.

See this article in my blog for performance details:

Add to integers in a list

Here is an example where the things to add come from a dictionary

>>> L = [0, 0, 0, 0]
>>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1})
>>> for item in things_to_add:
...     L[item['idx']] += item['amount']
... 
>>> L
[0, 1, 1, 0]

Here is an example adding elements from another list

>>> L = [0, 0, 0, 0]
>>> things_to_add = [0, 1, 1, 0]
>>> for idx, amount in enumerate(things_to_add):
...     L[idx] += amount
... 
>>> L
[0, 1, 1, 0]

You could also achieve the above with a list comprehension and zip

L[:] = [sum(i) for i in zip(L, things_to_add)]

Here is an example adding from a list of tuples

>>> things_to_add = [(1, 1), (2, 1)]
>>> for idx, amount in things_to_add:
...     L[idx] += amount
... 
>>> L
[0, 1, 1, 0]

What does AND 0xFF do?

& 0xFF by itself only ensures that if bytes are longer than 8 bits (allowed by the language standard), the rest are ignored.

And that seems to work fine too?

If the result ends up greater than SHRT_MAX, you get undefined behavior. In that respect both will work equally poorly.

ORA-28040: No matching authentication protocol exception

I was using eclipse and after trying all the other answers it didn't work for me. In the end, what worked for me was moving the ojdb7.jar to top in the Build Path. This occurs when multiple jars have conflicting same classes.

  1. Select project in Project Explorer
  2. Right click on Project -> Build Path -> Configure Build Path
  3. Go to Order and Export tab and select ojdbc.jar
  4. Click button TOP to move it to top

Moving Panel in Visual Studio Code to right side

You can do the same in insider's edition, There is an option on right top corner to switch to the panel to sidebar https://code.visualstudio.com/insiders/

terminal at the bottom side terminal in the bottom side

terminal at the right side terminal in the right side

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

I have encountered this issue with play-services:5.0.89. Upgrading to 6.1.11 solved problem.

SCRIPT5: Access is denied in IE9 on xmlhttprequest

Open the Internet Explorer Developer Tool, Tools -> F12 developer tools. (I think you can also press F12 to get it)

Change the Document Mode to Standards. (The page should be automatically refresh, if you change the Document Mode)

Problem should be fixed. Enjoy

Delete all rows in an HTML table

this is a simple code I just wrote to solve this, without removing the header row (first one).

var Tbl = document.getElementById('tblId');
while(Tbl.childNodes.length>2){Tbl.removeChild(Tbl.lastChild);}

Hope it works for you!!.

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

Try this:

$Wsdl = 'http://xxxx.xxx.xx/webservice3.asmx?WSDL';
libxml_disable_entity_loader(false); //adding this worked for me
$Client = new SoapClient($Wsdl);
//Code...

How to automatically select all text on focus in WPF TextBox?

I have a slightly simplified answer for this (with just the PreviewMouseLeftButtonDown event) which seems to mimic the usual functionality of a browser:

In XAML you have a TextBox say:

<TextBox Text="http://www.blabla.com" BorderThickness="2" BorderBrush="Green" VerticalAlignment="Center" Height="25"
                 PreviewMouseLeftButtonDown="SelectAll" />

In codebehind:

private void SelectAll(object sender, MouseButtonEventArgs e)
{
    TextBox tb = (sender as TextBox);

    if (tb == null)
    {
        return;
    }

    if (!tb.IsKeyboardFocusWithin)
    {
        tb.SelectAll();
        e.Handled = true;
        tb.Focus();
    }
}

Kill tomcat service running on any port, Windows

1) Go to (Open) Command Prompt (Press Window + R then type cmd Run this).

2) Run following commands

For all listening ports

netstat -aon | find /i "listening"

Apply port filter

netstat -aon |find /i "listening" |find "8080"

Finally with the PID we can run the following command to kill the process

3) Copy PID from result set

taskkill /F /PID

Ex: taskkill /F /PID 189

Sometimes you need to run Command Prompt with Administrator privileges

Done !!! you can start your service now.

Error: Cannot invoke an expression whose type lacks a call signature

Add a type to your variable and then return.

Eg:

const myVariable : string [] = ['hello', 'there'];

const result = myVaraible.map(x=> {
  return
  {
    x.id
  }
});

=> Important part is adding the string[] type etc:

How Do I Uninstall Yarn

If you are still getting errors after deleting ~/.yarn about files not being found, don't forget to delete the yarn rc file:

rm ~/.yarnrc.yml 

Selenium webdriver click google search

Simple Xpath for locating Google search box is: Xpath=//span[text()='Google Search']

PHP Header redirect not working

Don't include header.php. You should not output HTML when you are going to redirect.

Make a new file, eg. "pre.php". Put this in it:

<?php
include('class.user.php');
include('class.Connection.php');
?>

Then in header.php, include that, in stead of including the two other files. In form.php, include pre.php in stead of header.php.

Google Map API v3 ~ Simply Close an infowindow?

With the v3 API, you can easily close the InfoWindow with the InfoWindow.close() method. You simply need to keep a reference to the InfoWindow object that you are using. Consider the following example, which opens up an InfoWindow and closes it after 5 seconds:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
  <title>Google Maps API InfoWindow Demo</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 400px; height: 500px;"></div>

  <script type="text/javascript">
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: new google.maps.LatLng(-25.36388, 131.04492),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var marker = new google.maps.Marker({
      position: map.getCenter(),
      map: map
    });

    var infowindow = new google.maps.InfoWindow({
      content: 'An InfoWindow'
    });

    infowindow.open(map, marker);

    setTimeout(function () { infowindow.close(); }, 5000);
  </script>
</body>
</html>

If you have a separate InfoWindow object for each Marker, you may want to consider adding the InfoWindow object as a property of your Marker objects:

var marker = new google.maps.Marker({
  position: map.getCenter(),
   map: map
});

marker.infowindow = new google.maps.InfoWindow({
  content: 'An InfoWindow'
});

Then you would be able to open and close that InfoWindow as follows:

marker.infowindow.open(map, marker);
marker.infowindow.close();

The same applies if you have an array of markers:

var markers = [];

marker[0] = new google.maps.Marker({
  position: map.getCenter(),
   map: map
});

marker[0].infowindow = new google.maps.InfoWindow({
  content: 'An InfoWindow'
});

// ...

marker[0].infowindow.open(map, marker);
marker[0].infowindow.close();